Storybook Actions not consistent when using boolean function handler

I am trying to write a Storybook story in React that displays the output of a function handler on a component, using Storybook Actions. However, each event displays either the value itself, or an object with the name of the action and the args.

For example:

onClick: {name: "onClick", args: false}
onClick: true
onClick: {name: "onClick", args: false}
onClick: true
onClick: {name: "onClick", args: false}
onClick: true

Why is storybook outputting onClick: {name: "onClick", args: false} instead of
onClick: false? Or vice versa, why not display onClick: {name: "onClick", args: true} instead of onClick: true?

Story Code:


const Template = (args) => (
    <MyComponent {...args}/>
);

const Default = Template.bind({});

Default.argTypes = {
  onClick: {
    description:
      "A callback function that is called when the user changes the state of the checkbox.",
    action: "onClick",
  },
};

Component Code:

const MyComponent = ({ onClick }) => (  
  <input type="checkbox" onChange={(e) => onClick(e.target.checked)} />
);

I am using "@storybook/react": "^6.2.9".

Mobile Keyboard Closes Immediately on iPhone When Clicking Input or Text Editor in React Application

I’m experiencing a strange issue in my React application that only occurs on iPhones (tested in both Safari and Chrome).

The app contains standard input fields and a text editor. When I tap on an input or the text editor, the mobile keyboard briefly opens but immediately closes, making it impossible to type anything.

example: https://streamable.com/n2k7q5

This issue:

Only happens on iPhones (both Safari and Chrome).
Does not occur on Android devices.
Does not occur on desktop browsers, even when using mobile resolution in responsive design mode.
I’ve verified that there are no onBlur or similar events being triggered unintentionally, and I can’t find anything in the code that would explain this behavior.

When I comment out this part of my code:


<div className={profileStyles.aboutEdit}>
  <label htmlFor="file-upload" className={profileStyles.picturesAddBox}>
    <div className={profileStyles.picturesAddBoxContent}>
      <div className={profileStyles.picturesAddPlus}>
        <FontAwesomeIcon icon={faPlus} />
      </div>
      <h4>Add new media</h4>
    </div>
  </label>
  <input
    id="file-upload"
    type="file"
    accept="image/*"
    onChange={handleImageUpload}
    style={{
      position: 'absolute',
      top: 0,
      left: 0,
      width: '100%',
      height: '100%',
      opacity: 0,
      cursor: 'pointer',
      zIndex: 999,
      background: 'blue',
    }}
  />
</div>

And replace it with a simple <div>Something</div> and also If I remove the padding-top: 90px; from the

aboutviewContent

class in my CSS, the issue resolves, but it is not solution, i need file input for upload image.

Here’s my full code:

<div className="container widget-main">
  <div className="row aboutviewContent">
    <div className="col-lg-12">
      <div className="row">
        <div className="col-md-3">
          {file || (!!data && data?.image) ? (
            <div className="aboutImageBox">
              <Image
                className="aboutEditPageImage"
                width={100}
                height={100}
                src={
                  file
                    ? file
                    : 'https://cdn.widgera.com/company-widget/' +
                      (compId == 'publish'
                        ? context?.companyContextInfo?.id
                        : compId) +
                      '/image/' +
                      data?.image
                }
                alt="about"
              />
              <div className={profileStyles.picturesEditBoxBtns}>
                <div className={profileStyles.picturesEditBoxUpdate}>
                  <FontAwesomeIcon icon={faCamera} />
                </div>
                <div className={profileStyles.picturesEditBoxDelete}>
                  <FontAwesomeIcon icon={faTrashCan} />
                </div>
              </div>
              <input
                id="file-upload"
                type="file"
                accept="image/*"
                onChange={handleImageUpload}
                style={{
                  position: 'absolute',
                  top: 0,
                  left: 0,
                  width: '100%',
                  height: '100%',
                  opacity: 0,
                  cursor: 'pointer',
                  zIndex: 999,
                  background: 'blue',
                }}
              />
            </div>
          ) : (
            <div className={profileStyles.aboutEdit}>
              <label
                htmlFor="file-upload"
                className={profileStyles.picturesAddBox}
              >
                <div className={profileStyles.picturesAddBoxContent}>
                  <div className={profileStyles.picturesAddPlus}>
                    <FontAwesomeIcon icon={faPlus} />
                  </div>
                  <h4>Add new media</h4>
                </div>
              </label>
              <input
                id="file-upload"
                type="file"
                accept="image/*"
                onChange={handleImageUpload}
                style={{
                  position: 'absolute',
                  top: 0,
                  left: 0,
                  width: '100%',
                  height: '100%',
                  opacity: 0,
                  cursor: 'pointer',
                  zIndex: 999,
                  background: 'blue',
                }}
              />
            </div>
          )}
        </div>
        <div className="col-md-9">
          <Tiptap content={content} setContent={setContent} />
        </div>
      </div>
    </div>
  </div>
  <div className={profileStyles.aboutChangeBtns}>
    <button
      className="btn-md-tertiary"
      onClick={() => {
        props.setModal([]);
      }}
    >
      Cancel
    </button>
    <button
      className="btn-md-primery ms-2"
      onClick={() => handleSave()}
    >
      Save Changes
    </button>
  </div>
