Getting error Invalid Credentials : Bcyrpt.compare()

This is the user.js

router.post("/user/signup", async (req, res) => {
try {
    const { name, email, password } = req.body;
    const hashedPassword = await bcrypt.hash(password, 8);
    console.log("this is different from the saved pass : " , hashedPassword);
    const newUser = new User({
        name : name,
        email : email,
        password: hashedPassword,
    });
    await newUser.save();
    res.status(200).send(newUser);
} catch (error) {
    console.error("Error:", error);
    res.status(500).send({ error: "Internal Server Error" });
}

});

This is he file for schema

userSchema.statics.findByCredentials = async function (email, password) {
const user = await this.findOne({ email });
if (!user) {
    throw new Error('User not found');
}

const isMatch = await bcrypt.compare(password, user.password);

if (!isMatch) {
    throw new Error('Invalid password');
}

return user;

};

This -> console.log("this is different from the saved pass: ", hashedPassword); and the password stored in the database is different what could be the problem?

The error is :

Error: Error: Invalid password
    at Function.userSchema.statics.findByCredentials (

How to change body background when clicking on li element

When I click on the “Sign Out” anchor, I want the body of my design.html document to turn black and for a pop up blurb, like a speech bubble, to pop up next to where the word sign out originally was. Having this effect means you shouldn’t be able to see “Sign Out” because the color of that list element is also black.

I’m working on the first part–getting hovering over a list element to change the color of the body of the document.

The JavaScript I’ve posted does nothing to my web page. No changes when we mouse over or mouse out.

What changes should I make to get the desired effect?

document.getElementsByTagName("li").addEventListener("mouseover", function ()
  document.body.style.background = black
);

document.getElementsByTagName("li").addEventListener("mouseout", function ()
  document.body.style.background = pink
);
body {
  position: absolute;
  text-align: center;
  width: 100%;
  height: 100%;
}

ul {
  list-style-type: none;
}

li {
  margin: 50px;
}

#leftlist {
  position: absolute;
  left: 0%;
  bottom: 40%;
}

#rightlist {
  position: absolute;
  right: 0%;
  bottom: 40%;
}

#bottomlist {
  position: absolute;
  right: 25%;
  bottom: 10%;
}

#bottomlist li {
  display: inline;
}

a {
  text-decoration: none;
  color: inherit;
}
<body>
  <h3 id="header">Design Mode</h3>
  
  <ul id="leftlist">
    <li>View </li>
    <li>Coping Skills</li>
    <li>Notes to Self</li>
  </ul>
  <ul id="rightlist">
    <li>Objects</li>
    <li>Background</li>
    <li>Sound</li>
  </ul>
  <ul id="bottomlist">
    <li><a href="../homepage/index.html">Sign Out</a></li>
    <li width=10px>Sign in Using Different Username</li>
    <li>Save</li>
  </ul>

  <!-- script type="text/javascript" src="scriptdesign.js" defer -->
</body>

How to highlight paragraph specific words from an array of keywords?

I went highlight all words from array in paragraph. I have a paragraph and need to highlight keywords contained in an array.

I am able to loop through the array and highlight the first occurrence of each word in the paragraph. I am unable to highlight subsequent occurrences, however.

<p id="rebaz">
      This domain is established to be used for illustrative examples in documents. You may use this domain in examples.
      without prior coordination or asking for permission. </p>

var highlightword  = ["This", "field","need ", "examples","may",];

How to Get Collection inside document in Firebas

In my React app with version 17, I integrated Firebase v9.6.6.

I have one collection. Inside that collection, I have documents, and within each document, there are additional collections.

Now, I want to obtain a list of those collections in an array.

How can I achieve this? I want a highlighted list, as shown in the image:

enter image description here

Stripe not working in production saying element is still mounted

Payment goes through in development mode successfully but i n production I get this error: v3:1 Uncaught (in promise) IntegrationError: We could not retrieve data from the specified Element. Please make sure the Element you are attempting to use is still mounted.

checkoutform:

import { useState } from "react";
import { CardElement, useElements, useStripe } from "@stripe/react-stripe-js";
import axios from "axios";
import { Link, useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import {
  selectLoadingState,
  startLoading,
  stopLoading,
  startCheckout,
  completeCheckout,
  cancelCheckout,
  cleanCart,
} from "../redux/user/userSlice";
import PropTypes from "prop-types";
import Loader from "react-loader-spinner";
import { useTranslation } from "react-i18next";

import "../styles/CheckoutForm.css";

const CARD_OPTIONS = {
  iconStyle: "solid",
  style: {
    base: {
      iconColor: "#c4f0ff",
      color: "#fff",
      fontWeight: 500,
      fontFamily: "Roboto, Open Sans, Segoe UI, sans-serif",
      fontSize: "16px",
      fontSmoothing: "antialiased",
      ":-webkit-autofill": { color: "#fce883" },
      "::placeholder": { color: "#87bbfd" },
    },
    invalid: {
      iconColor: "#ffc7ee",
      color: "#ffc7ee",
    },
  },
};

export default function CheckoutForm({ location }) {
  const [success, setSuccess] = useState(false);
  const dispatch = useDispatch();
  const loading = useSelector(selectLoadingState);
  const stripe = useStripe();
  const elements = useElements();
  const navigate = useNavigate();
  const { t } = useTranslation();

  const handleSubmit = async (e) => {
    e.preventDefault();
    const { amount, items } = location.state || {};
    dispatch(startLoading());

    console.log("Total Price:", amount);

    const { error, paymentMethod } = await stripe.createPaymentMethod({
      type: "card",
      card: elements.getElement(CardElement),
    });

    if (!error) {
      try {
        dispatch(startCheckout());
        const { id } = paymentMethod;
        const response = await axios.post(
          "https://pizzasi.vercel.app/payment",
          {
            amount: amount,
            items: items,
            id,
          }
        );
        console.log();

        if (response.data.success) {
          console.log("Successful payment");
          dispatch(stopLoading());
          setSuccess(true);
          dispatch(completeCheckout({ items, amount }));
          dispatch(cleanCart());
          navigate("/success");
        }
      } catch (error) {
        console.log("Error", error);
        dispatch(stopLoading());
        dispatch(cancelCheckout());
        navigate("/canceled");
      }
    } else {
      console.log(error.message);
    }
  };

  return (
    <div className="container">
      {!success && !loading ? (
        <form onSubmit={handleSubmit}>
          <fieldset className="form-group">
            <div className="form-row">
              <CardElement options={CARD_OPTIONS} />
            </div>
          </fieldset>
          <button className="payBtn" type="submit">
            {loading ? (
              <Loader type="Oval" color="#FFF" height={20} width={20} />
            ) : (
              "Pay"
            )}
          </button>
          <Link to="/cart">
            <button className="goBacktBtn">{t("goBack")}</button>
          </Link>
        </form>
      ) : (
        <div>
          <h2>{t("paymentSuccess")}</h2>
        </div>
      )}
    </div>
  );
}

CheckoutForm.propTypes = {
  location: PropTypes.shape({
    state: PropTypes.shape({
      amount: PropTypes.number.isRequired,
      items: PropTypes.array.isRequired,
    }).isRequired,
  }).isRequired,
};

stripeContainer:

import { Elements } from "@stripe/react-stripe-js";
import { loadStripe } from "@stripe/stripe-js";
import CheckoutForm from "../pages/CheckoutForm";
import { useSelector } from "react-redux";
import { selectUserCart } from "../redux/user/userSlice";
import { useLocation } from "react-router-dom";

const stripeKey =
  import.meta.env.MODE === "development"
    ? import.meta.env.VITE_STRIPE_KEY_TEST
    : import.meta.env.VITE_STRIPE_KEY_LIVE;

const stripeTestPromise = loadStripe(stripeKey);

export default function StripeContainer() {
  const location = useLocation();
  const cartItems = useSelector(selectUserCart);
  const amount = cartItems.reduce(
    (total, cartItem) => total + cartItem.price * cartItem.quantity,
    0
  );

  console.log("Total Price stripe:", amount);

  return (
    <Elements stripe={stripeTestPromise}>
      <CheckoutForm amount={amount} location={location} items={cartItems} />
    </Elements>
  );
}

app:

import { Suspense } from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Navbar from "./components/Navbar";
import Footer from "./components/Footer";
import AnimatedRoutes from "./components/AnimatedRoutes";
import Menu from "./pages/Menu";
import About from "./pages/About";
import Contact from "./pages/Contact";
import Cart from "./pages/Cart";
import Login from "./pages/Login";
import CashOnDeliveryForm from "./pages/CashOnDeliveryForm";
import StripeContainer from "./components/StripeContainer";
import NotFoundPage from "./pages/NotFoundPage";
import ProtectedRoute from "./utils/ProtectedRoute";
import SuccessPage from "./pages/SuccessPage";
import CanceledPage from "./pages/CanceledPage";

function App() {
  return (
    <Suspense fallback={null}>
      <Router>
        <Navbar />
        <Routes>
          <Route path="/" element={<AnimatedRoutes />} />
          <Route path="/menu" element={<Menu />} />
          <Route path="/about" element={<About />} />
          <Route path="/contact" element={<Contact />} />
          <Route path="/login" element={<Login />} />
          <Route element={<ProtectedRoute />}>
            <Route exact path="/cart" element={<Cart />} />
            <Route path="/stripe-checkout" element={<StripeContainer />} />
            <Route path="/cash-on-delivery" element={<CashOnDeliveryForm />} />
          </Route>
          <Route path="/success" element={<SuccessPage />} />
          <Route path="/canceled" element={<CanceledPage />} />
          <Route path="/*" replace element={<NotFoundPage />} />
        </Routes>
        <Footer />
      </Router>
    </Suspense>
  );
}

export default App;

userSlice:

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

const initialState = {
  user: null,
  cart: [],
  checkoutStatus: null,
  paymentDetails: null,
  loading: false,
};

export const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    startLoading: (state) => {
      state.loading = true;
    },
    stopLoading: (state) => {
      state.loading = false;
    },
    signIn: (state, action) => {
      state.user = action.payload;
    },
    signOut: (state) => {
      state.user = null;
    },
    updateUserCart: (state, action) => {
      state.cart = action.payload.cartItems;
    },
    addItem: (state, action) => {
      state.cart.push(action.payload);
    },
    removeItem: (state, action) => {
      const itemIdToRemove = action.payload;
      state.cart = state.cart.filter((item) => item.itemId !== itemIdToRemove);
    },
    cleanCart: (state) => {
      state.cart = [];
    },
    startCheckout: (state) => {
      state.checkoutStatus = "processing";
    },
    completeCheckout: (state, action) => {
      state.checkoutStatus = "completed";
      state.paymentDetails = action.payload;
    },
    cancelCheckout: (state) => {
      state.checkoutStatus = "canceled";
    },
  },
});

