How can I disable a checkbox until data are load?

I need to disable checkboxes until the page load the data(products) and then enable them again,
this is my code for loading data:

function loadCounter(filterCounter) {
$.each(filterCounter.FilterCounter, function (key, value) {
    if (value.Count !== 0) {
        $("#filter .btn-groupl label :input[value='" + key + "']").parent("label").find("span.items-amount").text(value);
        $("filter .btn-group label :input[value='" + key + "']").parent("label").show();
    } else {
       ;
        $("filter .btn-group label :input[value='" + key + "']").parent("label").hide();
        
    }
});

How to use the same javascript custom package in two different folders without repeating it?

I’m building a microservice and dockerizing it. My folder structure looks as following:

Root
|
|--DockerPacks
   |--ProjectA
      |-docker-compose.yml (builds ServiceA & ServiceB)
|--Microservices
   |--ServiceA
      |-lib
        |-PackageA
      |-src
      |-index.js
      |-Dockerfile
      |-package.json
   |--ServiceB
      |-lib
        |-PackageA
      |-src
      |-index.js
      |-Dockerfile
      |-package.json

So in both services (ServiceA & ServiceB) I need to use the same custom package (PackageA inside lib folder) and I don’t want to have it twice. How could I do this? All help is appreciated.

how can i copy files with all sub-directories to another location on windows in npm script?

I have a project in which in which i have a package.json file which have some build commands.
So in that build command there is copy files to another location. But that command is linux based and is using cp -R for recursive copy to another location. Command piece is like this

cp fonts/ public/css/ -R && cp images/ public/css/ -R

so because in windows there is no cp so i modified this command to this

xcopy fonts/ public/css/ /E && xcopy images/ public/css/ /E

But it’s giving an error of

Invalid number of parameters

How can i resolve this?

Call useQuery api when button is clicked

Using the refetch function useQuery, put the refetch function in the button, and when the button is clicked, the data is fetched again through the api-call. I wanted to, but it didn’t happen.

   
  
 function SeedMaterialDetails(id: number) {
  return axios.get(`/detail/${id}`, {
    headers: {
      "Content-Type": "application/json",
    },
  }) 
} 



  const { data: SeedDetail, refetch: SeedDetaiList } = useQuery(
    ["seedId", seedId],
    () => SeedMaterialDetails(seedId),
    {
      onSuccess: (data) => {
         console.log(data);
      },
      onError: () => {},

      onSettled: (data, context) => {
         
      }
    }
  );

  const [value, setValue] = useState("");
 
  const onChangeValue = (event:  event: React.ChangeEvent<HTMLInputElement>) => {
      setValue(event.target.value)
}

 const handleMaterialSave = useCallback(
    (event: React.ChangeEvent<FormEvent>) => {
      event.preventDefault();
      console.log([value]);
      SeedDetaiList();
    },

    [SeedDetaiList]
  );

return (
<>
 <input 
 type="text"
 value={value}
 onChange={onChangeValue}

 <button onClick={handleMaterialSave}>저장</button>
</>
)

I put the refetch function in handleMaterialSave and when the button works, I thought the useQuery api would call but it doesn’t respond.

I want to call the useQuery api again when I click the Button, but how do I do it?

How to toggle the focus of an input using only JavaScript?

I have been trying to make this thing that focuses an input inside it when its outer div is clicked. I really hope this is not a duplicate as I have searched everywhere and not found an answer to this. I am at risk of being blocked so I hope no one flags this as a duplicate.

Here is the code below, it works with focusing the input, but when it has to unfocus it does not seem to work.

window.onload = function() {
  var drop = document.getElementsByClassName("datadrop");
  var drops = document.getElementsByClassName("datadrop").length;

  for (x = 0; x < drops; x++) {
    var input = document.getElementById(drop[x].getAttribute("input"));
    drop[x].onclick = function(e) {
      e.preventDefault();
      clicked = 0
      if (this == document.activeElement) {
        input.blur();
      } else {
        input.focus();
      }
    }
  }
}
.datadrop {
  padding: 7.5px;
  width: 85px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.datadrop .drop {
  width: 150px;
  position: fixed;
  display: none;
}

.datadrop .item {
  padding: 10px;
}

.datadrop .item:hover {
  background-color: #F1F3F4;
}

.datadrop .divider {
  padding: 5px;
  color: grey;
}

.datadrop .divider:hover {
  background-color: #ffffff;
}

.datadrop input {
  width: 60px;
  color: black;
}

.datadrop:hover {
  background-color: #F1F3F4;
  color: #5F6368;
}

.datadrop .click {
  color: #5F6368;
}

.datadrop input {
  background-color: transparent;
  border: 1px solid transparent;
  outline: none;
  padding: 5px;
}

.datadrop input:focus {
  background-color: white;
  border: 1px solid black;
  border-radius: 2.5px;
}
<div datadrop="scale" input="scales" class="datadrop">
  <input type="text" id="scales" value="100%"> &nbsp;&nbsp;|&nbsp; <i class="fa-solid fa-caret-down click"></i>
  <div class="drop" id="scale">
    <div class="item">Fit</div>
    <div class="item divider">
      <hr>
    </div>
    <div class="item">Fit</div>
    <div class="item">Fit</div>
    <div class="item">Fit</div>
  </div>
</div>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />

I hope someone has an answer to this using only JavaScript, and I hope no one flags this as a duplicate, as I am trying to not do duplicates.

Ruby algorithm for generating EChart Waterfall data

I’m trying to get this chart working.

EChart Sandbox: Waterfall Chart

And this the ruby code to elaborate my data.

    data = [ 500, 100, -1000, 300, 500]

    positive_values = []
    negative_values = []
    
    data.each_with_index do |value, index|
  
      if value.negative?
        positive_values << "-"
        negative_values << value.abs
      else
        positive_values << value
        negative_values << "-"
      end
  
    end

    base_values = []
  
    data.each_with_index do |value, index|

      base_values << 0 && next if index == 0

      base = base_values[index-1]

      base -= value.abs.to_f if value.negative?
      base += data[index-1].to_f if data[index-1].positive?

      base_values << base.round(2)

    end
  
    return { base_values: base_values, positive_values: positive_values, negative_values: negative_values }

Now this code works perfectly fine while you have positive values.

But when you start to have, as the code above, negative numbers that are going below 0, the algorithm doesn’t work, and I’m not able to understand the way to fix it.

The expected graph that i’m trying to get with the data mentioned above is the following.

Expected Graph – EChart

YAML/yamljs string deserialization behaviour

I was testing YAML (yamljs) with random inputs (please don’t ask why it’s a long story :D). I’m not very well versed in the YAML spec, but as far as I understand YAML should be able to serialize and deserialize primitives (strings, numbers, booleans) without an object or array wrapper. This however doesn’t always seem to be the case.

I isolated one failing case:

import YAML from 'yamljs'

describe('YAML', () => {
  it('should be equal to the input', () => {
    const str = '0xn5t'
    expect(YAML.parse(YAML.stringify(str))).toBe(str)
  })
})

Where it '0xn5t' is somehow parsed back to 5

Expected: "0xn5t"
Received: 5

Could someone please guide me to the spec where this behaviour is explained? Could this be an issue with the library I’m using?

Does anyone know why my form validation is not working in my upload component?

I am trying to allow a user to submit an image and a title for that image that gets sent to my backend API. I want a user to not be able to submit to that API if the title input box is empty. So I figured I need to implement a form validation for this. But for some reason, it is not working. Can someone help me figure out what I need to do to get it working so that the error displays when the title input is empty? I have a sandbox also if that helps. https://codesandbox.io/s/peaceful-frog-ui4413?file=/src/App.js

Upload.jsx:

import '../../components/pages/styles/Uploads.css';
import {Formik, Field, Form, ErrorMessage} from 'formik';
import * as Yup from 'yup';
import {useEffect, useState} from 'react';
import {} from 'react-router-dom';
import {useDispatch, useSelector} from 'react-redux';
import axios from 'axios';
import {clearMessage} from '../../slices/messages';
import authHeader from '../../services/auth-header';
const API_URL = 'http://localhost:8080/posts';

function Uploads() {
    const {user: currentUser} = useSelector((state) => state.auth);
    const [file, setFile] = useState();
    const [title, setTitle] = useState();
    const [description, setDescription] = useState('');
    const [loading, setLoading] = useState(false);
    const [content, setContent] = useState('');
    const [preview, setPreview] = useState(null);
    const initialValues = {
        title: '',
    };
    const [formValues, setFormValues] = useState(initialValues);
    const [formErrors, setFormErrors] = useState();

    useEffect(() => {}, []);

    const validate = (values) => {
        const errors = {};
        if (!values.title) {
            errors.title = 'Title of Post is required!';
        }
        return errors;
    };

    const handleChange = (e) => {
        const {name, value} = e.target;
        setFormValues({...formValues, [name]: value});
    };

    const handlePost = (formValue) => {};

    const onAddImage = (file) => {
        window.URL.revokeObjectURL(preview);
        if (!file) return;
        setPreview(window.URL.createObjectURL(file));
    };
    const postUserImage = async (event) => {
        //This is the code that will get passed to my backend. I need the image and title to be added here somehow.
        event.preventDefault();

        const formData = new FormData();
        formData.append('file', file);
        formData.append('title', formValues.title);

        const result = await axios.post('/post/upload', formData, {
            headers: {...authHeader(), 'Content-Type': 'multipart/form-data'},
        });
        console.log(result.data);
        setFormErrors(validate(formValues));
    };

    return (
        <div className='page'>
            <div className='upload-card'>
                <div id='preview'>
                    <img
                        src={preview || require('../../assets/user-solid.jpeg')}
                        id='image'
                        alt='Thumbnail'
                        className='user-post'
                    />
                </div>
            </div>
            <div className='upload-container'>
                <div className='post-form-container'>
                    <p id='upload-form-label'>Hello, feel free to post an image!</p>
                    <form
                        // onSubmit={'return Validate(this);'}

                        onSubmit={postUserImage}
                        className='upload-form'
                    >
                        <div className='panel'>
                            <div className='button_outer'>
                                <div className='btn_upload'>
                                    <input
                                        filename={file}
                                        onChange={(e) => onAddImage(e.target.files[0])}
                                        type='file'
                                        accept='.jpeg,.svg,.gif,.png'
                                        id='image-selection-btn'
                                    ></input>
                                    Choose your Art
                                </div>
                            </div>
                        </div>
                        <input
                            type='text'
                            className='form-control'
                            placeholder='Enter Title'
                            id='cred-input'
                            value={formValues.title}
                            onChange={handleChange}
                            initialValues={initialValues}
                        />

                        <button type='submit' id='post-upload-btn'>
                            Upload Image
                        </button>
                    </form>
                </div>
            </div>
        </div>
    );
}

export default Uploads;

A responsive Web-Server (Html page) to Handel HTTP request

I have some issues creating an Html page that reacts as a web server. Whit that I mean, there are other pages that send get/post requests every minute to this URL to add some content to this page. I want this webpage to be able to listen to any incoming HTTP request and show the new content on the page. Then from this webpage, everything will be written to a database. Is it even possible to do so?! And what are you recommending for such a process(Ajax, nod.js, …)?!
I have my Html page running on my server. I tried to reload the page with javascript every minute to collect the new get/post requests but I was not successful To make it work properly?!
I appreciate any hint?!!

Thanks

Edit Functionality React

import React, { useEffect, useState } from 'react'
import '../assets/css/popup.css';
import { IoIosCloseCircle } from "react-icons/io";
import axios from 'axios';
import {useParams } from 'react-router-dom';

const Edit= ({closeSuspenduser}) => {
  const [categories, setCategories] =  useState([]);
  const [data, setData] = useState ({
    title: "",
    serialnumber: "",
    price: "",
    category: "",
    description: "" 
  })

  const [profile, setProfile] = useState([]);
        const {assetId } = useParams();
    
  const getAssetProfile = (assetId) => {
      axios.get(`/assets/${assetId}`, {
          responseType: 'json'
      }).then(response => {
          if (response.status === 200) {
              console.log(response.data)
              setProfile(response.data)
          }
      })
  }
  useEffect(() => {
      if (assetId) {
          getAssetProfile(assetId);
      } 
  }, [assetId])

  function submit(e) {
    e.preventDefault();
    axios.put(`/assets/${assetId}`, {
      title: data.title,
      serialnumber: data.serialnumber,
      price: data.price,
      category: data.categorie_id,
      description: data.description
    })
    
    .then(res => {
      console.log(res.data)
      window.location.href = "../Assets";
    })
  }
  function handle(e) {
    const newdata ={ ...data }
    newdata[e.target.id] = e.target.value
    setData(newdata)
    console.log(newdata)
  }
             
  return(
    <div>
    <div className='popup'>
      <div className='popup-content'>
        <div className='popupheader'>
          <h3>EDIT ASSET</h3>
          <button className='close'onClick={() => closeSuspenduser(false)}>
            <IoIosCloseCircle size='2rem' color='var(--gray)' className='closebtn'/>
          </button>
        </div>
        <div className='popup-main'>
          <form onSubmit={(e) => submit(e)}>
            <div className='email'>
              <h4>ASSET NAME</h4>
              <input type='text' placeholder={profile.title} onChange={(e) => handle(e)} id="title" value={data.title}/>
            </div>
            <div className='username'>
              <h4>SERIAL NUMBER</h4>
              <input type='text' placeholder={profile.serialnumber} onChange={(e) => handle(e)} id="serialnumber" value={data.serialnumber}/>
            </div>
            <div className='password'>
              <h4>PRICE</h4>
              <input type='number' placeholder={profile.price} onChange={(e) => handle(e)} id="price" value={data.price}/>
            </div>
            <div className='password'>
              <h4>DATE PURCHASED</h4>
              <input type='date' onfocus="(this.type='date')" onblur="(this.type='text')" placeholder={profile.purchase_date} onChange={(e) => handle(e)} id="purchase_date" value={data.purchase_date}/>
            </div>
            <div className='assign-assets'>
              <h4>CATEGORY</h4>
              {/* <select>
                <option disabled selected value="">{profile.categorie[0].title}</option>
                {
              categories.map((val) => {
                return(
                <option onChange={(e) => handle(e)} id="category" value={data.category.}>{val.title}</option>
                                )})
                              }
              </select> */}
            </div>
            <div className='accessories'>
              <h4>DESCRIPTION</h4>
              <input type='text' placeholder={profile.description} onChange={(e) => handle(e)} id="description" value={data.description}/>
            </div>
            <button className='createuser'>
              SAVE EDITS
            </button>
          </form>
        </div>
      </div>
    </div>
    </div>
  )
}
          export default Edit;

this is an edit popup; I am trying to view the previous data information in the input so as to edit.
Also while editing a specific input, I am losing all the previous data …
How do I retain the previous information after editing so I can save all of them instead of re-editing every input in the form

I manage to upload the image but on the firebase storage but it says undefined

I cant preview the image inside the store, it says undefined I manage to upload it on images/ folder but the name of the file is undefined instead of the actual name of the image

enter image description here

const uploadFile = () => {



  console.log(selectedImages);
  const storageRef = ref(storage, 'images/' + selectedImages.name);

  const uploadTask = uploadBytesResumable(storageRef, selectedImages, metadata);
  console.log(selectedImages);

  uploadTask.on('state_changed',
    (snapshot) => {

      const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
      console.log(progress);
      console.log('Upload is ' + progress + '% done');
      switch (snapshot.state) {
        case 'paused':
          console.log('Upload is paused');
          break;
        case 'running':
          console.log('Upload is running');
          break;
        default:
          break;
      }
    },
    (error) => {
      console.log(error);
    },
    () => {
      // Upload completed successfully, now we can get the download URL
      getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
        console.log('File available at', downloadURL);
      });
    }
  );

};

