Text Animation Smooth in Chrome but Stuck and Not Smooth in Safari and iOS Devices

I’m working on a website with a text animation that looks smooth and performs well in Chrome. However, the same animation appears stuck and not smooth in Safari and on iOS devices.

Here’s a brief overview of the setup:

The animation is applied to a h1 element using CSS keyframes.
I’m using -webkit-animation for Safari and iOS support.
The animation involves transforming and opacity changes.
CSS Code:

.hero-scroll {
  position: absolute;
  top: 35%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 6rem;
  font-weight: bold;
  transition: transform 0.7s ease, font-size 0.7s ease, top 0.7s ease, color 0.7s ease;
  z-index: 2;
  color: rgba(255, 255, 255, 0.3);
  letter-spacing: 0.5px;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-rendering: optimizeLegibility;
  -webkit-text-stroke: 0.5px transparent;
  text-shadow: 0px 0px 1px rgba(0, 0, 0, 0.1);
}

@-webkit-keyframes keyarm {
  0% { -webkit-transform: rotate(0deg); }
  5% { -webkit-transform: rotate(-14deg); }
  10% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(0deg); }
}

@keyframes keyarm {
  0% { transform: rotate(0deg); }
  5% { transform: rotate(-14deg); }
  10% { transform: rotate(0deg); }
  100% { transform: rotate(0deg); }
}

.sticky {
  position: fixed;
  top: 5%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 2rem;
  color: #000;
  z-index: 1001;
  transition: top 0.7s ease, font-size 0.7s ease, color 0.7s ease;
  user-select: none;
  -webkit-animation: keyarm 1.5s ease-in-out infinite;
  animation: keyarm 1.5s ease-in-out infinite;
}

React Component Code:

import React, { forwardRef } from 'react';

const HeroSection = forwardRef((props, ref) => {
    return (
        <div className="hero-section">
            <div className="hero-image-left">
                <h1 className="hero-scroll" ref={ref}>ATNATIC</h1>
                <div className="video-container">
                    <video 
                        src="/Static/Models/Refercopy.mp4" 
                        autoPlay 
                        loop 
                        muted
                        playsInline
                        className="hero-video"
                    />
                </div>
            </div>
        </div>
    );
});

export default HeroSection;

App.js


    const handleScroll = () => {
        const header = headerRef.current;
        const heroText = heroTextRef.current;
        const threshold = header ? header.offsetHeight : 0;
    
        if (header) {
            if (window.scrollY > threshold) {
                header.classList.add('visible');
                header.classList.remove('pre-scroll');
            } else {
                header.classList.remove('visible');
                header.classList.add('pre-scroll');
            }
        }
    
        if (heroText) {
            if (window.scrollY >= threshold) {
                heroText.classList.add('sticky');
            } else {
                heroText.classList.remove('sticky');
            }
        }
    };

Problem:
The animation works well in Chrome but is not smooth in Safari and iOS devices. It appears stuck or choppy.

What I’ve Tried:

Added -webkit- prefixes for better support in Safari.
Ensured the will-change property is set.
Verified the issue persists on different devices.

Any suggestions on how to make the animation smoother across all browsers, especially Safari and iOS devices?

Luxon DateTime not recognized as Luxon DateTime object

I am not understanding how Luxon works…
I am using Redux Toolkit. I initialize the state like this

import {DateTime} from "luxon"

interface TestStateProps {
    startDate: DateTime,
    endDate: DateTime,
}

const initialTestState: TestStateProps {
    startDate: DateTime.now(), 
    endDate: DateTime.now(),
}

export const testSlice = createSlice({
    name: 'test',
    initialTestState,
    reducers: {
        addDay: (state, action: PayloadAction<number>) => {
            console.log(state.startDate instanceof DateTime)
            console.log(JSON.stringify(state.startDate))
            console.log(state.startDate.plus({days: action.payload }))
        }
    }
})

