I am using HighCharts . On x-axis always have start date , intermediate dates , end date . Please read the description for the problem i am facing

I am using HighCharts .
On the x-axis i am trying to plot dates . The dates are coming from api. The api is dynamic , I can have weekly , monthly, yearly data . basically the data is huge.

What i need to do : On the x-axis I have to always show the start date (first element of array) , i have to always show the end date (last element of the array) . the intermediate dates(elements between first element and last element).I can’t show all the intermediate dates because they will be huge . So i am looking for a solution that should have start date , some intermediate dates , end date .

problem i am facing : When i show start date and end date , i want the library to automatically adjust the intermediate dates .this is not happening . It only shows start date and end date .

this question is specific to highcharts . I am uisng Javascript .

Why aren’t my getters and setters working for title but they are working fine for description?

I’m trying to build a todo list and i’ve got a ‘createBasicTodo’ factory function that is being invoked in my standard ‘createTodo’ function. I’m trying to restructure this to use getters/setters in some places. In the below code, the getters and setters aren’t working for the createBasicTodo (being invoked from createTodo) but they are working for the description property in the todo. I can’t figure out why this is. What am I doing wrong?

// basic todo functionality for parent & child todos
export const createBasicTodo = ({ title, priority = 'medium' }) => {
  if (!title) return throwError('Give your Todo a title!');

  console.log(title);

  let todoTitle = validateString(title);
  console.log(todoTitle);
  
  return {
    get title() {
      console.log('getting title');
      return todoTitle;
    },
    set title(newVal) {
      console.log('setting title');
      const validatedTitle = validateString(newVal);
      if (validatedTitle) {
        todoTitle = validatedTitle
      } else {
        throwError("please enter a valid title!");
      }
    },
    priority: priorityProperty(priority),
    isComplete: completionProperty(),
  };
}

// parent todo built off basicTodo using composition
export const createTodo = ({ title, description = '', priority = "medium", dueDate = null }) => {
  let todoPriority = priority;
  let todoDueDate = dueDate;
  let basicTodo = createBasicTodo({ title, priority });

  console.log(basicTodo);

  return {
    ...basicTodo,
    get description() {
      console.log('getting description');
      return description;
    },
    set description(newVal) {
      console.log('setting description');
      description = newVal;
    },
    checklist: checklistProperty(createBasicTodo),
    dueDate: dateProperty(dueDate),
  }
}

I am expecting to see the console.logs when I view or change the test todo’s title. I’m not seeing them and am able to set thew title to invalid values.

Why object properties are getting undefined?

In my usecase of creating flights, I need to get the total capacity of the airplane whose id is provided by the user.so for that I am retrieving the airplane object from the table with the id specified.
The code for the same is as follows:

Repository layer code to get the airplane:

async get(id){
        console.log(id);
        try{
            const modelData=await this.model.find({
                where:{id}
            })
            console.log(modelData);
            return modelData;
        }
        catch(error){
            console.log("Something went wrong in the repository layer "+ error);
        }
    }

Flight creation code in service layer:

async create(data){
       
        try{
            const airplane = await this.airplaneRepo.get(data.airplaneId);
            console.log(airplane);
            const flight =await this.crudRepo.create(data);
            return flight;
        }
        catch(error){
            console.log("Something went wrong in the service layer " + error );
        }
    }

So when I log the airplane as in the above code, Im getting the following object:

[
  Airplane {
    dataValues: {
      id: 1,
      modelNumber: 'Boeing 737',
      capacity: 250,
      createdAt: 2023-12-19T12:07:24.000Z,
      updatedAt: 2023-12-19T12:07:24.000Z
    },
    _previousDataValues: {
      id: 1,
      modelNumber: 'Boeing 737',
      capacity: 250,
      createdAt: 2023-12-19T12:07:24.000Z,
      updatedAt: 2023-12-19T12:07:24.000Z
    },
    uniqno: 1,
    _changed: Set(0) {},
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      raw: true,
      attributes: [Array]
    },
    isNewRecord: false
  }
]

When I try to access capacity property of this airplane, it gives me undefined.

Facing Error: Uncaught RangeError – Maximum call stack size exceeded

When i Click Add to cart button then I’m encountering an "Uncaught RangeError: Maximum call stack size exceeded" error in my application.After investigating, it appears to be related to the handleAddCart function in the Product.js file. It seems there might be an unintentional infinite recursion happening within this function.

I tried every possible solution which came in my mind and i did fixed it.

As i am learning redux-toolkit please fixed my error. Your help will be kindly appreciated

Here is my code:

//productSlice.js

import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from "axios";

export const fetchProduct = createAsyncThunk("fetchProduct", async () => {
  try {
    const res = await axios.get("https://dummyjson.com/products");
    const data = await res.data.products;
    return data;
  } catch (error) {
    console.log(error);
    throw error;
  }
});

const initialState = {
  products: [],
  isLoading: false,
  isError: false,
};