why isn’t setState working even after using async await function [duplicate]

I’m trying to set images after uploading them to cloud, but seems like i’m missing something .
The output is not as desired . I expect the output to be having all the three array elements.
But it is just 0 instead.

import React, { Fragment, useState } from "react";

const App = () => {
  const [image, setimages] = useState([]);
  var array = ["a", "b", "c"];

  const upload = async () => {
    for (let i = 0; i < 3; i++) {
      setimages((pre) => [...pre, array[i]]);
    }
  };

  const onClick = async () => {
    await upload();
    const myForm = {
      formImages: image,
    };
    console.log("Form details", myForm);
  };

  return (
    <>
      <div className="container">
        <button
          type="button"
          onClick={onClick}
        >
          Click me
        </button>
      </div>
    </>
  );
};

export default App;

Desired Ouput is

Form details {formImages: Array(3)}

But the actual output is

Form details {formImages: Array(0)}
            

How to actually wait until everthing gets filled ,because when i click the button again, the array is actually filled with a,b,c . I want this to happen in the first iteration

Making a loop slider

I’m following this great solution to make a slider https://stackoverflow.com/a/70340585/18736427

It uses a good technique where once the slide reaches the last one, it will insert the first/last one into the previous/last place to make a loop effect.

However, this effect is instant…When you click next once it reaches the last slide, the first slide will always immediately be inserted once the last slide is reached which causes a weird animation sight.