export const {
  startLoading,
  stopLoading,
  signIn,
  signOut: performingSignOut,
  updateUserCart,
  addItem,
  removeItem,
  cleanCart,
  startCheckout,
  completeCheckout,
  cancelCheckout,
} = userSlice.actions;

export const selectLoadingState = (state) => state.user.loading;

export const selectUser = (state) => state.user.user;
export const selectUserCart = (state) => state.user.cart;

export const selectCheckoutStatus = (state) => state.user?.checkoutStatus;
export const selectPaymentDetails = (state) => state.user?.paymentDetails;

export default userSlice.reducer;

server:

const express = require("express");
const bodyParser = require("body-parser");
const app = express();
require("dotenv").config();
const cors = require("cors");
const { body, validationResult } = require("express-validator");
const admin = require("firebase-admin");
const serviceAccount = require("./serviceAccountKey.js");

const stripeSecretKey =
  process.env.NODE_ENV === "development"
    ? process.env.STRIPE_SECRET_KEY_TEST
    : process.env.STRIPE_SECRET_KEY_LIVE;

const stripe = require("stripe")(stripeSecretKey);

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: process.env.DB_URL,
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(cors());

const corsOptions = {
  origin: ["https://pizzasi.vercel.app/"],
  methods: "POST",
};

app.post("/payment", cors(corsOptions), async (req, res) => {
  console.log(req.body);
  let { amount, id, items } = req.body;

  try {
    if (isNaN(amount)) {
      console.error("Invalid amount:", amount);
      throw new Error("Invalid amount");
    }

    const paymentIntent = await stripe.paymentIntents.create({
      amount: amount * 100,
      currency: "EUR",
      description: "PizzaSi company",
      payment_method_types: ["card", "ideal"],
      payment_method: id,
      confirm: true,
      return_url: "https://pizzasi.vercel.app/success",
    });

    console.log("Payment", paymentIntent);
    res.status(200).json({
      message: "Payment successful",
      success: true,
      loading: false,
    });
  } catch (error) {
    console.log("Error", error);
    res.status(500).json({
      message: "Payment failed",
      success: false,
      loading: false,
    });
  }
});