const productSlice = createSlice({
  name: "product",
  initialState,
  reducers: {
    setProduct: (state, action) => {
      state.products = action.payload;
    },
  },
  extraReducers: (builder) => {
    builder.addCase(fetchProduct.pending, (state, action) => {
      state.isLoading = action.payload;
    });
    builder.addCase(fetchProduct.fulfilled, (state, action) => {
      state.products = action.payload;
    });
    builder.addCase(fetchProduct.rejected, (state, action) => {
      console.log("Error:", action.payload);
      state.isError = true;
    });
  },
});

export const { setProduct } = productSlice.actions;

export default productSlice.reducer;

//cartSlice.js

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  cart: [],
};

const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    addToCart: (state, action) => {
      state.cart.push(action.payload);
    },
    removeFromCart: (state, action) => {
      return state.filter((item) => item.id !== action.payload);
    },
    incrementItemInCart: (state, action) => {},
    decrementItemInCart: (state, action) => {},
  },
});

export const {
  addToCart,
  removeFromCart,
  incrementItemInCart,
  decrementItemInCart,
} = cartSlice.actions;

export default cartSlice.reducer;



// store.js

import { configureStore } from "@reduxjs/toolkit";
import cartReducer from "./slice/cartSlice";
import productReducer from "./slice/productSlice";

export const store = configureStore({
  reducer: {
    cart: cartReducer,
    product: productReducer,
  },
});


//Product.js

import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { fetchProduct } from "../redux/slice/productSlice";
import { Link } from "react-router-dom";
import "./style.css";
import Navbar from "./Navbar";