And now, the result of the console.log is quite unexpected

  1. console.log(state.startDate instanceof DateTime)

false

Why is it false? I initialized it with DateTime.now()

  1. console.log(JSON.stringify(state.startDate))

{“ts”:1724911978667,”_zone”:{},”loc”:{“locale”:”en-DE”,”numberingSystem”:null,”outputCalendar”:null,”weekSettings”:null,”intl”:”en-DE”,”weekdaysCache”:{“format”:{},”standalone”:{}},”monthsCache”:{“format”:{},”standalone”:{}},”meridiemCache”:null,”eraCache”:{},”specifiedLocale”:null,”fastNumbersCached”:null},”invalid”:null,”weekData”:null,”localWeekData”:null,”c”:{“year”:2024,”month”:8,”day”:29,”hour”:8,”minute”:12,”second”:58,”millisecond”:667},”o”:120,”isLuxonDateTime”:true}

I guess this is expected "isLuxonDateTime":true. Why is state.startDate instanceof DateTime returning false? When I check in the redux dev tools, its not deserialzed or something

Redux Tdev tools Screenshot

  1. console.log(state.startDate.plus({days: action.payload })) finally throws an error

Uncaught TypeError: state.startDate.plus is not a function

What am I doing wrong here?

Trap Focus Inside the Modal – Accessibility