app.post("/create-order", cors(), async (req, res) => {
  const orderDetails = req.body;

  [
    body("formData.name").isString(),
    body("formData.address").isString(),
    body("formData.phone").custom((value) => {
      const normalizePhone = value.replace(/[^0-9]/g, "");
      const phoneRegex = /^(+)?(216)?(d{8})£/;

      if (!phoneRegex.test(normalizePhone)) {
        throw new Error("Please enter a valid phone number");
      }

      return true;
    }),
  ],
    async (req, res) => {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
      }
    };

  try {
    const db = admin.database();
    const ordersRef = db.ref("orders");

    const newOrderRef = ordersRef.push();
    await newOrderRef.set(orderDetails);

    res.status(200).json({
      message: "Order created successfully",
      success: true,
      loading: false,
    });
  } catch (error) {
    console.log("Error", error);
    res.status(500).json({
      message: "Failed to create order",
      success: false,
      loading: false,
    });
  }
});

app.listen(3001, () => {
  console.log("Server is running on port 3001");
});

Open alert on Select Event of kendoContextMenu

as the title says i’m trying to open an alert on the Select Event of a kendoContextMenu, but the alert is shown only after the Select function is completed, is it possible to show an alert as soon as the user clicks on the ContextMenu option (at the start of the Select Event)?

Below the Select Event of my code:

select: function (e)
{
alert(“Test Alert”); //This one appears only after that the Select function ends.

//MY CODE
}

Thanks in advance.

Script to parse from csv to objects in javascript

I’m pretty new to javascript,
I extracted a bunch of lines from a csv file and saved it in a variable, now I would like to create an object for each line.
I have already created the object and all the needed fields

The fields of each line are separated by a comma, and the lines are separated by a simple space.
In the data neither additional commas/spaces are allowed.
Could anyone help me?

I got lost among regular expressions and such since this is all new to me, so I’m hoping this is a starting point

Thanks

Ge the current url or hostname in next ouside components

I’m using firebase. I have a file config. In this file I have something like this:
export const currentUrl = isEmulators ? "http://localhost:3000" : window.location.hostname

But I’m getting undefined for window. I’ve been looking through other questions and they all recommend hooks. But my implementation is in a config file that is not inside any component.

Is there any way to retrieve current hostname outside of components using next js? Something like window.location.hostname

export const currentUrl = isEmulators ? "http://localhost:3000" : window.location.hostname

Get Form schema on clicking a button outside of the form and post that form through ajax using FORM IO