const Product = () => {
  const dispatch = useDispatch();
  const products = useSelector((state) => state.product.products);

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

  const getPriceAfterDiscount = (price, dis) => {
    var p = price - price * (dis / 100);
    return p.toFixed(2);
  };

  const getFirstLine = (text) => {
    if (!text) return "";
    return text.length > 50 ? text.substring(0, 50) + "..." : text;
  };

  const handleAddCart = (item) => {
    dispatch(handleAddCart(item));
  };

  return (
    <>
      <Navbar />
      <div className="products">
        <h2>Welcome to redux toolkit store</h2>
        <h2>Products</h2>
        <div className="products-wrapper">
          {products.map((item) => (
            <div className="product-card">
              <div className="badge">Hot</div>
              <div className="product-tumb">
                <img src={item.thumbnail} alt="" />
              </div>
              <div className="product-details">
                <span className="product-catagory">{item.category}</span>
                <h4>
                  <Link style={{ fontSize: "14px" }} href="">
                    {item.title}
                  </Link>
                </h4>
                <p style={{ fontSize: "8px", margin: 0 }}>
                  {getFirstLine(item.description)}
                </p>
                <div className="product-bottom-details">
                  <div className="product-price">
                    <small>${item.price}</small>$
                    {getPriceAfterDiscount(item.price, item.discountPercentage)}
                  </div>
                  <div className="product-links">
                    <button onClick={() => handleAddCart(item)}>
                      Add to cart
                    </button>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </>
  );
};

export default Product;

solana/web3.js connection not working : fetch Failed

const connection = new web3.Connection(
web3.clusterApiUrl(‘testnet’,false),
‘confirmed’,
);
console.log(await connection.getBlockTime());

I got this error:
TypeError: fetch failed
at node:internal/deps/undici/undici:12442:11
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async ClientBrowser.callServer (/mnt/d/solang/hello/node_modules/@solana/web3.js/lib/index.cjs.js:6454:17) { cause: ConnectTimeoutError: Connect Timeout Error
at onConnectTimeout (node:internal/deps/undici/undici:7595:28)
at node:internal/deps/undici/undici:7551:50
at Immediate._onImmediate (node:internal/deps/undici/undici:7583:13)
at process.processImmediate (node:internal/timers:478:21) {
code: ‘UND_ERR_CONNECT_TIMEOUT’
}
}

i was expecting to get the blocktime

How to dynamically import() in SvelteKit?

I am trying to import all SVGs from a folder and display them in another component using SvelteKit 2.
SVGs are loaded as components with: ‘@poppanator/sveltekit-svg’

for (const path in import.meta.glob('$lib/img/icon/technology/*.svg')) {
    const technology_name = path.split('/').pop().split('.')[0]
    const import_string = `${base}${path}?component` // base = ''
    technologies_import_promisses[technology_name] =
        import(/* @vite-ignore */import_string)                 //1 works in dev
        // import(/* @vite-ignore */`${base}${path}?component`) //2 doesnt work
        // import(/* @vite-ignore */base + path + '?component') //3 works in dev
        // import(/* @vite-ignore */'$lib/img/icon/technology/'+technology_name+'.svg?component') //4 doesnt work
        // import(/* @vite-ignore */'$lib/img/icon/technology/python.svg?component') //5 works even in build
}

// some other component:

//{#await component} // let component = technologies_import_promisses['some_technology']
//    <Fallback class="w-8 h-8"/>
//{:then com}
//    {#if com}
//        <svelte:component this={com?.default} class=" w-8 h-8"/>
//    {:else}
//        <Fallback class="w-8 h-8"/>
//    {/if}
//{/await}

i dont understand why is it so strange with import()
how to make it work both in build and dev ?
should i consider totaly different aproach ?

Getting req.body empty while using FormData API with multer

I am working on a project which takes image files and other data on the mongo db. While registring user i am taking a profile picture and it is uploading correctly. And once the user register by selecting role as caregiver, then i am giving them the form for applying for caregiver account in which i am taking certificates(array) images and they also are uploading without any issue. But the issue is when i try to update the profile with new profile picture and certificates then I am unable to recieve data on the backend. And it works fine with other routes but with this route I am getting req.body as empty and getting this on console : http://localhost:8070/undefined 404

This is my modal for updating profile:

import {
  Avatar,
  Box,
  Button,
  Chip,
  Modal,
  Paper,
  TextField,
  Typography,
} from "@mui/material";
import { useEffect, useState } from "react";
import { AiOutlineCloudUpload } from "react-icons/ai";
import { useDispatch, useSelector } from "react-redux";
import { hideLoading, showLoading } from "../../redux/features/alertSlice";
import axios from "axios";
import { toast } from "react-toastify";
import { useParams } from "react-router-dom";

const UpdateProfileModal = ({ isOpen, onClose, caregiver }) => {
  const [editedData, setEditedData] = useState(null);

  const { user } = useSelector((state) => state.user);
  const dispatch = useDispatch();
  const params = useParams();

  const [profilePictureDisplay, setProfilePictureDisplay] = useState(null);

  useEffect(() => {
    const getNurseInfo = async () => {
      try {
        const res = await axios.post(
          "http://localhost:8070/api/v1/caregiver/getCaregiverInfo",
          { userId: params.id },
          {
            headers: {
              Authorization: `Bearer ${localStorage.getItem("token")}`,
            },
          }
        );
        if (res.data.success) {
          setEditedData(res.data.data);
        }
      } catch (error) {
        console.log(error);
      }
    };
    getNurseInfo();
  }, [params.id]);

  const handleInputChange = (e) => {
    const { name, value } = e.target;

    // Special handling for preferredCities to convert the string to an array
    if (name === "preferredCities") {
      const citiesArray = value.split(",").map((city) => city.trim());
      setEditedData((prevData) => ({
        ...prevData,
        [name]: citiesArray,
      }));
    } else if (name === "qualification") {
      const qualArray = value.split(",").map((qual) => qual.trim());
      setEditedData((prevData) => ({
        ...prevData,
        [name]: qualArray,
      }));
    } else if (name === "specialisation") {
      const specArray = value.split(",").map((spec) => spec.trim());
      setEditedData((prevData) => ({
        ...prevData,
        [name]: specArray,
      }));
    } else {
      // For other fields, directly update the state
      setEditedData((prevData) => ({
        ...prevData,
        [name]: value,
      }));
    }
  };


  const handleFileChange = (event) => {
    const file = event.target.files[0];
    if (file) {
      setProfilePictureDisplay(URL.createObjectURL(file));

      setEditedData((prevData) => ({
        ...prevData,
        profilePicture: file,
      }));
    }
  };

  const handleCertificateImageChange = (e) => {
    const files = e.target.files;
    const fileList = Array.from(files);

    const imageFiles = fileList.filter((file) =>
      file.type.startsWith("image/")
    );

    setEditedData((prevData) => ({
      ...prevData,
      certifications: [...prevData.certifications, ...imageFiles],
    }));
  };

  const removeCertificate = (certificate) => {
    setEditedData((prevData) => ({
      ...prevData,
      certifications: prevData.certifications.filter(
        (cert) => cert !== certificate
      ),
    }));
  };

  const handleSumbit = async (e) => {
    e.preventDefault();
    
    const formdata = new FormData();
    formdata.append("userId", user._id);
    formdata.append("name", editedData.name);
    formdata.append("address", editedData.address);
    formdata.append("yearsExperience", editedData.yearsExperience);
    formdata.append("feesPerDay", editedData.feesPerDay);
    formdata.append("description", editedData.description);
    formdata.append("ageRange", editedData.ageRange);
    formdata.append("availability", editedData.availability);
    formdata.append(
      "preferredCities",
      JSON.stringify(editedData.preferredCities)
    );
    formdata.append("qualification", JSON.stringify(editedData.qualification));
    formdata.append(
      "specialisation",
      JSON.stringify(editedData.specialisation)
    );

    formdata.append("profilePicture", editedData.profilePicture);
    editedData.certifications.forEach((certification, index) => {
      formdata.append(`certifications[${index}]`, certification);
    });


    try {
      dispatch(showLoading());
      const res = await axios.patch(
        "http://localhost:8070/api/v1/caregiver/updateCaregiver",
        formdata,
        {
          headers: {
            Authorization: `Bearer ${localStorage.getItem("token")}`,
            "Content-Type": "multipart/form-data",
          },
        }
      );
      dispatch(hideLoading());
      if (res.data.success) {
        toast.success(res.data.message, {
          position: toast.POSITION.TOP_CENTER,
        });
        onClose();
      } else {
        toast.error(res.data.message, {
          position: toast.POSITION.TOP_CENTER,
        });
      }
    } catch (error) {
      dispatch(hideLoading());
      console.log(error);
      toast.error("Something went wrong", {
        position: toast.POSITION.TOP_CENTER,
      });
    }
  };

  return (
    <>
      <div className="">
        <Modal
          open={isOpen}
          onClose={onClose}
          className="flex items-center justify-center pt-44  overflow-y-scroll"
        >
          <div className="">
            <form
              action=""
              method="patch"
              encType="multipart/form-data"
              className="max-w-4xl"
              onSubmit={handleSumbit}
            >
              <Box className="mt-14">
                <Paper elevation={3} className="p-6">
                  <div className="bg-white p-4">
                    {/* Profile Picture and Avatar */}
                    <div className="flex items-center space-x-4">
                      <div className="bg-white p-3 rounded shadow-md w-full">
                        <div className="mt-1 bg-[#f3f4f6] flex items-center justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md">
                          <div className="space-y-1 text-center">
                            <label
                              htmlFor="file-upload"
                              className="relative cursor-pointer rounded-md font-medium text-indigo-600 hover:text-indigo-500 focus-within:outline-none focus-within:border-indigo-300"
                            >
                              <span className="flex items-center justify-center gap-1">
                                <AiOutlineCloudUpload /> Upload a profile
                                picture
                              </span>
                              <input
                                id="file-upload"
                                name="profilePicture"
                                type="file"
                                accept="image/png,image/jpg,image/jpeg"
                                className="sr-only"
                                onChange={handleFileChange}
                              />
                            </label>
                            <p className="text-xs text-gray-500">
                              PNG, JPG, JPEG up to 10MB
                            </p>
                          </div>
                        </div>
                      </div>
                      <Box>
                        <Avatar
                          alt="Profile Picture"
                          src={`http://localhost:8070/${editedData?.profilePicture}`}
                          sx={{ width: 100, height: 100 }}
                        />
                      </Box>
                    </div>

                    <div className=" flex items-start justify-start gap-3">
                      {/* Name */}
                      <TextField
                        label="Name"
                        name="name"
                        value={editedData?.name}
                        onChange={handleInputChange}
                        fullWidth
                        className="mb-2"
                      />

                      {/* Address */}
                      <TextField
                        label="Address"
                        name="address"
                        value={editedData?.address}
                        onChange={handleInputChange}
                        fullWidth
                        className="mb-2"
                      />
                    </div>

                    <TextField
                      label="Years of experience"
                      name="yearsExperience"
                      value={editedData?.yearsExperience}
                      onChange={handleInputChange}
                      fullWidth
                      className="mb-2"
                    />
                    <div className=" flex items-start justify-start gap-3">
                      {/* Age Range */}
                      <TextField
                        label="Age Range Lower Limit"
                        value={editedData?.ageRange?.lowerLimit}
                        name="ageRange"
                        onChange={handleInputChange}
                        fullWidth
                        className="mb-2"
                      />
                      <TextField
                        label="Age Range Upper Limit"
                        value={editedData?.ageRange?.upperLimit}
                        name="ageRange"
                        onChange={handleInputChange}
                        fullWidth
                        className="mb-2"
                      />
                    </div>

                    {/* Availability */}
                    <TextField
                      label="Availability"
                      name="availability"
                      value={editedData?.availability}
                      onChange={handleInputChange}
                      fullWidth
                      className="mb-2"
                    />

                    {/* Certifications */}
                    <div className="flex items-start justify-center flex-col space-y-2 ">
                      <div className="bg-white p-3 rounded shadow-md  w-full">
                        <div className="mt-1 bg-[#f3f4f6] flex items-center justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md">
                          <div className="space-y-1 text-center ">
                            <label
                              htmlFor="file-upload"
                              className="relative cursor-pointer rounded-md font-medium text-indigo-600 hover:text-indigo-500 focus-within:outline-none focus-within:border-indigo-300"
                            >
                              <span className="flex items-center justify-center gap-1">
                                <AiOutlineCloudUpload />
                                Upload a file (certificates if any)
                              </span>
                              <input
                                id="file-upload"
                                name="certifications"
                                multiple
                                type="file"
                                accept="image/png,image/jpg,image/jpeg"
                                className="sr-only"
                                onChange={handleCertificateImageChange}
                              />
                            </label>
                            <p className="text-xs text-gray-500">
                              PNG, JPG, JPEG up to 10MB
                            </p>
                          </div>
                        </div>
                      </div>
                      <div className="h-4">
                        <span className="text-red-500 text-sm mt-1"></span>
                      </div>
                      <div className="flex items-center justify-start gap-2 w-full flex-wrap">
                        {editedData?.certifications &&
                          editedData?.certifications?.map((img, index) => {
                            return (
                              <>
                                <div>
                                  <Chip
                                    key={index}
                                    label={img}
                                    onDelete={() => removeCertificate(img)}
                                  />
                                  <a
                                    href={`http://localhost:8070/${img}`}
                                    rel="noreferrer"
                                    target="_blank"
                                  >
                                    Veiw
                                  </a>
                                </div>
                              </>
                            );
                          })}
                      </div>
                    </div>
                    {/* <TextField
                  label="Certifications"
                  name="certifications"
                  value={editedData.certifications.join(", ")}
                  onChange={handleInputChange}
                  fullWidth
                  className="mb-2"
                /> */}

                    {/* <div className=" flex items-start justify-start gap-3"> */}
                    {/* City */}
                    <TextField
                      label="City"
                      name="city"
                      value={editedData?.city}
                      onChange={handleInputChange}
                      fullWidth
                      className="mb-2"
                    />

                    {/* Preferred Cities */}
                    <div className="mb-2">
                      <TextField
                        label="Preferred cities"
                        name="preferredCities"
                        value={editedData?.preferredCities.join(", ")}
                        onChange={handleInputChange}
                        fullWidth
                        className="mb-2"
                      />
                      <TextField
                        label="Qualification"
                        name="qualification"
                        value={editedData?.qualification.join(", ")}
                        onChange={handleInputChange}
                        fullWidth
                        className="mb-2"
                      />
                      {/* <div>
                    {editedData.preferredCities.map((city, index) => (
                      <Chip key={index} label={city} className="mr-1 mb-1" />
                    ))}
                  </div> */}
                    </div>
                    {/* </div> */}
                    <TextField
                      label="Specialisation"
                      name="specialisation"
                      value={editedData?.specialisation.join(", ")}
                      onChange={handleInputChange}
                      fullWidth
                      className="mb-2"
                    />

                    <Button
                      variant="contained"
                      type="submit"
                      className="py-2 px-4 w-full bg-[#1976d2] hover:bg-[#1565c0]"
                    >
                      Save Changes
                    </Button>
                  </div>
                </Paper>
              </Box>
            </form>
          </div>
        </Modal>
      </div>
    </>
  );
};

export default UpdateProfileModal;

This is my server.js

const express = require("express");
const morgan = require("morgan");
const dotenv = require("dotenv");
const connnectDB = require("./config/db");
const cors = require('cors')
const path = require("path")

// dotenv config
dotenv.config();

//mongodb connection
connnectDB();

//rest object
const app = express();

//allow requests from frontend
app.use(cors({
  origin: ['http://localhost:5173']
}))

// middlewares
app.use(express.json());
app.use(morgan("dev"));
// Example configuration
app.use(express.urlencoded({ extended: true }));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));


// Handle file upload
// app.use('/api/v1/upload', upload.single('image'), require("./routes/uploadRoutes"))
// routes
app.use('/api/v1/user', require('./routes/userRoutes'))
app.use('/api/v1/admin', require('./routes/adminRoutes'))
app.use('/api/v1/caregiver', require('./routes/caregiverRoutes'))

//port
const port = process.env.PORT || 8070;

//listen port
app.listen(port, () => {
  console.log(
    `Server running in ${process.env.NODE_MODE} mode on port ${process.env.PORT}`
  );
});

This is my route

router.patch('/updateCaregiver', upload.single('profilePicture'), upload.array('certifications', 10), authMiddleware, updateCaregiverController)

CaregiverController

const updateCaregiverController = async (req, res) => {
    try {
        const user = await userModel.findOne({ _id: req.body.userId })
        const caregiver = await caregiverModel.findOne({ userId: req.body.userId })
        // const ageRange = JSON.parse(req.body.ageRange)
        let updatedCaregiver
        let updatedUser
        const {
            name,
            address,
            yearsExperience,
            feesPerDay,
            preferredCities,
            description,
            qualification,
            specialisation,
            ageRange,
            availability,
            userId
        } = req.body;

        console.log("REQUEST BODY:", req.body);

        if (caregiver) {
            updatedCaregiver = await caregiverModel.findOneAndUpdate({ userId: userId }, {
                yearsExperience,
                feesPerDay,
                preferredCities,
                description,
                qualification,
                specialisation, ageRange, availability
            }, {
                runValidators: true, new: true
            })
            if (req.files && req.files.certifications) {
                updatedCaregiver.certifications = req.files.certifications.map(file => file.path);
                await updatedCaregiver.save();
            }
        }

        if (user) {
            updatedUser = await userModel.findOneAndUpdate(
                { _id: req.body.userId },
                {
                    name,
                    address,
                },
                { runValidators: true, new: true }
            );

            if (req.files && req.files.profilePicture && req.files.profilePicture.length > 0) {
                updatedUser = await userModel.findOneAndUpdate(
                    { _id: req.body.userId },
                    {

                        profilePicture: req.files.profilePicture[0].path
                    },
                    { runValidators: true, new: true }
                );

                updatedUser.profilePicture = req.files.profilePicture[0].path;
                await updatedUser.save();
            }

        }

        const data = Object.assign(updatedCaregiver, updatedUser)
        res.status(200).send({
            success: true,
            message: "Profile updated successfully",
            data
        });

    } catch (error) {
        console.log(error)
        res.status(500).send({
            success: false,
            message: "Error while updating nurse details",
            error
        })
    }
}

multerConfig.js

const multer = require('multer');
const path = require('path');

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/');
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + '-' + file.originalname);
    },
});