I am trying to do when the modal opens, focus should move to the first focusable element inside the modal (like the close button. Also while the modal is open, users should only be able to navigate between elements inside the modal using the Tab key.

I have tried below code. But it traps in modal but after some tabs it go to the browser’s address bar.

<!DOCTYPE html>
<html lang="en">

<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <style>
      .modal {
         display: none;
         position: fixed;
         left: 50%;
         top: 50%;
         transform: translate(-50%, -50%);
         width: 250px;
         height: auto;
         z-index: 999;
         background-color: aliceblue;
      }
   </style>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
   <button class="openModal">Open Modal</button>
   <div class="modal">
      <button class="closeModal">Close Modal</button>
      <h4>Text here</h4>
      <a href="/main-page">Link to Main page</a>
   </div>

   <a href="/home">Home</a>
   <a href="/about">About</a>

   <script>
      $(document).on('click', '.openModal', function (e) {
         $('.modal').fadeIn();
         $('button').attr('tabindex', '-1');
         $('a').attr('tabindex', '-1');
         $('.modal button').removeAttr('tabindex',);
         $('.modal a').removeAttr('tabindex',);
      });

      $(document).on('click', '.closeModal', function (e) {
         $('.modal').fadeOut();
         $('button').removeAttr('tabindex',);
         $('a').removeAttr('tabindex',);
      });
   </script>
</body>
</html>

Issue with Inserting Multiple Subjects into a Database Using PHP and JavaScript

I’m working on a form where users can enter multiple subjects (courses), and I need to save this data into a MySQL database using PHP. The form allows users to dynamically add multiple subjects, and each subject includes fields like course code, course name, course marks, grade, course hours, and instructor name.

However, I’m encountering an issue where only the last subject is being inserted into the database. I need help to ensure that all subjects are correctly inserted.

enter image description here

// Inserting each course for the student
$rowCounter = 1;

while (isset($_POST["c-code-$rowCounter"])) {
    $c_code = $_POST["c-code-$rowCounter"];
    $c_name = $_POST["c-name-$rowCounter"];
    $c_marks = $_POST["c-marks-$rowCounter"];
    $grade = $_POST["grade-$rowCounter"];
    $c_hours = $_POST["c-hours-$rowCounter"];
    $i_name = $_POST["i-name-$rowCounter"];
    
    $sql = "INSERT INTO Courses (student_id, course_code, course_name, course_marks, grade, course_hours, instructor_name) 
            VALUES ('$student_id', '$c_code', '$c_name', '$c_marks', '$grade', '$c_hours', '$i_name')";

    if ($conn->query($sql) === FALSE) {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $rowCounter++;
}

$conn->close();
echo "Submitted Successfull";
  • I expected the form to submit all dynamically added subject rows with unique data for each row.
  • I expected that each course entry would be inserted into the Courses table with the correct student_id and corresponding course details. Specifically, all rows added to the form should be processed and saved into the database, not just the last row.

How to optimize large KMZ file on map in react js?

I have more than 100 200 files on google map. Its start lagging and stuck the map.

The method i already implemented and tested are

  1. throttledFetchKmzData
  2. debouncedFetchKmzData
  3. lazy laoding and cluster loading
  4. togeojson – NPM and Web Workers
    But nothing is working. How to optimize large KMZ file on map in react js?

Javascript fetch request returning empty [closed]

I am currently working on the CS50W Network project, and implementing the loading of all posts via API (path is created). When accessing the JsonResponse data directly through the path in the search bar, all data shows up as expected, but when using fetch to access the same data in Javascript, no response is received.

Below is the code:

document.addEventListener('DOMContentLoaded', ()=>{

    // Default: Load All posts (Page 1)
    load_posts('all', 1);
});



function load_posts(page_type, page_num){

    document.querySelector('#all-posts').innerHTML = "";

    // Loads all posts
    fetch(`/Load/Posts/all/1`)
    .then(response => response.json())
    .then(data => {
        let posts = data.responce;
        let direction = data.direction;
        console.log(posts);

        posts.forEach(post => {
            const new_post_div = document.createElement('div');
            new_post_div.className = 'card-post';
            
            new_post_div.innerHTML = `
            <h3>${post.user}</h3>
            <button href="#" id="edit">Edit</button>
            <div id="display_contents">
                <p>${post.content}</p>
            </div>
            <div id="timestamp" style="color:#d3d3d3">${post.timestamp}</div>
            <div id="likes-container">
                <button id="like-button" onclick=like_post(${post.id})><h3 style="color:#d4d4d4">&hearts;</h3></button>
                <span>${post.likes}</span>
            </div>
            `;
            document.querySelector("#all-posts").appendChild(new_post_div);
        });
    });

}

Here is the Python view that sends the JsonResponse data:

def load_posts(request, page_type, page_num):
    current_user = request.user

    # Determining type of page
    if page_type == 'all' :
        posts = Post.objects.all()
    elif page_type == 'following':
        profile = Profile.objects.filter(user=current_user)
        followings = profile.following
        posts = Post.objects.filter(user__in=followings)
    elif page_type == 'user':
        posts = Post.objects.filter(user=current_user)
        posts = posts.order_by('-timestamp')
    else:
        return JsonResponse({'error':'Invalid Request!'}, status=200)
    
    #Pagination
    p = Paginator(posts, 10)
    page = p.page(page_num)
    pages = p.num_pages
    
    response = [post.serialize() for post in page]

    prev = next = fwd = bwd = False

    if page.has_next():
        next = page.next_page_number()
        if page_num < pages:
            fwd = True
    
    if page.has_previous():
        prev = page.previous_page_number()
        if page_num > 1:
            bwd = True

    direction = {
        'prev':prev,
        'next':next,
        'fwd':fwd,
        'bwd':bwd
    }


    return JsonResponse({
        'response':response,
        'direction':direction
    })```

Custom block registered within custom category in WordPress is not showing in admin end

I am developing a custom theme in which I am trying to include some custom blocks by registering a custom block category. But it is not showing in the admin end.
Though when I execute the command it executes properly without any error.

npm run dev

I might be missing something which I am still not getting. Below is the code:

Package dependencies:

"devDependencies": {
    "@babel/core": "^7.25.2",
    "@babel/preset-env": "^7.25.3",
    "@babel/preset-react": "^7.24.7",
    "@svgr/cli": "^8.1.0",
    "@wordpress/base-styles": "^5.4.0",
    "@wordpress/block-editor": "^13.4.0",
    "@wordpress/blocks": "^13.4.0",
    "@wordpress/components": "^28.4.0",
    "@wordpress/compose": "^7.4.0",
    "@wordpress/data": "^10.4.0",
    "@wordpress/dependency-extraction-webpack-plugin": "^6.4.0",
    "@wordpress/element": "^6.4.0",
    "@wordpress/eslint-plugin": "^20.1.0",
    "@wordpress/hooks": "^4.4.0",
    "@wordpress/i18n": "^5.4.0",
    "@wordpress/icons": "^10.4.0",
    "@wordpress/scripts": "^27.9.0",
    "@wordpress/server-side-render": "^5.4.0",
    "babel-loader": "^9.1.3",
    "clean-webpack-plugin": "^4.0.0",
    "cross-env": "^7.0.3",
    "css-loader": "^7.1.2",
    "css-minimizer-webpack-plugin": "^7.0.0",
    "file-loader": "^6.2.0",
    "lodash": "^4.17.21",
    "mini-css-extract-plugin": "^2.9.0",
    "sass-loader": "^16.0.0",
    "sass-mq": "^5.0.1",
    "style-loader": "^4.0.0",
    "uglifyjs-webpack-plugin": "^2.2.0",
    "webpack": "^5.93.0",
    "webpack-cli": "^5.1.4"
  },
  "dependencies": {
    "@wordpress/babel-preset-default": "^8.5.0",
    "sass": "^1.77.8"
  }

Build Paths for JS and CSS:

if( ! defined( 'NINTYNINE_BUILD_JS_URI' ) ){
   define( 'NINTYNINE_BUILD_JS_URI', untrailingslashit( get_template_directory_uri() ) . '/assets/build/js' );
}

if( ! defined( 'NINTYNINE_BUILD_CSS_URI' ) ){
   define( 'NINTYNINE_BUILD_CSS_URI', untrailingslashit( get_template_directory_uri() ) . '/assets/build/css' );
}

if( ! defined( 'NINTYNINE_BUILD_CSS_DIR_PATH' ) ){
   define( 'NINTYNINE_BUILD_CSS_DIR_PATH', untrailingslashit( get_template_directory() ) . '/assets/build/css' );
}

assets.php file inside build folder:

<?php return [
    "js/main.js" => [
        "dependencies" => ["wp-polyfill"],
        "version" => "4d1ec442c34233d2338a",
    ],
    "js/single.js" => [
        "dependencies" => ["wp-polyfill"],
        "version" => "cf309fb462d151e0903f",
    ],
    "js/editor.js" => [
        "dependencies" => ["wp-polyfill"],
        "version" => "20e59da245b068507d19",
    ],
    "js/blocks.js" => [
        "dependencies" => [
            "lodash",
            "react",
            "wp-block-editor",
            "wp-blocks",
            "wp-components",
            "wp-i18n",
            "wp-polyfill",
        ],
        "version" => "e700597aa4ab30101b1c",
    ],
];

There is class-assets.php file:

<?php
/**
 * Enqueue theme assets
 * 
 * @package NintyNine
 */

namespace NINTYNINE_THEMEInc;

use NINTYNINE_THEMEIncTraitsSingleton;

class Assets {
    use Singleton;

    protected function __construct(){
        //load class.
        $this->setup_hooks();
    }

    protected function setup_hooks(){
        /**
         * Actions
         */
        add_action( 'enqueue_block_assets', [$this, 'enqueue_editor_assets' ] );
    }

    public function enqueue_editor_assets() {
        
        $asset_config_file = sprintf( '%s/assets.php', NINTYNINE_BUILD_PATH );

        if ( ! file_exists( $asset_config_file ) ) {
            return;
        }

        $asset_config = require_once $asset_config_file;

        if ( empty( $asset_config['js/blocks.js'] ) ) {
            return;
        }

        $editor_asset    = $asset_config['js/blocks.js'];
        $js_dependencies = ( ! empty( $editor_asset['dependencies'] ) ) ? $editor_asset['dependencies'] : [];
        $version         = ( ! empty( $editor_asset['version'] ) ) ? $editor_asset['version'] : filemtime( $asset_config_file );

        // Theme Gutenberg blocks JS.
        if ( is_admin() ) {
            wp_enqueue_script(
                'nintynine-blocks-js',
                NINTYNINE_BUILD_JS_URI . '/blocks.js',
                $js_dependencies,
                $version,
                true
            );
        }

        // Theme Gutenberg blocks CSS.
        $css_dependencies = [
            'wp-block-library-theme',
            'wp-block-library',
        ];

        wp_enqueue_style(
            'nintynine-blocks-css',
            NINTYNINE_BUILD_CSS_URI . '/blocks.css',
            $css_dependencies,
            filemtime( NINTYNINE_BUILD_CSS_DIR_PATH . '/blocks.css' ),
            'all'
        );

    }

}

Finally, the class-blocks.php file

<?php
/**
 * Theme Blocks
 * 
 * @package NintyNine
 */

namespace NINTYNINE_THEMEInc;

use NINTYNINE_THEMEIncTraitsSingleton;

class Blocks {
    use Singleton;

    protected function __construct(){
        //load class.
        $this->setup_hooks();
    }

    protected function setup_hooks(){
        /**
         * Actions
         */
        add_action( 'block_categories_all', [ $this, 'add_block_categories' ] );
    }

    public function add_block_categories( $categories ) {
        $categories_slugs = wp_list_pluck( $categories, 'slug' );

        return in_array( 'nintynine', $categories_slugs, true ) ? $categories : 
        array_merge( 
            $categories, 
            [
                [
                    'slug' => 'nintynine', 
                    'title' => __( 'NintyNine Blocks', 'nintynine' ), 
                    'icon' => 'table-row-after' 
                ]
            ]
        );

    }
   
}

Apexcharts – Dynamically update tickamount based on the screen width

I’m testing for the first time some libraries to create graphs in JavaScript of Open Source type to understand which one is the most interesting and suitable for me.


I was trying to update tickamount in Apexcharts on xaxis with type: 'category'.

In the labels there are datetimes formatted, but I can’t use the type: ' datetime' because some points in dates are null (there’s not the example case, full filled).

So watch this snippet. If I resize my browser window the tickAmount it’s replaced with tickAmount: newtickamount correctly, but I got completely different values on the xaxis.

It’s a bug or I’m doing something wrong?

Tnx All

    var options = {
        chart: {
            width: '100%',
            height: '400px',
            stacked: false,
            toolbar: { show: false, },
        },
        labels: [
            "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20", "29 08 2024 06:54:20",        ],

        series: [{
            name: 'Hello',
            info: 'hello',
            currency: 'USD',
            type: 'line',
            data: [
                357, 171, 472, 909, 707, 411, 470, 990, 112, 369, 428, 451, 44, 869, 710, 782, 718, 491, 479, 976, 438, 953, 976, 363, 886, 479, 274, 809, 625, 808, 569, 226, 158, 646, 196, 506, 754, 114, 513, 535, 271, 428, 155, 97, 412, 661, 181, 118, 616, 297, 23, 460, 344, 274, 467, 937, 839, 355, 290, 765, 647, 462, 90, 439, 737, 439, 194, 186, 973, 667, 181, 425, 84, 453, 43, 835, 99, 209, 580, 465, 329, 740, 541, 237, 17, 631, 916, 300, 745, 826, 63, 900, 990, 450, 560, 99, 21, 981, 954,             ],

            },
        ],

        stroke: {
            width: 2,
            curve: 'smooth',
        },

        plotOptions: {
            bar: { columnWidth: '90%', }
        },

        
        xaxis: {
            type: 'category',     //category    datetime     numeric
            //tickAmount: 20,
            tooltip: { enabled: false, },
            tickPlacement: 'on',
            labels: { rotate: -60, },
        },
        
        
        yaxis: [
          {
            show: true,
            labels: {
                show: true,
            },
            axisBorder: { show: false, },
            axisTicks: { show: false, },
            tooltip: { enabled: true, offsetX: -20, },
          },
        ],
        tooltip: {
            enabled: true,
            shared: true,
            intersect: false,
            //offsetY: 400,
            inverseOrder: false,
            //custom: function({series, seriesIndex, dataPointIndex, w}) {   return 'HELLO!';  }),
        }       
    };

    var chart = new ApexCharts(document.querySelector("#chart"), options);
    chart.render();
      
      
      
      
      
      
      
  
    //Replacing tickamount
    function replace_tickamount(){
        width = document.body.clientWidth;
        newtickamount = 0;
        
        if (width > 1000){
            newtickamount = 10;
        } else if (width > 500) {
            newtickamount = 8;
        } else {
            newtickamount = 4;
        }
        
        chart.updateOptions({
            xaxis: { type: 'category', tickAmount: newtickamount, },
        });

    }



    addEventListener("resize", (event) => { 
      replace_tickamount();
    });

    
<div id="chart"></div>
<style>
@import url(https://fonts.googleapis.com/css?family=Roboto);
body { font-family: Roboto, sans-serif; }
#chart { max-width: 100%; border: 1px solid #000; }
</style>
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>

The

Send the image created on canvas to the backend server

I have canvas and for now, i downloaded jpg file with this.

 var a = document.createElement('a');
 a.href = ref_canvas_release.current.toDataURL('image/jpeg', 0.85);
 
 a.download = GlobalParam.fileObj.project_name + '.jpg';
 a.click();

then now I want to upload this image to backend instead of download.

So, what I want to do is like this,

    fileimage = ref_canvas_release.current.toDataURL('image/jpeg', 0.85);
    const formData = new FormData();

    //It's not correct.
    formData.append("myfile",fileimage);
    
    var url = '/get_thumbnail';
    axios.post(url, formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }).then((res) =>{
        console.log(res);
    });

maybe I don’t need to make file but use bytestream,

However how can I do this?

Why is the control going inside the if condition in this case [duplicate]

$(document).on('click', '.addReframeJob', function (e) {

            let srtFileUrl = $(this).attr('srtFileUrl');

            console.log("srtfile url from reframe button click: ",srtFileUrl);

            let srtFile = '';

            if (srtFileUrl !== undefined || srtFileUrl !== null || srtFileUrl !== '') {
               let srtPath = new URL(srtFileUrl).pathname;
               srtFile = srtPath.substring(1);
           }


        });

I have confirmed in the console that srtFileUrl is indeed null, even then the flow is getting inside the if condition.

According to the code, if the srtFileUrl is null, it shouldn’t go inside the if condition but it is still getting inside it.

How to stop a celery task if user unloads?

My website allows users to translate files. I want to add a failsafe in case a user decides to unload the webpage(whether by reloading, navigating away or closing the tab). My backend is django plus celery[redis]. Currently, after a user begins the translation task my frontend polls the backend every 5 seconds to see if the task is still running. Here is the corresponding JS for reference:

function pollTaskStatus(taskId) {
    currentTaskId = taskId;
    console.log(currentTaskId)
    pollInterval = setInterval(() => {
        const xhr = new XMLHttpRequest();
        xhr.onload = function() {
            if (xhr.status == 200) {
                const response = JSON.parse(xhr.responseText);
                if (response.status === 'completed') {
                    console.log('sent');
                    showTranslationComplete(response);
                    clearInterval(pollInterval); // Stop polling once completed
                    isTranslating = false; // Set to false when translation is complete
                }
            } else {
                showError('An error occurred.');
                clearInterval(pollInterval); // Stop polling on error
                isTranslating = false; // Set to false on errors
            }
        };
        xhr.onerror = function() {
            showError('Connection error. Please check your network connection and try again.');
            clearInterval(pollInterval); // Stop polling on network error
            isTranslating = false; // Set to false on network error
            
        };
        xhr.open('GET', `/translate/poll_task_status/${taskId}/`, true);
        xhr.send();
    }, 5000); // Poll every 5 seconds
}

I know it is unreliable to run functions during/after an unload event so I’ve avoided that. Any suggestions appreciated.

Jest testing “Cannot access ‘mockDb’ before initialization”

import { getDocument, saveDocument } from “./request”;

import { getDocument, saveDocument } from "./request";

const mockDb = {
    get: jest.fn(),
    insert: jest.fn(),
};

jest.mock("nano", () => () => ({
    db: {
        use: () => mockDb,
    },
}));

describe("Database operations", () => {
    beforeEach(() => {
        jest.clearAllMocks();
    });
    test("should get document successfully", async () => {
        const docId = "test-doc";
        const mockDocument = { _id: docId, name: "test" };
        mockDb.get.mockResolvedValue(mockDocument);
        const result = await getDocument(docId);
        expect(result).toEqual(mockDocument);
        expect(mockDb.get).toHaveBeenCalledWith(docId);
    });
});

Im using npm nano and using jest to test my code, I ran the test then it log Cannot access 'mockDb' before initialization. I found some people said use commonjs, but I want to import using ES6. Does anyone know what the problem is? Please help me, thanks.

SVG morphing on scroll javascript handling

enter image description here

Trying to recreate this javascript scrolling animation – responding to changes in scroll direction and morphing between different transitions

A basic example I’ve looked over using mousedown events

let rid = null;
// the value of the y coordinate of the point is changing between 134.86 and 177.14
let memory = [134.86, 177.14];
let target = memory[0]; 
let value = memory[1];

//a function that updates that value
function updateValue() {
    let dist = target - value;
    let vel = dist/10;
    value += vel;
    // stopping the animation when the distance between the target and the value is very small
    if (Math.abs(dist) < .01) {
    if(rid){window.cancelAnimationFrame(rid);
    rid = null;
    }
  }  
}

function updatePath() {  
  morphingPath.setAttributeNS(null, "d",`M0,0H47V156L23.5, ${value}L0,156V0z`);
}

function Frame() {
  rid = window.requestAnimationFrame(Frame);
  updateValue();
  updatePath();
}

window.addEventListener(
  "load",
   updatePath,
   false
);

svg.addEventListener(//animate the path on mousedown
  "mousedown",
  function() {
    if (rid) {
      window.cancelAnimationFrame(rid);
      rid = null;
    }
    
    memory.reverse();
    target = memory[1];
    Frame();
  },
  false
);
svg{width:50px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<svg id="svg" viewBox="0 0 46 180"><path id="morphingPath" d="M0,0h47v156L23.5,134.86L0,156V0z" /></svg>

Visual Studio Code Error: “Unterminated string in JSON at position 8192 (line 1 column 8193)”

I’m encountering the following error in Visual Studio Code:


2024-08-28 15:32:54.847 [error] Unterminated string in JSON at position 8192 (line 1 column 8193): SyntaxError: Unterminated string in JSON at position 8192 (line 1 column 8193)
    at JSON.parse (<anonymous>)
    at Object.factory (/usr/share/code/resources/app/out/vs/code/node/sharedProcess/sharedProcessMain.js:104:79756)

This error seems to be related to the sharedProcessMain.js file, which is a core component of Visual Studio Code. I’ve tried disabling all extensions and checking for updates, but the issue persists.

Clearly, updating visual studio and disable all extensions did not resolve the issue. Those were expected to resolve the JSON string problem. Whenever I try to install the Python extensions. The error comes up that stops the download.