</div>

CSS:

css

.aboutviewContent {
  border-radius: 0;
  padding: 4px;
  background-color: var(--generic-white);
  height: calc(100vh - 149px);
  padding-top: 90px; /* Removing this resolves the issue, if i have commented div of input*/
}

Has anyone encountered this issue before? How can I resolve it?

Any help would be greatly appreciated!

Extracting base64 data from img tag with cross-origin redirected src

I’m developing a browser extension and I need to access the data from an img tag. The src attribute of the img redirects to a cross-origin resource and is credential protected. I know that getting this data is possible because extensions like https://github.com/gildas-lormeau/SingleFile are able to get the data of the image in string format, but I’m having difficulty tracing the code.

From this file https://github.com/gildas-lormeau/SingleFile/blob/bfcc3c4aac6780bd90bdc1b5688c1bab863c12da/src/lib/single-file/fetch/content/content-fetch.js#L100 it looks like using a combination of the hostFetch and fetchResources methods should be what I’m seeking but I can’t figure out what handles the event sent on line 100.

Extracting base64 data from img with cross-origin redirected src

I’m developing a browser extension and I need to access the data from an img tag. The src attribute of the img redirects to a cross-origin resource and is credential protected. I know that getting this data is possible because extensions like https://github.com/gildas-lormeau/SingleFile are able to get the data of the image in string format, but I’m having difficulty tracing the code.

For anyone who doesn’t have a solution, could you at least tell me how I can find what code is being called here: https://github.com/gildas-lormeau/SingleFile/blob/bfcc3c4aac6780bd90bdc1b5688c1bab863c12da/src/lib/single-file/fetch/content/content-fetch.js#L100
It looks like using a combination of the hostFetch and fetchResources methods should be what I’m seeking.

React is ignoring / not executing DOM modification by JQuery or javascript

I have a
.html page like

<div>year=<span class='year'></span></div>.

and
.js file with code

$('.year').text(new Date().getFullYear());

this is working fine with HTML pages but not in react pages.I tried using inline script, using javascript .textContent, .innerHTML but nothing is working.

I don’t have access to directly make changes in the react file so how could i make it work such scenarios.

How to properly convert my slider from vanillajs to work with nextjs component without images desync

I do apologize for such a question, I have tried on my own before asking but failing to achieve the desired effect, first of all here is a working example with vanillajs

https://stackblitz.com/edit/vitejs-vite-tr68pgsl?file=index.html,src%2Fmain.js,src%2Fstyle.css

html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite App</title>
  </head>
  <body>
    <div id="app">
    <div class="slider">
    <div class="slider-images">
      <ul>
        <li class="slider-item">
          <img src="/imgs/1.jpg" alt="Image 1">
        </li>
        <li class="slider-item">
          <img src="/imgs/2.jpg" alt="Image 2">
        </li>
        <li class="slider-item">
          <img src="/imgs/3.jpg" alt="Image 3">
        </li>
      </ul>
    </div>

    <!-- slider title -->
    <div class="slider-title">
      <ul>
        <li>the revival ensemble</li>
        <li>Above the canvas</li>
        <li>Harmony in every note</li>
      </ul>
    </div>

    <!-- slider counter -->
    <div class="slider-counter">
      <div class="counter">
        <p>1</p>
        <p>2</p>
        <p>3</p>
      </div>
      <div>
        <p>&mdash;</p>
      </div>
      <div>
        <p>3</p>
      </div>
    </div>

    <!-- slider preview -->
    <div class="slider-preview">
      <div class="preview">
        <img src="/imgs/1.jpg" alt="">
      </div>
      <div class="preview">
        <img src="/imgs/2.jpg" alt="">
      </div>
      <div class="preview">
        <img src="/imgs/3.jpg" alt="">
      </div>
    </div>

    <!-- slider indicators -->
    <div class="slider-indicators">
      <p>+</p>
      <p>+</p>
    </div>

  </div>
    </div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>