const upload = multer({ storage: storage });

module.exports = upload;

Any help would be appreciated!
Thank you!

How to transpose an Excel spreadsheet using Excel Javascript on Mac

So in my Excel spreadsheet, there is column A which are events and column B which are categories. A1 and B1 are both headers and can be excluded from the transformation. I am trying to write a script that takes all the unique categories from column B and transposes it horizontally. These will become the new headers and then column A data will be populated underneath these new headers if the categories match in column B. I am having such a hard time getting this to work and would appreciate any help.

If I do it manually, I use the following two Excel formulas: =TRANSPOSE(UNIQUE(OFFSET(B2,0,0,COUNTA(B:B)-1)))
=IF(D2<>””, FILTER($A:$A,$B:$B=D2), “”)

But if I am automating it with a script, I can get it as far as transposing it on my Excel spreadsheet, but can’t figure out how to then populate column A information underneath.

function main(workbook: ExcelScript.Workbook) {
    const worksheet = workbook.getActiveWorksheet();

  // Extract unique values from Column B (excluding header)
    const uniqueValuesRange = worksheet.getRange("B2:B" + worksheet.getUsedRange().getRowCount());
    const uniqueValues: string[][] = uniqueValuesRange.getValues();
    const uniqueRetentionCategories: string[] = uniqueValues.reduce((acc, row) => acc.concat(row), []).filter((value, index, self) => self.indexOf(value) === index);

    // Transpose unique values starting from cell D2 going horizontally
    const transposed2DArray: string[][] = [uniqueRetentionCategories]; // Create 2D array
    const startRange = worksheet.getRange("D2");
    for (let i = 0; i < transposed2DArray.length; i++) {
        for (let j = 0; j < transposed2DArray[i].length; j++) {
            const cell = startRange.getCell(i, j);
            cell.setValue(transposed2DArray[i][j]);
        }
    }
}