You can run the code snippet to have an idea, the animation looks good before 5, but it will be weird after it.

I’ve tried the setTimeout method but it looks even weird because it just flies over to the right side every time when you click the next button.

// slider
const slides = document.getElementsByClassName("slide"); // this selection is a live collection; any changes in DOM is updated in the variable unlike querySelectors
const btnLeft = document.querySelector(`.btn-left`);
const btnRight = document.querySelector(`.btn-right`);

let currentSlideIndex = 0;
let lastSlideIndex = slides.length - 1;

// go to a slide;
function goToSlide(slideIndex) {
    [...slides].forEach((s, i) => {
        s.style.transform = `translateX(${110 * (i - slideIndex)}%)`
    })
    currentSlideIndex = slideIndex;
}
goToSlide(currentSlideIndex);

// make ready the next slide if current slide is the first or the last slide
function readyNextSlide() {
    // if currentSlide is the last slide, shift the first slide to the end
    if (currentSlideIndex === lastSlideIndex) {
        slides[lastSlideIndex].insertAdjacentElement("afterend", slides[0]);
        slides[lastSlideIndex].style.transform = `translateX(${110}%)`;
        currentSlideIndex--; //this is because current slide is now the second last slide
    }
    // if currentSlide is the first slide, shift the last slide to the beginning
    if (currentSlideIndex === 0) {
        slides[0].insertAdjacentElement("beforebegin", slides[lastSlideIndex]);
        slides[0].style.transform = `translateX(-${110}%)`;
        currentSlideIndex++; //this is because current slide is now the second slide
    }
}