I am using formio (https://formio.github.io/formio.js/app/sandbox.html) for one of my project and I have a requirement around saving the form schema on clicking a button outside the form.

I have created a fiddle here – https://jsfiddle.net/wrLf5q3v/2/

I want the form JSON schema when I click on Get JSON Schema button on top.

The form schema looks something like this –

{
  "display": "form",
  "components": [
    {
      "label": "Text Field",
      "applyMaskOn": "change",
      "tableView": true,
      "key": "textField",
      "type": "textfield",
      "input": true
    },
    {
      "label": "Text Area",
      "applyMaskOn": "change",
      "autoExpand": false,
      "tableView": true,
      "key": "textArea",
      "type": "textarea",
      "input": true
    },
    {
      "type": "button",
      "label": "Submit",
      "key": "submit",
      "disableOnInvalid": true,
      "input": true,
      "tableView": false
    }
  ]
}

Query params are not getting cleared when navigating from one path to another- Reactjs

I have a component called EnrolledStudentsLayout where when the component mounts when the user click on the path ‘/enrolled-students’ it automatically updates the query params with some initial value like below which makes the url look like /enrolled-students?tuition_type=GEN


const EnrolledStudentsLayout = () => {
  const userProfile = useSelector(getUserProfile);

  const [searchParams, setSearchParams] = useSearchParams();

  const tuitionTypeParam = searchParams.get("tuition_type");

  const searchQueryParam = searchParams.get("search_query");

  const [progress, setProgress] = useState(0);

  const [tuitionTypeValue, setTuitionTypeValue] = useState("");

  const [isTuitionTypeSelectOpen, setIsTuitionTypeOpen] = useState(false);

  const [enrolledStudents, setEnrolledStudents] = useState([]);

  const [tuitionTyepOptions, setTuitionTypeOptions] = useState([]);

  const [toggleSearchbar, setToggleSearchbar] = useState(false);

  const fetchStudents = useQuery(
    ["teacher/fetchStudents", tuitionTypeParam, searchQueryParam],
    () => getEnrolledStudents(tuitionTypeParam, searchQueryParam),
    {
      refetchOnWindowFocus: false,
      enabled: tuitionTypeParam !== null,
      onSuccess: (response) => {
        setEnrolledStudents(response.data);
      },
      onError: (error) => {
        console.log(error);
      },
      onSettled: () => {
        setProgress(100);
      },
    }
  );

  if (tuitionTypeParam === null) {
    setSearchParams(
      { tuition_type: "GEN"},
      { replace: true }
    );
  }

  const handleTuitionTypeToggle = () => {
    setIsTuitionTypeOpen((curr) => !curr);
  };

  const handleTuitionTypeSelect = (value, label) => {
    setSearchParams({ tuition_type: value });
    setTuitionTypeValue(label);
    setIsTuitionTypeOpen(false);
  };



  const handleToggleSearchbar = () => {
    setToggleSearchbar((curr) => !curr);
  };

  useEffect(() => {
    /*
     CONTROLS THE PROGRESS BAR
    */
    if (fetchStudents.isLoading) {
      setProgress(80);
    }
  }, [fetchStudents.isLoading]);

  useEffect(() => {
    console.log("EnrolledStudentsLayout mounted");
    return () => {
      console.log("EnrolledStudentsLayout unmounted");
    };
  }, []);

  return (
    <>
      <LoadingBar
        color="red"
        progress={progress}
        onLoaderFinished={() => setProgress(0)}
        height={4}
      />
      <Helmet>
        <title>Enrolled Students</title>
      </Helmet>
      <Wrapper>
        <Header>
          <SearchToggleButton onClick={handleToggleSearchbar}>
            <i className="fas fa-search"></i>
          </SearchToggleButton>
          <SearchBar
            toggleSearchbar={toggleSearchbar}
            handleToggle={handleToggleSearchbar}
          />
          <CustomSelectButton
            options={tuitionTyepOptions}
            isOpen={isTuitionTypeSelectOpen}
            onToggle={handleTuitionTypeToggle}
            value={tuitionTypeValue}
            handleSelect={handleTuitionTypeSelect}
          />
        </Header>
        <CardContainer>
          {enrolledStudents.length > 0 ? (
            enrolledStudents.map((student) => (
              <Cards key={student.id} student={student} />
            ))
          ) : (
            <p>No enrolled students</p>
          )}
        </CardContainer>
      </Wrapper>
    </>
  );
};

export default EnrolledStudentsLayout;

but when I navigate to a completely different path, say ‘/activate-enrollment’ which mounts a completely new component, the query params still persist in the url which make the url in this case look like /activate-enrollment?tuition_type=GEN. Only double clicking on the same link in the navigation bar removes the query params. I have no idea why this is happening. I even tried to check the component mount and unmount by using the useEffect in the enrolled students component and it is outputing the correct logs.

Please give me a solution to this problem

I need help adding legend functionality to my graph using D3

The goal of this assignment is create an interactive visualization. I am making a bar graph that includes a legend to toggle certain bars.

The y-axis of my graph shows the number of electric car sales in Europe, the x-axis shows the country. The colors of the graph represent the range of the population for that country. I want to create a legend that, when a specific color is clicked, toggles the bars with that corresponding color.

This my first time ever using D3 so my code may or may not be up to par. Any help is appreciated!

var salesData;
var runningData;
var runningColors;

var customLegendData = [{
    label: "Population: >10 Million",
    color: "#008B8B"
  },
  {
    label: "Population: 10 Million - 50 Million",
    color: "#2F4F4F"
  },
  {
    label: "Population: 50 Million - 100 Million",
    color: "#48308B"
  }
];

$(document).ready(function() {
  Plot();
  addCustomLegend(customLegendData);
  attachLegendToggle();
});

function Plot() {
  TransformChartData(chartData, chartOptions);
  BuildBar("chart", chartData, chartOptions);
}

function BuildBar(id, chartData, options, level) {
  var chart = d3.select("#" + id);

  var margin = {
      top: 10,
      right: 10,
      bottom: 70,
      left: 70
    },
    barWidth = 70,
    barPadding = 5;
  var width = (barWidth + barPadding) * runningData.length; // Adjusted the width
  var height = $(chart[0]).outerHeight() - margin.top - margin.bottom;

  var xVarName;
  var yVarName = options[0].yaxis;

  xVarName = options[0].xaxis;

  var xAry = runningData.map(function(el) {
    return el[xVarName];
  });

  var yAry = runningData.map(function(el) {
    return el[yVarName];
  });

  var capAry = runningData.map(function(el) {
    return el.caption;
  });

  var x = d3.scale.ordinal().domain(xAry).rangeRoundBands([0, width], 0.1);

  var yMax = d3.max(runningData, function(d) {
    return +d[yVarName];
  });
  var y = d3.scale.linear().domain([0, yMax]).range([height, 0]);

  var rcolor = d3.scale.ordinal().range(runningColors);

  chart = chart
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  var bars = chart.selectAll("g")
    .data(runningData)
    .enter()
    .append("g")
    .attr("class", function(d) {
      return "bar " + d[xVarName]; // Add a class based on the country
    })
    .attr("data-country", function(d) {
      return d[xVarName]; // Add data attribute with the country name
    })
    .attr("transform", function(d) {
      return "translate(" + (x(d[xVarName]) + barPadding / 2) + ", 0)";
    });

  var ctrtxt = 0;

  var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .ticks(xAry.length)
    .tickFormat(function(d) {
      var mapper = options[0].captions[0];
      return mapper[d];
    });

  var yAxisTicks = [0, 10000, 50000, 100000, 200000, 300000, 400000]
  var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .tickValues(yAxisTicks);

  bars.append("rect")
    .attr("class", function(d) {
      return "bar-" + d[xVarName]; // Add a class based on the country
    })
    .attr("y", function(d) {
      return y(parseInt(d[yVarName]));
    })
    .attr("height", function(d) {
      return height - y(parseInt(d[yVarName]));
    })
    .attr("width", x.rangeBand() - barPadding)
    .style("fill", function(d) {
      return rcolor(d[xVarName]);
    });

  bars.append("text")
    .attr("x", x.rangeBand() / 2)
    .attr("y", function(d) {
      return y(parseInt(d[yVarName])) - 5;
    })
    .attr("dy", ".35em")
    .text(function(d) {
      return d[yVarName];
    })
    .attr("class", "bar-text");

  chart.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis)
    .selectAll(".tick text")
    .style("text-anchor", "end")
    .attr("dx", "-.8em")
    .attr("dy", ".15em")
    .attr("transform", "rotate(-45)");

  chart.append("g")
    .attr("class", "y axis")
    .call(yAxis)
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", -40)
    .attr("dy", ".71em")
    .style("text-anchor", "end");

  return chart;
}