Three JS, InstanceMesh’s Dots overlapping and Gaps

enter image description here
Hi, I’m building a Globe in Three Js, and i want to have One Million InstanceMesh small transparent dots on it which I already archieved as you guys can see in image, but thier is some overlapping and small gaps between dots, it there any way i can remove it and distribute dots around the sphere perfectly so that there will be no spacing of overlapping. if I increase the size of the dots to reduce spacing, then overlapping becomes more and if i tried to reduce the overlapping gaps becomes more, they are in-directly proportional to each other.

I’ve tried to distribute dots around the globe in many different ways like Fibonacci, grid-base, poisson disk sampling distributions but they all failed.

How to upsert multiple object by array in JS?

I have an array with an objects from which for each object i need to find if some key exist then it should update or else insert. I have done this from for loop but problem is i have approximately 20L of data which need to be run through this every morning using cron scheduler.

My question is : Can I use some other way like i pass this array to a method for better performance ?

My approach :

const arr = [{id: 1, pre: 10, post: 15 , name: 'egg'},{id: 2, pre: 10, post: 15 , name: 'egg 2'},{id: 3, pre: 10, post: 15 , name: 'egg 3'},{id: 4, pre: 10, post: 15 , name: 'egg 4'}]

for(x = 0; x < arr.length ; x++) {
   await processed_.findByIdAndUpdate({id: arr[x].id}, { $set: arr[x] }, {upsert: true, new: true})
}