css

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  user-select: none;
}

html,
body {
  width: 100%;
  height: 100%;
}

img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

a,
p {
  text-decoration: none;
  color: #fff;
  font-size: 14px;
}

.slider {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.slider-images {
  position: absolute;
  width: 100%;
  height: 100%;
}

.slider-item {
  position: absolute;
  width: 100%;
  height: 100%;
  list-style: none;
}

.slider-counter {
  position: absolute;
  bottom: 2em;
  left: 50%;
  transform: translateX(-50%);
  height: 24px;
  display: flex;
  gap: 0.5em;
  overflow: hidden;
}

.slider-counter > div {
  flex: 1;
}

.slider-counter p {
  line-height: 20px;
}

.counter {
  position: relative;
  top: 0;
  will-change: transform;
}

.slider-title {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  height: 64px;
  overflow: hidden;
  color: #fff;
}

.slider-title ul {
  text-align: center;
}

.slider-title li {
  font-size: 50px;
  line-height: 60px;
}

.slider-indicators {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 75%;
  display: flex;
  justify-content: space-between;
}

.slider-indicators p {
  font-size: 40px;
  font-weight: 200;
}

.slider-preview {
  position: absolute;
  bottom: 2em;
  right: 2em;
  width: 35%;
  height: 50px;
  display: flex;
  gap: 1em;
}

.preview {
  position: relative;
  flex: 1;
  cursor: pointer;
}

.preview::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  transition: 0.3s ease-in-out;
}

.preview.active::after {
  background: rgba(0, 0, 0, 0);
}

@media (max-width: 900px) {
  .slider-indicators {
    width: 90%;
  }

  .slider-preview {
    width: 90%;
    bottom: 5em;
  }

  .slider-title li {
    font-size: 30px;
  }
}

js

import './style.css';
import gsap from 'gsap';
import CustomEase from 'gsap/CustomEase';

document.addEventListener('DOMContentLoaded', () => {
  gsap.registerPlugin(CustomEase);
  CustomEase.create(
    'hop',
    'M0,0 C0.071,0.505 0.192,0.726 0.318,0.852 0.45,0.984 0.504,1 1,1'
  );

  const sliderImages = document.querySelector('.slider-images ul');
  const counter = document.querySelector('.counter');
  const title = document.querySelector('.slider-title ul');
  const indicators = document.querySelectorAll('.slider-indicators p');
  const previews = document.querySelectorAll('.slider-preview .preview');
  const totalSlides = 3;

  let currentImg = 1;
  let indicatorRotation = 0;

  const updateCounterAndTitlePosition = () => {
    const counterY = -20 * (currentImg - 1);
    const titleY = -60 * (currentImg - 1);

    gsap.to(counter, {
      y: counterY,
      duration: 1,
      ease: 'hop',
    });

    gsap.to(title, {
      y: titleY,
      duration: 1.5,
      ease: 'hop',
    });
  };

  const updateActiveSlidePreview = () => {
    previews.forEach((prev) => prev.classList.remove('active'));
    previews[currentImg - 1].classList.add('active');
  };

  const animateSlide = (direction) => {
    const currentSlide = sliderImages.querySelector('.slider-item:last-child');

    const slideImg = document.createElement('li');
    slideImg.classList.add('slider-item');
    const slideImgElem = document.createElement('img');
    slideImgElem.src = `/imgs/${currentImg}.jpg`;
    gsap.set(slideImgElem, { x: direction === 'left' ? -300 : 300 });

    slideImg.appendChild(slideImgElem);
    sliderImages.appendChild(slideImg);

    gsap.to(currentSlide.querySelector('img'), {
      x: direction === 'left' ? 300 : -300,
      duration: 1.5,
      ease: 'power4.out',
    });

    gsap.fromTo(
      slideImg,
      {
        clipPath: direction === 'left'
          ? 'polygon(0% 0%, 0% 0%, 0% 100%, 0% 100%)'
          : 'polygon(100% 0%, 100% 0%, 100% 100%, 100% 100%)',
      },
      {
        clipPath: 'polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%)',
        duration: 1.5,
        ease: 'power4.out',
      }
    );

    gsap.to(slideImgElem, {
      x: 0,
      duration: 1.5,
      ease: 'power4.out',
    });

    cleanupSlides();

    indicatorRotation += direction === 'left' ? -90 : 90;
    gsap.to(indicators, {
      rotate: indicatorRotation,
      duration: 1,
      ease: 'hop',
    });
  };

  document.addEventListener('click', (event) => {
    const sliderWidth = document.querySelector('.slider').clientWidth;
    const clickPosition = event.clientX;

    const clickedPreview = event.target.closest('.preview');
    if (clickedPreview) {
      const clickedIndex = Array.from(previews).indexOf(clickedPreview) + 1;

      if (clickedIndex !== currentImg) {
        currentImg = clickedIndex;
        animateSlide(clickedIndex < currentImg ? 'left' : 'right');
        updateActiveSlidePreview();
        updateCounterAndTitlePosition();
      }
      return;
    }

    if (clickPosition < sliderWidth / 2 && currentImg !== 1) {
      currentImg--;
      animateSlide('left');
    } else if (clickPosition > sliderWidth / 2 && currentImg !== totalSlides) {
      currentImg++;
      animateSlide('right');
    }

    updateActiveSlidePreview();
    updateCounterAndTitlePosition();
  });

  const cleanupSlides = () => {
    const imgElements = document.querySelectorAll('.slider-images .slider-item');
    if (imgElements.length > totalSlides) {
      imgElements[0].remove();
    }
  };
});