function attachLegendToggle() {
  d3.selectAll("#legend .legend-item").on("click", function(event, d) {
    var country = d.label;
    var barsToToggle = d3.selectAll("#chart [data-country='" + country + "']");

    barsToToggle.classed("hidden", function() {
      var isHidden = d3.select(this).classed("hidden");
      return !isHidden;
    });
  });
}

function TransformChartData(chartData, opts, level, filter) {
  var result = [];
  var resultColors = [];
  var counter = 0;
  var hasMatch;
  var xVarName;
  var yVarName = opts[0].yaxis;

  xVarName = opts[0].xaxis;

  for (var i in chartData) {
    hasMatch = false;
    for (var index = 0; index < result.length; ++index) {
      var data = result[index];

      if (data[xVarName] == chartData[i][xVarName]) {
        result[index][yVarName] = result[index][yVarName] + chartData[i][yVarName];
        hasMatch = true;
        break;
      }
    }
    if (hasMatch == false) {
      ditem = {};
      ditem[xVarName] = chartData[i][xVarName];
      ditem[yVarName] = chartData[i][yVarName];
      ditem["caption"] = opts[0].captions != undefined ? opts[0].captions[0]
        [chartData[i][xVarName]] : "";
      ditem["title"] = opts[0].captions != undefined ? opts[0].captions[0]
        [chartData[i][xVarName]] : "";
      ditem["op"] = 1;
      result.push(ditem);

      resultColors[counter] = opts[0].color != undefined ? opts[0].color[0]
        [chartData[i][xVarName]] : "";

      counter += 1;
    }
  }
  runningData = result;
  runningColors = resultColors;
  return;
}