Thanks for the suggestions.

How to get json data from texarea or file in js?

There is a .txt file that contains json:

{
  "com": "ip",
  "res": [
    {
      "add": "04554E9",
      "m": "6773CYU",
      "default": false,
    },
    {
      "add": "4CECEC58F23",
      "m": "32DW4N",
      "default": true,
    },
    {
      "add": "6E3458",
      "m": "9ANYJ6C5ZVAM",
      "default": true,
    }
  ]
}

Trying to loop sort add where “default”: true. Through the browser the file is in the local folder.
If you write json in the js file, everything works. The js code:

function loadJsonData() {
var cc = here's the json code

    var myArray = cc.res;
    var idToLookFor = true;
    
    var addrs = myArray
      .filter(function (item) {
        return item.default === idToLookFor;
      })
      .map(function (elem) {
        return elem.add;
      })
      .join(",");
console.log(addrs);
};

But I want to do it via file selection or textarea. I have tried all the options and I get undefined everywhere. Here are some variants I have tried:

const el = document.getElementById('benderform').addEventListener('submit', submitForm);
function submitForm(event) {
    event.preventDefault();
    let formData = new FormData(event.target);
    let obj = {};
    formData.forEach((value, key) => obj[key] = value);
    console.log(obj);
var idToLookFor = true;
    var addrs = obj.filter(function (item) {
        return item.default === idToLookFor;
      })
      .map(function (elem) {
        return elem.add;
      })
      .join(",");
      console.log(addrs);
    console.log('ok');
}</script>
<form id="benderform">
  <input name="name" value="Bender">
  <input type="submit" value="TEST">
  </form>