And here is what I’ve tried so far with next js
I have tried but the images are out of sync
and the title animation is broken
i understand that it’s lack of skills
would be grateful if someone can guide me how to fix those issues

'use client'

import { useState } from 'react';
import gsap from 'gsap';
import CustomEase from 'gsap/CustomEase';
import { useGSAP } from '@gsap/react';

const Slider = () => {
  // State to manage current image and indicator rotation
  const [currentImg, setCurrentImg] = useState(1);
  const [indicatorRotation, setIndicatorRotation] = useState(0);

  const totalSlides = 3;

  // Initialize GSAP with .slider as the container
  useGSAP(() => {
    // Register GSAP plugin and create custom easing
    gsap.registerPlugin(CustomEase);
    CustomEase.create(
      'hop',
      'M0,0 C0.071,0.505 0.192,0.726 0.318,0.852 0.45,0.984 0.504,1 1,1'
    );
  }, []);

  useGSAP(() => {
    // Update counter and title position
    updateCounterAndTitlePosition();
    updateActiveSlidePreview();
  }, [currentImg]);

  const updateCounterAndTitlePosition = () => {
    const counterY = -20 * (currentImg - 1);
    const titleY = -60 * (currentImg - 1);

    gsap.to('.slider .counter', {
      y: counterY,
      duration: 1,
      ease: 'hop',
    });

    gsap.to('.slider .slider-title', {
      y: titleY,
      duration: 1.5,
      ease: 'hop',
    });
  };

  const updateActiveSlidePreview = () => {
    const previews = document.querySelectorAll('.slider .preview');
    previews.forEach((prev) => prev.classList.remove('active'));
    previews[currentImg - 1].classList.add('active');
  };

  const animateSlide = (direction) => {
    const sliderImages = document.querySelector('.slider .slider-images ul');
    const currentSlide = sliderImages.querySelector('.slider-item:last-child');

    const slideImg = document.createElement('li');
    slideImg.classList.add('slider-item');
    const slideImgElem = document.createElement('img');
    slideImgElem.src = `/imgs/${currentImg}.jpg`;
    gsap.set(slideImgElem, { x: direction === 'left' ? -300 : 300 });

    slideImg.appendChild(slideImgElem);
    sliderImages.appendChild(slideImg);

    gsap.to(currentSlide.querySelector('img'), {
      x: direction === 'left' ? 300 : -300,
      duration: 1.5,
      ease: 'power4.out',
    });

    gsap.fromTo(
      slideImg,
      {
        clipPath: direction === 'left'
          ? 'polygon(0% 0%, 0% 0%, 0% 100%, 0% 100%)'
          : 'polygon(100% 0%, 100% 0%, 100% 100%, 100% 100%)',
      },
      {
        clipPath: 'polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%)',
        duration: 1.5,
        ease: 'power4.out',
      }
    );

    gsap.to(slideImgElem, {
      x: 0,
      duration: 1.5,
      ease: 'power4.out',
    });

    cleanupSlides();

    setIndicatorRotation((prevRotation) => prevRotation + (direction === 'left' ? -90 : 90));
    gsap.to('.slider .slider-indicators', {
      rotate: indicatorRotation,
      duration: 1,
      ease: 'hop',
    });
  };

  const cleanupSlides = () => {
    const imgElements = document.querySelectorAll('.slider .slider-item');
    if (imgElements.length > totalSlides) {
      imgElements[0].remove();
    }
  };

  const handleClick = (event) => {
    const sliderWidth = document.querySelector('.slider').clientWidth;
    const clickPosition = event.clientX;

    const clickedPreview = event.target.closest('.preview');
    if (clickedPreview) {
      const clickedIndex = Array.from(document.querySelectorAll('.slider .preview')).indexOf(clickedPreview) + 1;

      if (clickedIndex !== currentImg) {
        setCurrentImg(clickedIndex);
        animateSlide(clickedIndex < currentImg ? 'left' : 'right');
        updateActiveSlidePreview();
        updateCounterAndTitlePosition();
      }
      return;
    }

    if (clickPosition < sliderWidth / 2 && currentImg !== 1) {
      setCurrentImg(currentImg - 1);
      animateSlide('left');
    } else if (clickPosition > sliderWidth / 2 && currentImg !== totalSlides) {
      setCurrentImg(currentImg + 1);
      animateSlide('right');
    }

    updateActiveSlidePreview();
    updateCounterAndTitlePosition();
  };

  return (
    <div className="slider" onClick={handleClick}>
      <div className="slider-images">
        <ul>
          {[...Array(totalSlides)].map((_, index) => (
            <li key={index} className="slider-item">
              <img src={`/imgs/${index + 1}.jpg`} alt={`Image ${index + 1}`} />
            </li>
          ))}
        </ul>
      </div>

      <div className="slider-title">
        <ul>
          <li>the revival ensemble</li>
          <li>Above the canvas</li>
          <li>Harmony in every note</li>
        </ul>
      </div>

      <div className="slider-counter">
        <div className="counter">
          {[...Array(totalSlides)].map((_, index) => (
            <p key={index}>{index + 1}</p>
          ))}
        </div>
        <div>
          <p>&mdash;</p>
        </div>
        <div>
          <p>{totalSlides}</p>
        </div>
      </div>

      <div className="slider-preview">
        {[...Array(totalSlides)].map((_, index) => (
          <div key={index} className={`preview ${currentImg === index + 1 ? 'active' : ''}`}>
            <img src={`/imgs/${index + 1}.jpg`} alt={`Preview ${index + 1}`} />
          </div>
        ))}
      </div>

      <div className="slider-indicators">
        {[...Array(2)].map((_, index) => (
          <p key={index}>+</p>
        ))}
      </div>
    </div>
  );
};