var chartData = [{
    "Country": "UK",
    "Sales": "370000"
  },
  {
    "Country": "France",
    "Sales": "340000"
  },
  {
    "Country": "Norway",
    "Sales": "166000"
  },
  {
    "Country": "Sweden",
    "Sales": "163000"
  },
  {
    "Country": "Italy",
    "Sales": "114000"
  },
  {
    "Country": "Netherlands",
    "Sales": "107000"
  },
  {
    "Country": "Belgium",
    "Sales": "97000"
  },
  {
    "Country": "Spain",
    "Sales": "82000"
  },
  {
    "Country": "Switzerland",
    "Sales": "59000"
  },
  {
    "Country": "Denmark",
    "Sales": "57000"
  },
  {
    "Country": "Austria",
    "Sales": "38900"
  },
  {
    "Country": "Portugal",
    "Sales": "34000"
  },
  {
    "Country": "Finland",
    "Sales": "31000"
  },
  {
    "Country": "Poland",
    "Sales": "25000"
  },
  {
    "Country": "Iceland",
    "Sales": "11900"
  },
  {
    "Country": "Greece",
    "Sales": "8300"
  },
  {
    "Country": "Turkey",
    "Sales": "7540"
  },
];

chartOptions = [{
  "captions": [{
    "Germany": "Germany",
    "UK": "UK",
    "France": "France",
    "Norway": "Norway",
    "Sweden": "Sweden",
    "Italy": "Italy",
    "Netherlands": "Netherlands",
    "Belgium": "Belgium",
    "Spain": "Spain",
    "Switzerland": "Switzerland",
    "Denmark": "Denmark",
    "Austria": "Austria",
    "Portugal": "Portugal",
    "Finland": "Finland",
    "Poland": "Poland",
    "Iceland": "Iceland",
    "Greece": "Greece",
    "Turkey": "Turkey",
  }],

  "color": [{
    "Germany": "#483D8B",
    "UK": "#483D8B",
    "France": "#483D8B",
    "Norway": "#008B8B",
    "Sweden": "#2F4F4F",
    "Italy": "#483D8B",
    "Netherlands": "#2F4F4F",
    "Belgium": "#2F4F4F",
    "Spain": "#2F4F4F",
    "Switzerland": "#008B8B",
    "Denmark": "#008B8B",
    "Austria": "#008B8B",
    "Portugal": "#2F4F4F",
    "Finland": "#483D8B",
    "Poland": "#2F4F4F",
    "Iceland": "#008B8B",
    "Greece": "#2F4F4F",
    "Turkey": "#483D8B",
  }],
  "xaxis": "Country",
  "yaxis": "Sales"
}];