function loadJsonData() {
var cc = document.getElementById("dropdown").value;
    var myArray = cc.res;
    var idToLookFor = true;   
    var addrs = myArray.filter(function (item) {
        return item.default === idToLookFor; }).map(function (elem) {
        return elem.add;}).join(",");
    console.log(addrs);
};

When using the command:

$.getJSON('filename.json', function(data) {

It returns: from origin ‘null’ has been blocked by CORS policy:

Is there any way to get this data without using the server and adding the json text directly to the js file?

Chrome Extension: Button in extension is supposed to open a webpage, but return a page in the chrome extension. How do I fix this?

I am building a simple Chrome extension where the user selects a button and opens a new browser page to a randomly selected website (e.g. Stumble Upon or Cloudhiker). However, when on click, a new browser page opens but it says it’s specific to the extension and the intended URL is prepended with chrome extension data. For example: chrome-extension://hflifofppgknepfodmmkohenjknmendb/www.bing.com

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Stumble Upon Clone</title>
    <link rel="stylesheet" href="style.css" />
    <script src="scripts.js"></script>
  </head>
  <body></body>
</html>
body {
  background-color: black;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  min-height: 50vh;
  min-width: 200px;
  border-radius: 10px;
}

h1 {
  color: grey;
}
document.addEventListener('DOMContentLoaded', () => {
  const title = document.createElement('h1');
  title.innerText = 'Welcome to the Stumble Upon Clone!';
  document.querySelector('body').appendChild(title);

  const btnStumble = document.createElement('button');
  btnStumble.setAttribute('class', 'btnStumble');
  btnStumble.innerText = "Let's Stumble!";
  document.querySelector('body').appendChild(btnStumble);

  btnStumble.addEventListener('click', () => {
    const selection = randomSite();
    console.log(selection);
    window.open(selection);
  });
});

const sites = ['www.google.com', 'www.yahoo.com', 'www.bing.com'];

const randomSite = () => {
  const roll = Math.floor(Math.random() * 3);
  const choice = sites[roll];
  return choice;
};

randomSite(sites);
randomSite(sites);
randomSite(sites);

    {
      "manifest_version": 3,
      "name": "Stumble Upon Clone",
      "version": "1.0.0",
      "description": "My version of the old Stumble Upon website",
      "action": {
        "default_popup": "index.html"
      },
      "icons": {
        "48": "img/cloud.png"
      }
    }

I’ve tried changing the window.open to document.open, but that wasn’t helpful. I’m not sure what else to do at this point. Thank you for any help and insight you can provide!

PayPal IPN Listener Testing issues

I have trying to implement the PayPal IPN Service for a customer, but so far I wasn’t able to even verify the request with it’s “handshake”.

I have been sending test IPN messages with the IPN Simulator but I get every time the text “INVALID” although I am pretty sure I followed all the PayPal recommendations.

I also went through the [troubleshooting documentation][5] and I couldn’t find anything wrong in any of the codes.

Since the requirements were to use C# as the web service desired language but the PayPal documentation was outdated, I had to adjust the [C# code exmaple][4] to the current NET framework thanks to ChatGPT (because I barely know how to work with C#).

This is the C# MVC controller:

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json.Linq;
using log4net;

namespace IPN_Listener.Controllers
{
    public class IPNController : ControllerBase
    {
        private readonly HttpClient _httpClient;
        private static readonly ILog log = LogManager.GetLogger(typeof(IPNController));

        private readonly bool isProduction = false;
        private readonly string sandboxURL = "https://ipnpb.sandbox.paypal.com/cgi-bin/webscr";
        private readonly string liveURL = "https://ipnpb.paypal.com/cgi-bin/webscr";

        public IPNController(IHttpClientFactory httpClientFactory)
        {
            _httpClient = httpClientFactory.CreateClient();
        }

        [HttpPost]
        [Route("[controller]")]
        public async Task<IActionResult> Receive()
        {
            var handshakeResult = await VerifyTask(Request);

            if (handshakeResult.Equals("VERIFIED"))
            {
                await LogRequest(Request);
                log.Info("Handshake verified.");
                return Ok();
            }
            else
            {
                log.Error($"Handshake failed: {handshakeResult}");
                return BadRequest(handshakeResult);
            }
        }

        private async Task<string> VerifyTask(HttpRequest ipnRequest)
        {
            var verificationResponse = string.Empty;
            var paypalURL = isProduction ? liveURL : sandboxURL;

            try
            {
                ipnRequest.EnableBuffering();
                var requestBody = await new StreamReader(ipnRequest.Body).ReadToEndAsync();
                ipnRequest.Body.Position = 0;
                var strRequest = "cmd=_notify-validate&" + requestBody;

                var verificationRequest = new HttpRequestMessage(HttpMethod.Post, paypalURL)
                {
                    Content = new StringContent(strRequest, Encoding.UTF8, "application/x-www-form-urlencoded")
                };

                verificationRequest.Headers.Add("User-Agent", "MyCustomer-IPNListener/1.0");

                var response = await _httpClient.SendAsync(verificationRequest);
                verificationResponse = await response.Content.ReadAsStringAsync();
            }
            catch (Exception exception)
            {
                log.Error("Error during verification with PayPal", exception);
            }

            return verificationResponse;
        }

        private async Task LogRequest(HttpRequest request)
        {
            var parsedBody = await GetParsedBody(request);
            log.Info($"Received IPN message: {parsedBody}");
        }

        private async Task<string> GetParsedBody(HttpRequest request)
        {
            request.EnableBuffering();

            var requestBody = await new StreamReader(request.Body).ReadToEndAsync();
            request.Body.Position = 0;

            var formData = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(requestBody);
            var json = new JObject();
            foreach (var item in formData)
            {
                json[item.Key] = item.Value.ToString();
            }

            return json.ToString();
        }
    }
}

So, I think I created the exact same code but with Node.js and Express to test the IPN messages, but I am still getting “INVALID”.

This is the code, just in case:

const express = require('express')
const axios = require('axios')

const app = express()

app.use(express.urlencoded({ extended: true }))

app.post('/ipn', async (req, res) => {
    const rawBody = req.body
    const params = new URLSearchParams()
    params.append('cmd', '_notify-validate');
    Object.keys(rawBody).forEach(key => {
        params.append(key, rawBody[key])
    });

    try {
        // Handshake
        const response = await axios.post(
            'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr', 
            params.toString(), 
            {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'User-Agent': 'MyCompany-IPNListener/1.0'
                }
            }
        );

        if (response.data === 'VERIFIED') {
            console.log('IPN Verified')
        } else {
            console.log('IPN Verification Failed')
        }


        res.json({ test: true })
    } catch (error) {
        console.error('IPN Verification Error: ', error)
    }
});

const PORT = 4000

app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`)
})

Just as side notes:

  1. I used ngrok to expose the C# and JS web services.
  2. I was able to debug the incoming PayPal requests in Visual Studio 2022.
  3. When I was sending IPN messages to the C# web service, the IPN Simulator displayed an error message every time saying the handshake was not verified, because they weren’t; but when I tested with the Express application, I got a success message saying the handshake were verified (something wrong I guess, because I got “INVALID” every time).

So, the C# web service should work so I can proceed, but I created the Express application to visualize what I really needed to accomplish sice I would rather use JavaScript than C#.

Any ideas of what is going on that I am getting the “INVALID” message every time?

How to convert HTML template to Reactjs

I’ve converted a HTML template into React. But some of the icons / dropdowns that can be collapse are not functioning.

Dropdown is stuck

Dropdown is stuck

The menu button does not hide the left side bar

The menu button does not hide the left side bar

I’ve tried observe the related javascript files for those elements. But I think the errors are not in the javascript. I think maybe I need to use React Hooks to make the menu bar & dropdowns work, but I’m not sure.

var a;
  n("#side-menu").metisMenu(),
    n("#vertical-menu-btn").on("click", function (e) {
      e.preventDefault(),
        n("body").toggleClass("sidebar-enable"),
        992 <= n(window).width()
          ? n("body").toggleClass("vertical-collpsed")
          : n("body").removeClass("vertical-collpsed");
    }),
    n("body,html").click(function (e) {
      var t = n("#vertical-menu-btn");
      t.is(e.target) ||
        0 !== t.has(e.target).length ||
        e.target.closest("div.vertical-menu") ||
        n("body").removeClass("sidebar-enable");
    }),

Any advice or answers are greatly appreciated. Thank you.

CSS animation classes not working when applied with javascript

Based on some googling about how you can’t animate hidden (display:none) elements, I have the following:

HTML element styled with tailwind utility classes

<div class="absolute z-10 hidden overflow-hidden md:hidden transform -translate-x-20 opacity-0 transition-all duration-500 delay-100 ease-out">

And this is a small fragment of the javascript that responds to open/close events on the related hamburger button:

    // on first open of the sidebar, this should remove the 'display: none'... 
    sidebar?.classList.toggle('hidden')

    // so now these should trigger animations:
    sidebar?.classList.toggle('opacity-0') // => 100% opacity, but without transition.
    sidebar?.classList.toggle('-translate-x-20') // => correct x-pos, but without transition.