export default Slider;

Assigning object to array of objects based on another array check in javascript [closed]

I have array of objects as below:

const jobs = [
  {
    jobId: '11111',
    jobData: {
      title: 'Job 1',
      customFields: [
        {
          name: 'AA Checkbox 1',
          type: 'CHECKBOX',
          value: 'Yes',
        },
        {
          id: 'koi',
          name: 'CF Time',
          type: 'TIME',
          value: '22:45',
        },
      ]
    }
  },
  {
    jobId: '22222',
    jobData: {
      title: 'Job 2',
      customFields: [
        {
          name: 'BB Checkbox 2',
          type: 'CHECKBOX',
          value: 'No',
        },
        {
          id: '444',
          name: 'CF Time',
          type: 'TIME',
          value: '12:08',
        },
      ]
    }
  },
  {
    jobId: '33333',
    jobData: {
      title: 'Job 3',
      customFields: []
    }
  }
]

Inside of each object there is another object jobData with another array called customFields. The customFields array may or may not have “CHECKBOX” type field objects.
There might be more than one “CHECKBOX” type object with different names, and with different values “Yes” or “No” like in my example.

What I want is to assign a “CHECKBOX” type object with value: “No” to every job which don’t have it if at least one of the jobs have it, no matter if the value is “Yes” or “No” in the existing one.
So that the output is like that