// put the last slide in the beginning; ('if' condition is not necessary but providing if condition is future proof if user sets the initial slide to be shown as the last slide )
if (currentSlideIndex === lastSlideIndex || currentSlideIndex === 0) readyNextSlide();

// shift all slides left or right based on direction provided
function shiftSlides(direction) {
    direction ? currentSlideIndex++ : currentSlideIndex--
    if (currentSlideIndex === lastSlideIndex || currentSlideIndex === 0) readyNextSlide();
    goToSlide(currentSlideIndex);
}

//button click events
btnRight.addEventListener("click", shiftSlides.bind(null, 1));
btnLeft.addEventListener("click", shiftSlides.bind(null, 0));
body {
  display: grid;
  height: 100vh;
  width: 100vw;
  align-items: center;
  align-content: center;
  justify-content: center;
}

.slider {
  display: flex;
  justify-content: center;
  position: relative;
  width: 600px;
  height: 300px;
  transform: scale(0.8);
  overflow: hidden; /* remove overflow to see what's going on*/
}

.slide {
  position: absolute;
  width: 50%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 1s;
}

.slide b {
  position: absolute;
  font-size: 10em;
  color: black;
  opacity: 0.6;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.s1 {
  background-color: cornflowerblue;
}

.s2 {
  background-color: bisque;
}

.s3 {
  background-color: coral;
}

.s4 {
  background-color: thistle;
}

.btn {
  position: absolute;
  top: 50%;
  z-index: 10;
  border: none;
  background: crimson;
  font-family: inherit;
  color: white;
  height: 5.5rem;
  width: 5.5rem;
  font-size: 3.25rem;
  cursor: pointer;
}

.btn-left {
  left: 6%;
  transform: translate(-50%, -50%);
}

.btn-right {
  right: 6%;
  transform: translate(50%, -50%);
}
<div class="slider">
    <div class="slide s1"><b>1</b></div>
    <div class="slide s2"><b>2</b></div>
    <div class="slide s3"><b>3</b></div>
    <div class="slide s4"><b>4</b></div>
    <div class="slide s4"><b>5</b></div>
    <div class="slide s4"><b>6</b></div>

    <button class="btn btn-left">&larr;</button>
    <button class="btn btn-right">&rarr;</button>
</div>

Compare key and get neatest min key and it’s value in JavaScript array of object

I have JS object like this

{
        "100": {.. data },
        "200": {.. data },
        "500": {.. data },
        "1000": {.. data }
    /* so on */
            
    }

here how to search key with any number like 
if search number is between 0 to 99 then it will return false,
if search number is between 100 to 199 then i t will return key 100 and it's value 
if 500 to 999 then return key 500 and it's value 
if 1000+ then key as 1000 and it's value