function addCustomLegend(legendData) {
  var legend = d3.select("#legend")
    .selectAll(".legend-item") // Add class selector
    .data(legendData)
    .enter()
    .append("g")
    .attr("class", "legend-item") // Add class
    .attr("transform", function(d, i) {
      return "translate(0," + i * 20 + ")";
    });

  legend.append("rect")
    .attr("width", 18)
    .attr("height", 18)
    .style("fill", function(d) {
      return d.color;
    });

  legend.append("text")
    .attr("x", 24)
    .attr("y", 9)
    .attr("dy", ".35em")
    .style("text-anchor", "start")
    .text(function(d) {
      return d.label;
    });
}
#chart text {
  fill: black;
  font: 10px sans-serif;
  text-anchor: end;
}

.axis text {
  font: bold 10px sans-serif;
}

.axis text.x-axis-label {
  font: bold 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  shape-rendering: crispEdges;
}

html,
body {
  height: 100%;
  margin: 0;
}

body {
  color: #eaeaea;
  padding: 0px;
  background: linear-gradient(to bottom, #3498db, #ffffff);
  background-attachment: fixed;
}

path {
  stroke: steelblue;
  stroke-width: 2;
  fill: none;
}

#chart-title {
  text-align: center;
  margin-top: 20px;
}

#chart-title h2 {
  font-size: 50px;
  color: #333;
}

#chart {
  width: 100%;
}

#legend {
  position: absolute;
  padding-top: 1%;
  padding-right: 1%;
  padding-left: 1%;
  top: 100px;
  right: 20px;
  background-color: #FFFFFF;
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js" charset="utf-8"></script>
<script src="https://d3js.org/d3.v3.min.js"></script>
<div id="chart-title">
  <h2>2022 Electric Vehicle Sales in Europe</h2>
</div>
<div id="chart" style="height:100%; width:100%;"></div>
<svg id="legend" width="200" height="200"></svg>

simplify the link between array of parent child javascript [closed]

//A function to return true if the relation between 2 nodes exist else false

const obj = [
    { id: 1, child: [3, 2] },
    { id: 2, child: [4] },
    { id: 3, child: [5] },
    { id: 7, child: [8] }
]

// output :
// if input is 1,3 => return true because there is relation
// if input is 1,7 => return false because there is no relation

I have tried using loops but couldn’t solve it

input (1,2)
output true

input (1,7)
output false

Moment js calender problem, cant split days to td

 <script>
        moment.locale('tr');

        document.addEventListener('DOMContentLoaded', function () {
            // Gün adlarını ekle
            var daysOfWeekRow = document.getElementById('days-of-week');
            var daysOfWeek = moment.weekdaysShort(true);

            daysOfWeek.forEach(function(day) {
                daysOfWeekRow.innerHTML += '<th>' + day + '</th>';
            });

            // Saati güncelleme fonksiyonu
            function updateClock() {
                var formattedDateTime = moment().format('LLLL');
                var formattedTime = moment().format('LTS');
                var displayText = formattedDateTime + "<br>" + formattedTime;
                document.getElementById('datetime').innerHTML = displayText;
            }

            // Ayın günlerini takvime ekleme
            function generateCalendar() {
                var calendarBody = document.getElementById('calendar-body');
                var currentDate = moment().startOf('month');
                var endDate = moment().endOf('month');

                while (currentDate.isSameOrBefore(endDate)) {
                    calendarBody.innerHTML += '<td>' + currentDate.format('DD') + '</td>';
                    currentDate.add(1, 'days');
                }
                
            }

            // Saati belirli aralıklarla güncelle
            updateClock();
            setInterval(updateClock, 1000); // Her saniye güncelle

            // Takvimi oluştur
            generateCalendar();
        });
    </script>

I am trying to make a calendar. I’m taking a month days but it only shows these days inside of one td. I want to see these days in each of these 7 td tags

I am trying to make a calendar. I’m taking a month days but it only shows these days inside of one td. I want to see these days in each of these 7 td tags