const jobs = [
  {
    jobId: '11111',
    jobData: {
      title: 'Job 1',
      customFields: [
        {
          id: 'sasa',
          name: 'AA Checkbox 1',
          type: 'CHECKBOX',
          value: 'Yes',
        },
        {
          id: 'fdf',
          name: 'BB Checkbox 2',
          type: 'CHECKBOX',
          value: 'No',
        },
        {
          id: 'koi',
          name: 'CF Time',
          type: 'TIME',
          value: '22:45',
        },
      ]
    }
  },
  {
    jobId: '22222',
    jobData: {
      title: 'Job 2',
      customFields: [
        {
          id: 'sasa',
          name: 'AA Checkbox 1',
          type: 'CHECKBOX',
          value: 'No',
        },
        {
          id: 'fdf',
          name: 'BB Checkbox 2',
          type: 'CHECKBOX',
          value: 'No',
        },
        {
          id: '444',
          name: 'CF Time',
          type: 'TIME',
          value: '12:08',
        },
      ]
    }
  },
  {
    jobId: '33333',
    jobData: {
      title: 'Job 3',
      customFields: [
        {
          id: 'sasa',
          name: 'AA Checkbox 1',
          type: 'CHECKBOX',
          value: 'No',
        },
        {
          id: 'fdf',
          name: 'BB Checkbox 2',
          type: 'CHECKBOX',
          value: 'No',
        }
      ]
    }
  }
]

How do I load a 3D model using three.js using the editor playcode.io?

I have been trying to load in a 3d Model on playcode.io. My browser supports WebGl and so does playcode.io (I think) So far, no success. There is no problem The model either. The model is called plane.gltf. The screen is just a blank black screen. Here is my code for the three.js:

import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

const loader = new GLTFLoader();

loader.load( 'plane.gltf', function ( gltf ) {

    scene.add( gltf.scene );

}, undefined, function ( error ) {

    console.error( error );

} );

function animate() {
    renderer.render( scene, camera );
}
renderer.setAnimationLoop( animate );

And here is my code for the HTML:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>My first three.js app</title>
        <style>
            body { margin: 0; }
        </style>
    </head>
    <body>
        <script type="module" src="/main.js"></script>
    </body>
</html>

I checked all the threeJS documentation and tutorials. I was expecting the model to load up. it didn’t. I tried in multiple editors but no success. am I doing something wrong?

Write data to publicly shared Google Sheets

I have a Google Sheets form that is shared so that anyone with the link can edit.
How do I write a html file so that when you run it it adds something to the google sheets file, eg

function add_name(let name, let age) {
   // Code here to add a new line to the url "https://docs.google.com/spreadsheets/d/my_spreadsheet/edit?usp=sharing"
   // and add the values
};
function get_all_names() {
   // Code here to return all the names
};

I have tried everything, please help (:

After spending a solid hour looking up methods to do that, I couldn’t find one without having some kind of extention. Extentions should not be needed as anyone who has the link can make changes. I will accept any answer as long as the html is a file and there is no extra extentions added. Any apis must be contained within the project folder with the main html file.

JavaScript Regex Missing a Capture Group with Quantifier

I’m working on some regex patterns and wondering why in my regular expression the middle group is skipped.

Expression:

/^hsl((d+)(?:deg)?(?:[s,]s*(d+)%?){2})$/

Testing with:

hsl(0,1,2) // PASS = 0, 2 (expecting 0, 1, 2)
hsl(123deg 456% 789%) // PASS = 123, 789 (expecting 123, 456, 789)
hsl(360deg, 50%, 25%) // PASS = 360, 25 (expecting 360, 50, 25)
hsl(532) // FAIL (as intended)

I’m curious why only the last match is captured and the middle is skipped. The expression matches the string correctly otherwise.

JavaScript – Copy Data From Excel Column to HTML Inputs

I am looking for solution where one can copy a column from Excel and paste directly into HTML form

var col = 5; //number of 'cells' in a row
const cells = document.querySelectorAll('input[type=text]');

cells.forEach(cell => {
    cell.addEventListener('paste', handlePaste );
})

function handlePaste(event){
    event.preventDefault();
    const plainTextLines = event.clipboardData.getData('text');
    const lines = plainTextLines.split(/rn/g)
    const currentRowIndex = parseInt(event.target.getAttribute('data-row-index'), 10);
    const total = cells.length;
    const pasteTotal = lines.length;
    //console.log(pasteTotal);
    for(let i = currentRowIndex; i < total; i++){
        const valueToPaste = lines[i - currentRowIndex];
        if (valueToPaste) {
            cells[i].value = valueToPaste;
        }
    }
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<form action="save_report.php" method="post" id="save_report">
  <div class="report_student_data" id="report_table">
    <div class="row align-items-center">
      <div class="col-3 text-start"><span>Name</span></div>     
      <div class="col">           
        <input class="report_table_degree_input" type="text" name="degree[]" data-row-index="0">
      </div>
      <div class="col">           
        <input class="report_table_degree_input" type="text" name="degree[]" data-row-index="1">
      </div> 
      <div class="col">           
        <input class="report_table_degree_input" type="text" name="degree[]" data-row-index="2">
      </div> 
      <div class="col">           
        <input class="report_table_degree_input" type="text" name="degree[]" data-row-index="3">
      </div>
      <div class="col">           
        <input class="report_table_degree_input" type="text" name="degree[]" data-row-index="4">
      </div> 
    </div>
  </div>  
  <div class="report_student_data" id="report_table">
    <div class="row align-items-center">
      <div class="col-3 text-start"><span>Name</span></div>     
      <div class="col">           
        <input class="report_table_degree_input" type="text" name="degree[]" data-row-index="5">
      </div>
      <div class="col">           
        <input class="report_table_degree_input" type="text" name="degree[]" data-row-index="6">
      </div> 
      <div class="col">           
        <input class="report_table_degree_input" type="text" name="degree[]" data-row-index="7">
      </div> 
      <div class="col">           
        <input class="report_table_degree_input" type="text" name="degree[]" data-row-index="8">
      </div>
      <div class="col">           
        <input class="report_table_degree_input" type="text" name="degree[]" data-row-index="9">
      </div> 
    </div>
  </div> 
</form>

I need to paste the values in vertical columns not horizontal rows
(I am using PHP). It has around 100 cells, and the data is being stored in the MySQL.
Any suggestions or help will be highly appreciated.
sorry for my bad English 🙂

object.assign change attribute [duplicate]

I want to copy the object of a variable to assign to another variable and only change some properties in the object of the new variable without changing the old object.

I create new object for new variable and change properties but when print out old variable is also changed. how to fix it?

let thongTinMuaXeKhachA = {
    iDluotmua:`abc129867`,
    nguoiSohuu:{
        ten: `Pham Van A`,
        tuoi: 35,
        gioTinh: `nam`,
        namSinh: 1984,
        diaChi: `ha noi`,
        cccd: 12345678,
    },
    thongTinXe: {
        tenXe: `Vinfast luxA 2.0`,
        hangXe: `Vinfast`,
        soCho: 5,
        tocDoTrungBinh: 90,
        mauSac: `Den`,
        giaBan: 1200000000,
        namSanXuat: 2019,
    },
    ngayMua: `26/01/2022`,
};
console.log(`Thong tin khach hang A:`,thongTinMuaXeKhachA);
console.log(`--------------------------`);

let thongTinMuaXeKhachB = Object.assign({},thongTinMuaXeKhachA);
thongTinMuaXeKhachB.nguoiSohuu.ten = `Pham Van B`;
console.log(thongTinMuaXeKhachA);
console.log(thongTinMuaXeKhachB);    

Giving recaptcha response with axios

I’m working on Axios trying to get response from
https://footlocker.queue-it.net/?c=footlocker&e=cxcdtest02

The challenge api is not from recaptcha but is from

https://footlocker.queue-it.net/challengeapi/recaptchainvisible/challenge/
Which gave me the following parameters:

challengeDetails:"Yfz3aGSAliZGAH1Yf(...)="
sessionId: "72d5c5bc-8f4b-449d-995f-787c9ac54c9d"
siteKey:"6LePTyoUAAAAADPttQg1At44EFCygqxZYzgleaKp" 

I have already solved the captcha with 2captcha but can’t figure out how to give that answer to the next API that match “sessionId” and “ChallengeDetails”
userverify API
And then the “enqueue” system which give the “QueueID”
Enqueue

How to calculate median expenditure up to the first Sunday of each month in JavaScript?

I’m working on a task where I need to calculate the median of expenditures up to and including the first Sunday of each month. Here’s a breakdown of the requirements:

const expenses = {
  "2023-01": {
    "01": {
      "food": [22.11, 43, 11.72, 2.2, 36.29, 2.5, 19],
      "fuel": [210.22],
    },
    "09": {
      "food": [11.9],
      "fuel": [190.22],
    },
  },
  "2023-03": {
    "07": {
      "food": [20, 11.9, 30.2, 11.9],
    },
    "04": {
      "food": [10.2, 11.5, 2.5],
      "fuel": [],
    },
  },
  "2023-04": {},
};

For each month, I need to calculate the median of all the expenditures (food, fuel, etc.) up to and including the first Sunday of the month. For example, for the months “2023-09” and “2023-10”, the first Sunday is 1st, 2nd, and 3rd of September, and 1st October respectively.

Requirements:

Unoptimized Solution (solution1): I need to implement a basic version that calculates the median without optimizations (just a simple approach).

Optimized Solution (solution2): The second solution should be optimized using one of the following methods:

Priority queues
Quick select
Quick sort
Or another method of your choice

The result should be a single number representing the median for data that meets the criteria, or null if no data is found.

I can use either Python or JavaScript for the solution.

I should only use functions/modules from the standard library (e.g., math in JavaScript).

What I Need Help With:
I already have a solution, but it was rejected, and I’m not sure why. Below is the code I submitted:

// Helper function to get expenses for the first Sunday
function getFirstSundayExpenses(expenses) {
    const firstSundayExpenses = [];

    for (const month in expenses) {
        const monthExpenses = expenses[month];
        for (const day in monthExpenses) {
            const date = new Date(`${month}-${day}`);
            if (date.getDay() === 0) {
                // Aggregate expenses for the first Sunday
                for (const category in monthExpenses[day]) {
                    firstSundayExpenses.push(...monthExpenses[day][category]);
                }
                break; // Only consider the first Sunday
            }
        }
    }

    return firstSundayExpenses;
}

// Quick Sort Implementation
function quickSort(arr) {
    if (arr.length <= 1) return arr;

    const pivot = arr[arr.length - 1]; // Use the last element as pivot
    const left = [];
    const right = [];

    for (let i = 0; i < arr.length - 1; i++) {
        if (arr[i] < pivot) left.push(arr[i]);
        else right.push(arr[i]);
    }

    return [...quickSort(left), pivot, ...quickSort(right)];
}

// Function to calculate the median after sorting the array
function median(arr) {
    arr.sort((a, b) => a - b); // Sort the array in ascending order
    const n = arr.length;
    if (n % 2 === 0) {
        return (arr[n / 2 - 1] + arr[n / 2]) / 2;
    } else {
        return arr[Math.floor(n / 2)];
    }
}


function solution1(expenses) {
    const firstSundayExpenses = getFirstSundayExpenses(expenses);

    if (firstSundayExpenses.length === 0) return null;

    // Use the median function to find the median
    return median(firstSundayExpenses);
}

function solution2(expenses) {
    const firstSundayExpenses = getFirstSundayExpenses(expenses);

    if (firstSundayExpenses.length === 0) return null;

    // Quick Sort to sort the expenses array
    quickSort(firstSundayExpenses);

    // Use the median function to find the median after sorting
    return median(firstSundayExpenses);
}


console.log(solution1(expenses)); 
console.log(solution2(expenses)); 

I’ve implemented a function that aggregates the expenditures up to and including the first Sunday of each month and calculates the median using a simple quick sort method. However, my solution was rejected. Could someone help me understand what might be wrong with my approach?

Configure Absolute links using ASTROJS Component applied to JSON API DATA

I am using AstroJS v5.0.0-beta.12 and loading data from a prefomatted json file with html links formatted like this <a href="https://www.example.com>example link text</a>.
When I fetch this data on my site using Astro Collections like this import { getCollection } from "astro:content"; const myApi = await getCollection("myAPI");
and then render the data on my .astro page using {myApi.map( (posts) =><p style="margin: 2rem auto;"><Fragment set:html={posts.data.mdbody}></Fragment></p> )} the above external url get reformatted to http://[myservername]:[myport]/[MyBlogDirectoryNameUnderAstroPagesFolder]/https://www.example.com.

It seems to automatically turn it into a “<base>” or relative link

How can I fix this? Any suggestions help.Thank you!