Type assertion in JSDoc VScode

/**
 * @typedef Animal
 * @property {string} noise
*/

/**
 * @typedef Duck
 * @property {string} noise
 * @property {number} wings
*/

/**
 * @param {Animal} a
 */
function TestAnimal(a) { console.log(a.noise) }

// 0. warning
TestAnimal({ noise: 'quack', wings: 2 })  // Object literal may only specify known properties, and 'wings' does not exist in type 'Animal'.ts(2353)

// 1. multiple
const bear = { noise: 'roar', feet: 4 }
TestAnimal(bear)

// 2. single, extra parentheses
TestAnimal(/** @type {Animal} */({ noise: 'meow', tails: 1 }))

Are these the only 2 ways to type assert without warning in VSCode? I find both unwieldy and something closer to (0) would be much preferred.

Another solution I’ve come across is

/**
 * @typedef {{
 *   noise: string
 *   [others: string]: any
 * }} Animal
*/

but it’s less than ideal since I have to apply it to all typedef I might extend from and defeats its purpose in some cases

I dont want to use

/** @typedef {Duck | Bear | Cat} Animal */

either, since this requires Animal to keep track of everything that extends it and doesn’t allow other users to extend it

rehype-mdx-code-props is not working correctly with nextjs app router

I’m using nextjs 14, using app router.
I was trying to use the mdx in nextjs, for creating documentation in which I require to add code blocks for reference.
now I found that rehype-mdx-code-props can help on passing the props to my component.

```js filename="demo.js" filetype="js"
function sayHello(name) {
  console.log('Hello', name);
}
```

And in the mdx-components.tsx which is inside the src folder I’ve written this:

export function useMDXComponents(components: MDXComponents): MDXComponents {
  return {
    h1: ({ children }) => (
      <h1 className="text-3xl font-bold tracking-tight">{children}</h1>
    ),
    img: (props) => (
      <Image
        sizes="100vw"
        style={{ width: "100%", height: "auto" }}
        {...(props as ImageProps)}
      />
    ),
    code: ({children}) => {
        return <MyCodeBlock children={children} />;
    },
    p: ({ children }) => (
      <p className="text-sm text-muted-foreground">{children}</p>
    ),
    ...components,
  };
}

problem is the line code: ({children}) part, here I tried to do the console log for the props being passed but only children and classname is being passed as props, so this is causing filename and filetype arguments not getting passed to component.

How do I get filename and filetype as arguments to my method?

for ref next.config.mjs:

import createMDX from '@next/mdx'
import remarkGfm from 'remark-gfm'
import rehypeMdxCodeProps from 'rehype-mdx-code-props'

/** @type {import('next').NextConfig} */
const nextConfig = {
  // Configure `pageExtensions` to include markdown and MDX files
  pageExtensions: ['js', 'jsx', 'md', 'mdx', 'ts', 'tsx'],
  // Optionally, add any other Next.js config below
}
 
const withMDX = createMDX({
  // Add markdown plugins here, as desired
  options: {
    remarkPlugins: [remarkGfm],
    rehypePlugins: [rehypeMdxCodeProps],
    },
})
 
// Merge MDX config with Next.js config
export default withMDX(nextConfig)

multiple action on the same order using the different tab in ReactJS how to restrict it

We are building a restaurant app currently we facing an issue with the testing team.

They can make a different action in the same order using multiple tabs.

This leads to incorrect information stored in the DB

How to fix it.

We suggest the backend team implement this type of logic but the backend team is saying this needs to be done from the front end. Is there any way we can do it from front-end

JavaScript diff-match-patch shows diff between numbers incorrectly

I am using the diff-match-patch library in JavaScript to determine and visualize the differences between two configuration files for some components. It usually works well, however I’ve realized that for example in one line of a file there is the number “1657” and in the corresponding line in the other file there is the number “2160”. In this case, I want it to strikethrough the whole number “1657” and show “2160” as a completely new addition, however it instead only strikes through the “57” and shows the “2” and “0” in “2160” as new additions. This is how it looks in the diff-match-patch demo:

diff-match-patch demo

I understand this behavior is due to how the algorithm of diff-match-patch works, it only sees “2” and “0” as new additions because they didn’t exist in the previous string – but I am not sure how to fix it. I initially believed diff-match-patch doesn’t do a character-by-character comparison, but the demo page states that it actually does.

This is the current state of the function where I use diff-match-patch:

         function generateDiff(text1, text2) {
            let dmp = new diff_match_patch();
            let diff = dmp.diff_main(text1, text2);
            dmp.diff_cleanupSemantic(diff);

            let display1 = '';
            let display2 = '';

            for (let i = 0; i < diff.length; i++) {
                let part = diff[i];
                let op = part[0];    // Operation (insert, delete, equal)
                let data = part[1];  // Text of the change

                let span1 = document.createElement('span');
                let span2 = document.createElement('span');

                if (op === 0) {  // Equal
                     span1.className = 'diff-equal';
                     span2.className = 'diff-equal';

                     span1.textContent = data;
                     span2.textContent = data;

                     display1 += span1.outerHTML;
                     display2 += span2.outerHTML;
                } else if (op === -1) {  // Delete
                    span1.className = 'diff-delete';
                    span1.textContent = data;
                    display1 += span1.outerHTML;
                } else {  // Insert
                    span2.className = 'diff-insert';
                    span2.textContent = data;
                    display2 += span2.outerHTML;
                }
            }

            return [display1, display2];
        }

I have tried to handle only numbers differently by using some regex and identifying them in the text, but it didn’t work. I would appreciate any help on this, thank you!

Check if email address is personal or business related [closed]

I would like to verify if email address is of some university or corporate or just personal use.

just like how teamblind.com does things. how they verify if the email address is associated with company or not?

I’ve read several stackoverflow question’s answers but it doesn’t seem to fit in with my requirements. also many post on the internet verify email by matching email with [email protected] pattern but there can company with different pattern and university does have different pattern than this too.

Small box with dropdown options after selecting file to upload

I’ve implemented an input element and after the file is selected for upload, I want to show a box with a dropdown like this. I’ve seen them on different sites but can’t seem to find a npm pacakge that does this.

Is this something which requires a custom component using the event.target.files object or does one already exist?

enter image description here

Nextjs – Clerk web hook to sync supabase

The normal work flow :
When user hits a route that protected by Clerk, it triggers the app/api/clerk/webhook.
Inside the web hook I check specifically 2 event types. user create and delete.
If it is user-created event, I get the userid & email from Clerk, create a user with data from clerk in supabase database.
Everything works, I can see the user in Clerk and supabase created.
my NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/chat. So, after webhook runs, Clerk redirect to /chat.
which is my server component app/chat/page.js

In this server component, I fetch user data from database and render a client-side component with some data.
This works most of the time. So, everything works in webhooks, user is created at clerk and supabase, I hit the /chat, get user data from database and render. However, sometimes I get the error rendered, because chat component runs before webhook completes. Everything still works behind the scenes I just don’t have updated data. If I re-load the page, I get all the data rendered on the page. So I get the user data from database before its created actually. Any know why is this happening and how to solve it the best way?

Thanks

If I change NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/chat to for example NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/another and move chat , yes , it solves my problem but I want to redirect to exactly that page and want to understand this does not work. First time working with webhooks.

invalid_request: The provided value for the input parameter ‘redirect_uri’ is not valid

I am developing an app to read the calendar and render it with fullcalendar, the error comes when logging in and the redirect uri gives an error

I am working on localhost and this is my url that I am working on:

http://localhost/newdocu/calendarOutlook

and I have that url as a redirect in the azure portal and the following error screen appears after entering the email and clicking continue.
azure

error

I have also tried with the url ending in .php (In the test I did before adding the functionality to the entire application the redirect ended in ‘.html’ since that was the file extension), entering the folder path to the file, redirecting to another file and the error still appears

This is the code where i put the redirect Uri:

const msalConfig = {
    auth: {
        clientId: "...",
        authority: "...",                    
        redirectUri: "http://localhost/newdocu/calendarOutlook",
        popUp: true
    }
};

Thank you very much!!

Why is my code not running in my for await function

So I am calling this function from a useEffect hook in React Native, the issue is within the function as the function contains a for await loop. The console.log outside the function works but all of the code inside the for await doesn’t run. how do I fix this?

Here is the function:

const addBook = async () => {
    console.log('IT IS HAPPENING!!!! 2');
    for await (const book of selectedBooks) {
      console.log('IT IS HAPPENING!!!! 3');
      setIdSearchValue(book.id);
      console.log('ID SREARCH VALUE', book.id);
      console.log(' ~ screenTransfer ~ selectedBooks[i].id:', book.id);
      await getBooksQuery.refetch(); // Wait for data to be fetched
      console.log('ENABLE BOOKS QUERY VALUE', enableBooksQuery);
      console.log('GETBOOOKSQUERYDATA', getBooksQuery.data);
      console.log('GETBOOOKSQUERYERROR', getBooksQuery.isError, getBooksQuery.error);
    }
  };

I tried switching the for await to a regular for loop with the same await but it still doesn’t work. I am Expecting to see all of the console.logs in the for await to be ran.

Unable to parse JSON due to format of numerical value [closed]

I am trying to convert JSON to an object via JSON.parse(`{${jsonStr.replace()}}`), is my case value of the {${jsonStr.replace()}} is

{ "MIA": 246, "liberty": 215, "TerminalOrderId": 002539224748 }

Is there any possible way to convert this string from

{ "MIA": 246, "liberty": 215, "TerminalOrderId": 002539224748 }

To

{ "MIA": "246", "liberty": "215", "TerminalOrderId": "002539224748" }

This would allow me to convert JSON to an object without any errors

when conditionally rendering an input component getting this error – A component is changing a controlled input to be uncontrolled

When I am editing the campaign and switching the Welcome Message Type from Text to Audio it throws this error – Warning: A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.

Audio component is a file component –

index.js

import {
  Button,
  Card,
  CardBody,
  CardHeader,
  Col,
  Container,
  Row,
} from "reactstrap";
import BreadCrumb from "../../Components/Common/BreadCrumb";
import { Link } from "react-router-dom";
import AddCampaignModal from "./AddCampaignModal";
import { useFormik } from "formik";
import * as Yup from "yup";
import CampaignRemoveModal from "./CampaignRemoveModal";
import {
  getCampaigns,
  createCampaign,
  updateCampaign,
  removeCampaign,
} from "../../slices/Campaigns/thunk";

import { useDispatch } from "react-redux";
import { useSelector } from "react-redux";
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { getGateway } from "../../slices/Gateway/thunk";
import Loader from "../../Components/Common/Loader";

const Campaigns = () => {
  const [modal_list, setmodal_list] = useState(false);

  const [modal_delete, setmodal_delete] = useState(false);

  const [loading, setLoading] = useState(false);

  const [isEditingCampaign, setIsEditingCampaign] = useState(false);

  const [listCampaignId, setListCampaignId] = useState(null);

  const [welcomeMessageAudio, setWelcomeMessageAudio] = useState("");

  const [invalidMessageAudio, setInvalidMessageAudio] = useState(null);

  const [timeOutMessageAudio, setTimeOutMessageAudio] = useState(null);

  const [selectSingleWelcomeTextOrAudio, setSelectSingleWelcomeTextOrAudio] =
    useState(null);

  const [selectSingleInvalidTextOrAudio, setSelectSingleInvalidTextOrAudio] =
    useState(null);

  const [selectSingleTimeOutTextOrAudio, setSelectSingleTimeOutTextOrAudio] =
    useState(null);

  const [selectedSingleGateway, setSelectedSingleGateway] = useState(null);

  const dispatch = useDispatch();

  const { campaigns, alreadyRegisteredError } = useSelector(
    (state) => state.Campaigns
  );
  const { gateways } = useSelector((state) => state.Gateways);

  function tog_list() {
    setmodal_list(!modal_list);
  }

  function tog_delete() {
    setmodal_delete(!modal_delete);
  }

  useEffect(() => {
    if (alreadyRegisteredError) {
      setmodal_list(!modal_list);
    }
  }, [alreadyRegisteredError]);

  useEffect(() => {
    setLoading(true);
    dispatch(getCampaigns()).finally(() => {
      setLoading(false);
    });
    dispatch(getGateway());
  }, [dispatch]);

  const welcomeMessageTextOrAudioOptions = [
    { label: "Text", value: "Text" },
    { label: "Audio", value: "Audio" },
  ];

  function handleSelectSingleWelcomeMessageTextOrAudio(welcomeMessageType) {
    setSelectSingleWelcomeTextOrAudio(welcomeMessageType);
    // if (welcomeMessageType?.value === "Audio") {
    //   validation.setFieldValue("welcomeMessageText", "");
    // }
  }
  const invalidMessageTextOrAudioOptions = [
    { label: "Text", value: "Text" },
    { label: "Audio", value: "Audio" },
  ];

  function handleSelectSingleInvalidMessageTextOrAudio(invalidMessageType) {
    setSelectSingleInvalidTextOrAudio(invalidMessageType);
  }
  const timeOutMessageTextOrAudioOptions = [
    { label: "Text", value: "Text" },
    { label: "Audio", value: "Audio" },
  ];

  function handleSelectSingleTimeOutMessageTextOrAudio(timeOutMessageType) {
    setSelectSingleTimeOutTextOrAudio(timeOutMessageType);
  }

  const gatewayOptions = gateways?.map((gateway) => {
    return {
      id: gateway.id,
      value: gateway.gatewayIpAddress,
      label: gateway.gatewayIpAddress,
    };
  });

  function handleSelectSingleGateway(gateway) {
    setSelectedSingleGateway(gateway);
  }

  const validation = useFormik({
    initialValues: {
      campaignName: "",
      gatewayId: "",
      welcomeMessageText: "",
      InvalidMessageText: "",
      timeOutMessageText: "",
    },
    validationSchema: Yup.object({
      campaignName: Yup.string().required("Please enter campaign name"),
      gatewayId: Yup.string().required("Gateway is required"),
      welcomeMessageText: Yup.string(),
      invalidMessageText: Yup.string(),
      timeOutMessageText: Yup.string(),
    }),
    onSubmit: (values, { resetForm }) => {
      if (isEditingCampaign) {
        dispatch(
          updateCampaign({
            ...values,
            campaignId: listCampaignId,
            welcomeMessageAudio,
            invalidMessageAudio,
            timeOutMessageAudio,
            gatewayId: selectedSingleGateway.id,
          })
        );
      } else {
        dispatch(
          createCampaign({
            ...values,
            welcomeMessageAudio,
            invalidMessageAudio,
            timeOutMessageAudio,
            gatewayId: selectedSingleGateway.id,
          })
        );
      }

      // if (!isEditingCampaign) {
      //   resetForm();
      // }

      resetForm();

      setSelectedSingleGateway(null);
      setSelectSingleInvalidTextOrAudio(null);
      setSelectSingleTimeOutTextOrAudio(null);
      setSelectSingleWelcomeTextOrAudio(null);

      setmodal_list(false);
    },
  });

  console.log("VALIDATION VALUES ->", validation.values);

  function formHandleSubmit(e) {
    e.preventDefault();
    validation.handleSubmit();

    if (!validation.errors) {
      setmodal_list(false);
    }
    return false;
  }

  function handleEditCampaign(campaignData) {
    setIsEditingCampaign(true);
    setmodal_list(!modal_list);
    setListCampaignId(campaignData.id);

    const selectedGateway = gatewayOptions?.find(
      (gateway) => (gateway.id = campaignData.gatewayId)
    );

    if (campaignData.welcomeMessageText) {
      const selectedOption = welcomeMessageTextOrAudioOptions.find(
        (option) => option.value === "Text"
      );

      setSelectSingleWelcomeTextOrAudio(selectedOption);
    } else {
      validation.setFieldValue("welcomeMessageText", ""); // Ensure welcomeMessageText is cleared
    }

    if (campaignData.invalidMessageText) {
      const selectedOption = invalidMessageTextOrAudioOptions.find(
        (option) => option.value === "Text"
      );

      setSelectSingleInvalidTextOrAudio(selectedOption);
    }
    if (campaignData.timeOutMessageText) {
      const selectedOption = timeOutMessageTextOrAudioOptions.find(
        (option) => option.value === "Text"
      );

      setSelectSingleTimeOutTextOrAudio(selectedOption);
    }

    setSelectedSingleGateway(selectedGateway);

    validation.setValues({
      campaignName: campaignData.campaignName,
      welcomeMessageText: campaignData.welcomeMessageText,
      invalidMessageText: campaignData.invalidMessageText,
      timeOutMessageText: campaignData.timeOutMessageText,
      gatewayId: campaignData.gatewayId,
    });
  }

  function tog_list() {
    validation.resetForm();
    setSelectedSingleGateway(null);
    setSelectSingleInvalidTextOrAudio(null);
    setSelectSingleTimeOutTextOrAudio(null);
    setSelectSingleWelcomeTextOrAudio(null);

    setmodal_list(!modal_list);
  }

  document.title = "Campaigns";
  return (
    <React.Fragment>
      <div className="page-content">
        <Container fluid>
          <BreadCrumb title="Campaigns" pageTitle="Management" />
          <Row>
            <Col lg={12}>
              <Card>
                <CardHeader>
                  <h4 className="card-title mb-0">Create a Campaign</h4>
                </CardHeader>

                <CardBody>
                  <div className="listjs-table" id="userList">
                    <Row className="g-4 mb-3">
                      <Col className="col-sm-auto w-100 d-flex justify-content-between">
                        <Button
                          color="primary"
                          className="add-btn me-1"
                          onClick={tog_list}
                          id="create-btn"
                        >
                          <i className="ri-add-line align-bottom me-1"></i> Add
                          Campaign
                        </Button>
                      </Col>
                    </Row>

                    <div className="table-responsive table-card mt-3 mb-1">
                      <table
                        className="table align-middle table-nowrap"
                        id="userTable"
                      >
                        <thead className="table-light">
                          <tr>
                            <th>S.No</th>
                            <th>Campaign Name</th>
                            <th>Welcome Text</th>
                            <th>Invalid Text</th>
                            <th>TimeOut Text</th>

                            <th>Action</th>
                          </tr>
                        </thead>
                        <tbody className="list form-check-all">
                          {loading ? (
                            <tr>
                              <td
                                colSpan={7}
                                style={{
                                  border: "none",
                                  textAlign: "center",
                                  verticalAlign: "middle",
                                }}
                              >
                                <Loader />
                              </td>
                            </tr>
                          ) : (
                            <>
                              {campaigns?.map((campaign, idx) => (
                                <tr key={campaign.id}>
                                  <td>{idx + 1}</td>
                                  <td>{campaign.campaignName}</td>
                                  <td>{campaign.welcomeMessageText}</td>
                                  <td>{campaign.invalidMessageText}</td>
                                  <td>{campaign.timeOutMessageText}</td>

                                  <td>
                                    <div className="d-flex gap-2">
                                      <div className="edit">
                                        <button
                                          className="btn btn-sm btn-primary edit-item-btn"
                                          data-bs-toggle="modal"
                                          data-bs-target="#showModal"
                                          onClick={() => {
                                            handleEditCampaign(campaign);
                                          }}
                                        >
                                          Edit
                                        </button>
                                      </div>

                                      <div className="remove">
                                        <button
                                          className="btn btn-sm btn-danger edit-item-btn"
                                          data-bs-toggle="modal"
                                          data-bs-target="#showModal"
                                          onClick={() => {
                                            setListCampaignId(campaign.id);
                                            tog_delete();
                                          }}
                                        >
                                          Remove
                                        </button>
                                      </div>
                                    </div>
                                  </td>
                                </tr>
                              ))}
                            </>
                          )}
                        </tbody>
                      </table>
                    </div>

                    <div className="d-flex justify-content-end">
                      <div className="pagination-wrap hstack gap-2">
                        <Link
                          className="page-item pagination-prev disabled"
                          to="#"
                        >
                          Previous
                        </Link>
                        <ul className="pagination listjs-pagination mb-0"></ul>
                        <Link className="page-item pagination-next" to="#">
                          Next
                        </Link>
                      </div>
                    </div>
                  </div>
                </CardBody>
              </Card>
            </Col>
          </Row>
        </Container>
      </div>
      <ToastContainer />

      <AddCampaignModal
        validation={validation}
        isEditingCampaign={isEditingCampaign}
        modal_list={modal_list}
        tog_list={tog_list}
        formHandleSubmit={formHandleSubmit}
        alreadyRegisteredError={alreadyRegisteredError}
        welcomeMessageAudio={welcomeMessageAudio}
        setWelcomeMessageAudio={setWelcomeMessageAudio}
        invalidMessageAudio={invalidMessageAudio}
        setInvalidMessageAudio={setInvalidMessageAudio}
        timeOutMessageAudio={timeOutMessageAudio}
        setTimeOutMessageAudio={setTimeOutMessageAudio}
        welcomeMessageTextOrAudioOptions={welcomeMessageTextOrAudioOptions}
        selectSingleWelcomeTextOrAudio={selectSingleWelcomeTextOrAudio}
        handleSelectSingleWelcomeMessageTextOrAudio={
          handleSelectSingleWelcomeMessageTextOrAudio
        }
        invalidMessageTextOrAudioOptions={invalidMessageTextOrAudioOptions}
        selectSingleInvalidTextOrAudio={selectSingleInvalidTextOrAudio}
        handleSelectSingleInvalidMessageTextOrAudio={
          handleSelectSingleInvalidMessageTextOrAudio
        }
        selectSingleTimeOutTextOrAudio={selectSingleTimeOutTextOrAudio}
        timeOutMessageTextOrAudioOptions={timeOutMessageTextOrAudioOptions}
        handleSelectSingleTimeOutMessageTextOrAudio={
          handleSelectSingleTimeOutMessageTextOrAudio
        }
        gatewayOptions={gatewayOptions}
        handleSelectSingleGateway={handleSelectSingleGateway}
        selectedSingleGateway={selectedSingleGateway}
      />

      <CampaignRemoveModal
        modal_delete={modal_delete}
        setmodal_delete={setmodal_delete}
        tog_delete={tog_delete}
        handleDeleteCampaign={() => {
          dispatch(removeCampaign(listCampaignId));
          setmodal_delete(false);
        }}
      />
    </React.Fragment>
  );
};

export default Campaigns;

AddCampaignModal.js

import {
  Alert,
  Input,
  Label,
  Form,
  FormFeedback,
  Modal,
  ModalBody,
  ModalHeader,
  Row,
  Col,
} from "reactstrap";
import "react-toastify/dist/ReactToastify.css";
import Select from "react-select";

function AddCampaignModal({
  modal_list,
  tog_list,
  formHandleSubmit,
  validation,
  isEditingCampaign,
  alreadyRegisteredError,
  welcomeMessageAudio,
  setWelcomeMessageAudio,
  invalidMessageAudio,
  setInvalidMessageAudio,
  timeOutMessageAudio,
  setTimeOutMessageAudio,
  welcomeMessageTextOrAudioOptions,
  selectSingleWelcomeTextOrAudio,
  handleSelectSingleWelcomeMessageTextOrAudio,
  invalidMessageTextOrAudioOptions,
  selectSingleInvalidTextOrAudio,
  handleSelectSingleInvalidMessageTextOrAudio,
  selectSingleTimeOutTextOrAudio,
  timeOutMessageTextOrAudioOptions,
  handleSelectSingleTimeOutMessageTextOrAudio,
  selectedSingleGateway,
  handleSelectSingleGateway,
  gatewayOptions,
}) {
  return (
    <Modal
      isOpen={modal_list}
      toggle={() => {
        tog_list();
      }}
      centered
      className="modal-lg"
    >
      <ModalHeader
        className="bg-light p-3"
        toggle={() => {
          tog_list();
        }}
      >
        {isEditingCampaign ? "Update Campaign" : "Add Campaign"}
      </ModalHeader>
      <Form className="tablelist-form" onSubmit={(e) => formHandleSubmit(e)}>
        <ModalBody style={{ paddingTop: "0px" }}>
          {alreadyRegisteredError && (
            <Alert color="danger" style={{ marginBlock: "10px" }}>
              {alreadyRegisteredError}
            </Alert>
          )}

          <Row>
            <Col md={6}>
              <div className="mb-2">
                <Label htmlFor="campaignName" className="form-label">
                  Campaign Name
                </Label>

                <Input
                  id="campaignName"
                  name="campaignName"
                  className="form-control"
                  placeholder="Enter Campaign Name"
                  type="text"
                  onChange={validation.handleChange}
                  onBlur={validation.handleBlur}
                  value={validation.values.campaignName || ""}
                  invalid={
                    validation.touched.campaignName &&
                    validation.errors.campaignName
                      ? true
                      : false
                  }
                />

                {validation.touched.campaignName &&
                validation.errors.campaignName ? (
                  <FormFeedback type="invalid">
                    {validation.errors.campaignName}
                  </FormFeedback>
                ) : null}
              </div>
            </Col>

            <Col md={6}>
              <div className="mb-2">
                <Label htmlFor="gatewayId" className="form-label">
                  Gateways
                </Label>

                <Select
                  id="gatewayId"
                  name="gatewayId"
                  value={selectedSingleGateway}
                  onChange={(gateway) => {
                    handleSelectSingleGateway(gateway);
                    validation.setFieldValue("gatewayId", gateway.id);
                  }}
                  gateway
                  options={gatewayOptions}
                  placeholder="Select Gateway"
                  styles={{
                    control: (provided, state) => ({
                      ...provided,
                      borderColor: state.isFocused ? "#a8d9f3" : "#ced4da",
                      "&:hover": {
                        borderColor: "#ced4da",
                      },
                    }),
                  }}
                />
              </div>
            </Col>

            <Col md={6}>
              <div className="mb-2">
                <Label
                  htmlFor="welcomeMessageTextOrAudioSelect"
                  className="form-label"
                >
                  Welcome Message Type
                </Label>

                <Select
                  id="welcomeMessageTextOrAudioSelect"
                  name="welcomeMessageTextOrAudioSelect"
                  value={selectSingleWelcomeTextOrAudio}
                  onChange={(messageOrAudio) => {
                    handleSelectSingleWelcomeMessageTextOrAudio(messageOrAudio);
                  }}
                  options={welcomeMessageTextOrAudioOptions}
                  placeholder="Select Welcome Message Type"
                  styles={{
                    control: (provided, state) => ({
                      ...provided,
                      borderColor: state.isFocused ? "#a8d9f3" : "#ced4da",
                      "&:hover": {
                        borderColor: "#ced4da",
                      },
                    }),
                  }}
                />
              </div>
            </Col>

            {selectSingleWelcomeTextOrAudio?.value === "Text" ? (
              <Col md={6}>
                <div className="mb-2">
                  <Label htmlFor="welcomeMessageText" className="form-label">
                    Welcome Message Text
                  </Label>

                  <Input
                    id="welcomeMessageText"
                    name="welcomeMessageText"
                    className="form-control"
                    placeholder="Enter Welcome Text"
                    type="text"
                    onChange={validation.handleChange}
                    onBlur={validation.handleBlur}
                    value={validation.values.welcomeMessageText}
                    invalid={
                      validation.touched.welcomeMessageText &&
                      validation.errors.welcomeMessageText
                        ? true
                        : false
                    }
                  />

                  {validation.touched.welcomeMessageText &&
                  validation.errors.welcomeMessageText ? (
                    <FormFeedback type="invalid">
                      {validation.errors.welcomeMessageText}
                    </FormFeedback>
                  ) : null}
                </div>
              </Col>
            ) : selectSingleWelcomeTextOrAudio?.value === "Audio" ? (
              <Col lg={6}>
                <div>
                  <Label htmlFor="formFile" className="form-label">
                    Welcome Message Audio
                  </Label>
                  <Input
                    id="welcomeMessageAudio"
                    name="welcomeMessageAudio"
                    className="form-control"
                    type="file"
                    onChange={(e) => setWelcomeMessageAudio(e.target.files[0])}
                  />
                </div>
              </Col>
            ) : (
              <Col lg={6}></Col>
            )}

            <Col md={6}>
              <div className="mb-2">
                <Label htmlFor="invalidMessageText" className="form-label">
                  Invalid Message Type
                </Label>

                <Select
                  id="invalidMessageTextOrAudioSelect"
                  name="invalidMessageTextOrAudioSelect"
                  value={selectSingleInvalidTextOrAudio}
                  onChange={(messageOrAudio) => {
                    handleSelectSingleInvalidMessageTextOrAudio(messageOrAudio);
                  }}
                  options={invalidMessageTextOrAudioOptions}
                  placeholder="Select Welcome Message Type"
                  styles={{
                    control: (provided, state) => ({
                      ...provided,
                      borderColor: state.isFocused ? "#a8d9f3" : "#ced4da",
                      "&:hover": {
                        borderColor: "#ced4da",
                      },
                    }),
                  }}
                />
              </div>
            </Col>

            {selectSingleInvalidTextOrAudio?.value === "Text" ? (
              <Col md={6}>
                <div className="mb-2">
                  <Label htmlFor="welcomeMessageText" className="form-label">
                    Invalid Message Text
                  </Label>

                  <Input
                    id="invalidMessageText"
                    name="invalidMessageText"
                    className="form-control"
                    placeholder="Enter Invalid Text"
                    type="text"
                    onChange={validation.handleChange}
                    onBlur={validation.handleBlur}
                    value={validation.values.invalidMessageText || ""}
                    invalid={
                      validation.touched.invalidMessageText &&
                      validation.errors.invalidMessageText
                        ? true
                        : false
                    }
                  />

                  {validation.touched.invalidMessageText &&
                  validation.errors.invalidMessageText ? (
                    <FormFeedback type="invalid">
                      {validation.errors.invalidMessageText}
                    </FormFeedback>
                  ) : null}
                </div>
              </Col>
            ) : selectSingleInvalidTextOrAudio?.value === "Audio" ? (
              <Col lg={6}>
                <div>
                  <Label htmlFor="formFile" className="form-label">
                    Invalid Message Audio
                  </Label>
                  <Input
                    id="invalidMessageAudio"
                    name="invalidMessageAudio"
                    className="form-control"
                    type="file"
                    onChange={(e) => setInvalidMessageAudio(e.target.files[0])}
                  />
                </div>
              </Col>
            ) : (
              <Col lg={6}></Col>
            )}

            <Col md={6}>
              <div className="mb-2">
                <Label
                  htmlFor="timeOutMessageTextOrAudioSelect"
                  className="form-label"
                >
                  TimeOut Message Type
                </Label>

                <Select
                  id="timeOutMessageTextOrAudioSelect"
                  name="timeOutMessageTextOrAudioSelect"
                  value={selectSingleTimeOutTextOrAudio}
                  onChange={(messageOrAudio) => {
                    handleSelectSingleTimeOutMessageTextOrAudio(messageOrAudio);
                  }}
                  options={timeOutMessageTextOrAudioOptions}
                  placeholder="Select Time Out Message Type"
                  styles={{
                    control: (provided, state) => ({
                      ...provided,
                      borderColor: state.isFocused ? "#a8d9f3" : "#ced4da",
                      "&:hover": {
                        borderColor: "#ced4da",
                      },
                    }),
                  }}
                />
              </div>
            </Col>

            {selectSingleTimeOutTextOrAudio?.value === "Text" ? (
              <Col md={6}>
                <div className="mb-2">
                  <Label htmlFor="timeOutMessageText" className="form-label">
                    TimeOut Message Text
                  </Label>

                  <Input
                    id="timeOutMessageText"
                    name="timeOutMessageText"
                    className="form-control"
                    placeholder="Enter TimeOut Text"
                    type="text"
                    onChange={validation.handleChange}
                    onBlur={validation.handleBlur}
                    value={validation.values.timeOutMessageText || ""}
                    invalid={
                      validation.touched.timeOutMessageText &&
                      validation.errors.timeOutMessageText
                        ? true
                        : false
                    }
                  />
                </div>
              </Col>
            ) : selectSingleTimeOutTextOrAudio?.value === "Audio" ? (
              <Col lg={6}>
                <div>
                  <Label htmlFor="formFile" className="form-label">
                    TimeOut Message Audio
                  </Label>
                  <Input
                    id="timeOutMessageAudio"
                    name="timeOutMessageAudio"
                    className="form-control"
                    type="file"
                    onChange={(e) => setTimeOutMessageAudio(e.target.files[0])}
                  />
                </div>
              </Col>
            ) : (
              <Col lg={6}></Col>
            )}
          </Row>

          <div className="text-end">
            <button type="submit" className="btn btn-primary">
              {isEditingCampaign ? "Update Campaign" : "Save Campaign"}
            </button>
          </div>
        </ModalBody>
      </Form>
    </Modal>
  );
}

export default AddCampaignModal;

Discard millisecond part from timestamp when defining schema with @dsnp/parquetjs library

I want to define a parquet schema using @dsnp/parquetjs library.

One of the fields of the Schema needs to be in Timestamp without milliseconds (Unix timestamp for instance).

The only available timestamp types in this library are TIMESTAMP_MILLIS and TIMESTAMP_MICROS.

Do you have some workaround solutions?

Here is my code so far

export const mySchema = new ParquetSchema({
  creationDate: {
    type: 'TIMESTAMP_MILLIS', // I need it without milliseconds part
    optional: true,
  },
  // ... other fields
});

How to display conditional inputs of radio buttons without removing generate buttons at the bottom

I’m building a program for work that assists in generating a medical SITREP report for our own purposes, and I’m having a bit of trouble with the HTML/jscript side of things. With help from ChatGPT, I was able to get the ball rolling a bit, but I’ve run into an issue…

The base of the HTML doc is a form with a series of labels and inputs for information that’s compiled in the function generateReport(). That section I plan to work on later; however, at the moment it’s part of the GUI that I’m trying to debug.

At the base of the code before the Generate Report and Copy SITREP buttons are a series of three radio buttons. I had it working once before, but the radio buttons were supposed to display different labels and inputs based on which radio button was selected. However, now for some reason, no matter which radio button is clicked, it doesn’t show any conditional inputs, and in fact it removes the Generate Report and Copy SITREP buttons entirely!

Like I said before, I attempted to use ChatGPT to assist me in debugging and fixing this issue, but it may have just made it worse in the process. Regardless, here’s the code I currently have. If you all are able to assist me with this issue, I’ll be extremely grateful! 🙂

function checkSymptoms() {
  var symptoms = document.getElementById("symptoms").value;
  var symptomsDetails = document.getElementById("symptomsDetails");
  if (symptoms === "smallCut" || symptoms === "jammed" || symptoms === "sprain" || symptoms === "eyeDamage" || symptoms === "other") {
    symptomsDetails.style.display = "inline-block";
  } else {
    symptomsDetails.style.display = "none";
  }
}

function showFields() {
  // Hide all conditional inputs initially
  document.getElementById('stayingWork').classList.add('hidden');
  document.getElementById('goingHome').classList.add('hidden');
  document.getElementById('emsResponse').classList.add('hidden');

  // Get the selected option
  const selectedOption = document.querySelector('input[name="response"]:checked')?.value;

  // Show fields based on selected option
  if (selectedOption === 'stayingWork') {
    document.getElementById('stayingWork').classList.remove('hidden');
  } else if (selectedOption === 'goingHome') {
    document.getElementById('goingHome').classList.remove('hidden');
  } else if (selectedOption === 'emsResponse') {
    document.getElementById('emsResponse').classList.remove('hidden');
  } else {
    document.getElementById('sitrepSection').classList.add('hidden');
  }
}

function generateReport() {
  var time1 = document.getElementById("time1").value;
  var timeZone = document.getElementById("timeZone").value;
  var employeeType1 = document.getElementById("employeeType1").value;
  var employee1 = document.getElementById("employee1").value;
  var employeeId1 = document.getElementById("employeeId1").value;
  var employeeType2 = document.getElementById("employeeType2").value;
  var employee2 = document.getElementById("employee2").value;
  var employeeId2 = document.getElementById("employeeId2").value;
  var symptoms = document.getElementById("symptoms").value;
  var symptomsDetails = document.getElementById("symptomsDetails").value;

  // Object mapping symptoms to sentence structures
  var symptomSentences = {
    "dizzy": "who was feeling dizzy while on shift",
    "nausea": "who began feeling nauseous while on shift",
    "vomit": "who had begun vommiting while on shift",
    "sweats": "who had started sweating heavily on shift",
    "smallCut": "who had sustained a small cut on their {details}",
    "eyeDamage": "who had sustained eye damage due to {details}",
    "jammed": "who had jammed their {details}",
    "breathing": "who was having trouble breathing",
    "tremors": "who was experiencing shakes and tremors in their {details}",
    "headInjury": "who had sustained a head injury while on shift",
    "slip": "who had experienced a slip and fall event",
    "sprain": "who had sprained their {details} while on shift",
    "chestPain": "who was experiencing chest pains",
    "severeHeadache": "who begun experiencing a severe headache",
    "labor": "who had begun experience symptoms of labor",
    "pregnancy complication": "who had possibly begun experiencing a pregnancy complication",
    "seizure": "who had experienced a seizure while on shift",
    "heartAttack": "who had begun showing symptoms of a heart attack",
    "feinting": "who had feinted while on shift",
    "panicAttack": "who began having a panic attack while on shift",
    "other": "who was experiencing {details}"
  };

  // If the symptom requires details (e.g., sprain location), we add it
  var sentence = symptomSentences[symptoms];
  if (symptoms === "smallCut" || symptoms === "eyeDamage" || symptoms === "jammed" || symptoms === "tremors" || symptoms === "sprain" || symptoms === "other") {
    if (symptomsDetails) {
      sentence = sentence.replace("{details}", symptomDetails);
    } else {
      sentence = sentence.replace("{details}", "unspecified area");
    }
  }
  var mod = document.getElementById("mod").value;
  var location = document.getElementById("location").value;
  var time2 = document.getElementById("time2").value;
  var ERTMember = document.getElementById("ERTMember").value;
  var ERTResponse = document.getElementById("ERTResponse").value;

  var report = "At " + time1 + " " + timeZone + ", the RSOC (Regional Security Operations Center) received a call from " +
    employeeType1 + " employee " + employee1 + " (" + employeeId1 + ") regarding " + employeeType2 + " employee " + employee2 + " (" + employeeId2 + ") " +
    sentence + " in Mod " + mod + " nearby column " + location + ". The ERT Team was contacted through the Push To Talk (PTT) phone at " + time2 + " " + timeZone +
    ", and ERT Team member " + ERTMember + " responded stating that they were en route. ERT arrived at the patient at " + ERTResponse + " " + timeZone +
    " and began assessing the situation. ";

  document.getElementById("sitrepReport").textContent = report;
  alert("SITREP Generated!");
}

function copyToClipboard() {
  var reportText = document.getElementById("sitrepReport").textContent;
  navigator.clipboard.writeText(reportText).then(function() {
    alert('SITREP Report copied to clipboard');
  }, function(err) {
    alert('Error in copying text: ', err);
  });
}
body {
  font-family: Arial, sans-serif;
  background-color: #f4f4f4;
  margin: 0;
  padding: 20px;
}

h1 {
  color: #333;
}

form {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  max-width: 900px;
  margin: auto;
}

.form-group {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  box-sizing: border-box;
}

.form-group label {
  flex: 0 0 auto;
  margin-right: 10px;
  font-weight: bold;
}

.form-group input[type="text"],
.form-group select {
  flex: 1;
  margin: 0;
  margin-right: 10px;
  box-sizing: border-box;
}

.form-group input[type="button"] {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.form-group input[type="button"]:hover {
  background-color: #45a049;
}

.radio-group {
  margin-bottom: 10px;
}

.radio-group label {
  margin-right: 20px;
}

.conditional-inputs {
  display: none;
  margin-top: 10px;
}

.conditional-inputs input[type="text"] {
  width: 100%;
  max-width: 500px;
  margin: 5px 0;
  box-sizing: border-box;
}

pre {
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  max-width: 800px;
  margin: auto;
}

#copyButton {
  background-color: #008CBA;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  margin-top: 10px;
}

#copyButton:hover {
  background-color: #007bb5;
}

.hidden {
  display: none;
}
<h1>Medical SITREP Report Generator</h1>
<form id="incidentForm">
  <div class="form-group">
    <label for="time1">Initial Call Time:</label>
    <input type="time" id="time1" name="time1" required>
    <label for="timeZone">Time Zone:</label>
    <select id="timeZone" name="timeZone" required>
      <option value="">Select Time Zone</option>
      <option value="CST">CST</option>
      <option value="EST">EST</option>
      <option value="PST">PST</option>
    </select>
  </div>
  <div class="form-group">
    <label for="employeeType1">Company:</label>
    <select id="employeeType1" name="employeeType1" required>
      <option value="">--Select Company--</option>
      <option value="Flex">Flex</option>
      <option value="Aramark">Aramark</option>
      <option value="SolarEdge">SolarEdge</option>
      <option value="Aerotek">Aerotek</option>
      <option value="Hallmark">Hallmark</option>
      <option value="VOLT">VOLT</option>
      <option value="Staffmark">Staffmark</option>
      <option value="ONIN">ONIN</option>
      <option value="Allied Universal">Allied Universal</option>
      <option value="Facilities">Facilities</option>
      <option value="Other">Other</option>
    </select><br>
    <label for="employee1">Reporting Employee:</label>
    <input type="text" id="employee1" name="employee1" required>
    <label for="employeeId1">ID Number:</label>
    <input type="text" id="employeeId1" name="employeeId1" required>
  </div>
  <div class="form-group">
    <label for="employeeType2">Company:</label>
    <select id="employeeType2" name="employeeType2" required>
      <option value="">--Select Company--</option>
      <option value="Flex">Flex</option>
      <option value="Aramark">Aramark</option>
      <option value="SolarEdge">SolarEdge</option>
      <option value="Aerotek">Aerotek</option>
      <option value="Hallmark">Hallmark</option>
      <option value="VOLT">VOLT</option>
      <option value="Staffmark">Staffmark</option>
      <option value="ONIN">ONIN</option>
      <option value="Allied Universal">Allied Universal</option>
      <option value="Facilities">Facilities</option>
      <option value="Other">Other</option>
    </select>
    <label for="employee2">Patient Name:</label>
    <input type="text" id="employee2" name="employee2" required>
    <label for="employeeId2">Patient ID Number:</label>
    <input type="text" id="employeeId2" name="employeeId2" required>
  </div>
  <div class="form-group">
    <label for="symptoms">Symptoms:</label>
    <select id="symptoms" name="symptoms" onchange="checkSymptoms()" required>
      <option value="">--Select Symptoms--</option>
      <option value="dizzy">Dizziness</option>
      <option value="nausea">Nausea</option>
      <option value="vommit">Vommiting</option>
      <option value="sweats">Sweating</option>
      <option value="smallCut">Small Cut</option>
      <option value="eyeDamage">Something in their eye</option>
      <option value="jammed">Jammed Body Part</option>
      <option value="breathing">Difficulty Breathing</option>
      <option value="tremors">Tremors and/or Shakes</option>
      <option value="headInjury">Head injury</option>
      <option value="slip">Slip and Fall</option>
      <option value="sprain">Sprain</option>
      <option value="chestPain">Chest Pain</option>
      <option value="severeHeadache">Severe Headache</option>
      <option value="labor">Labor</option>
      <option value="pregnancy complication">Pregnancy Complication</option>
      <option value="seizure">Seizure</option>
      <option value="heartAttack">Heart Attack Symptoms</option>
      <option value="feinting">Feinting</option>
      <option value="panicAttack">Anxiety/Panic Attack</option>
      <option value="other">Other</option>
    </select>
    <input type="text" id="symptomsDetails" name="symptomsDetails" placeholder="Provide more details" style="display:none; margin-left: 10px;">
  </div>
  <div class="form-group">
    <label for="mod">Mod:</label>
    <select id="mod" name="mod" required>
      <option value="">--Select Mod--</option>
      <option value="A">A</option>
      <option value="B">B</option>
      <option value="C">C</option>
      <option value="D">D</option>
      <option value="E">E</option>
      <option value="F">F</option>
      <option value="G">G</option>
      <option value="H">H</option>
      <option value="I">I</option>
      <option value="J">J</option>
      <option value="K">K</option>
      <option value="L">L</option>
      <option value="M">M</option>
      <option value="N">N</option>
      <option value="O">O</option>
      <option value="P">P</option>
      <option value="Q">Q</option>
      <option value="R">R</option>
      <option value="S">S</option>
      <option value="T">T</option>
      <option value="U">U</option>
      <option value="V">V</option>
      <option value="W">W</option>
    </select>
    <label for="location">Exact Location:</label>
    <input type="text" id="location" name="location" required>
  </div>
  <div class="form-group">
    <label for="time2">Time ERT Team Contacted:</label>
    <input type="time" id="time2" name="time2" required style="width: 150px;">
  </div>
  <div class="form-group">
    <label for="ERTMember">Responding ERT Member:</label>
    <input type="text" id="ERTMember" name="ERTMember" required>
  </div>
  <div class="form-group">
    <label for="ERTResponse">Time ERT Arrived:</label>
    <input type="time" id="ERTResponse" name="ERTResponse" required>
  </div>
  <div class="radio-group">
    <label><input type="radio" name="response" value="stayingWork" onclick="showFields()"> Staying at Work</label>
    <label><input type="radio" name="response" value="goingHome" onclick="showFields()"> Going Home</label>
    <label><input type="radio" name="response" value="emsResponse" onclick="showFields()"> EMS Responded</label>
  </div>
  <div id="stayingWork" class="hidden">
    <label for="allClearTime">Time of All Clear:</label>
    <input type="time" id="allClearTime" name="allClearTime" </div>
    <div id="goingHome" class="hidden">
      <label for="leftSite">Left site at:</label>
      <input type="time" id="leftSite" name="leftSite"><br>
      <label for="homeAllClearTime">Time of All Clear:</label>
      <input type="time" id="homeAllClearTime" name="homeAllClearTime">
    </div>
    <div id="emsResponse" class="hidden">
      <label for="unitNumber">Unit #:</label>
      <input type="text" id="unitNumber" name="unitNumber"><br>
      <label for="arrivedSite">Arrived at Site:</label>
      <input type="time" id="arrivedSite" name="arrivedSite"><br>
      <label for="arrivedPatient">Arrived at Patient:</label>
      <input type="time" id="arrivedPatient" name="arrivedPatient"><br>
      <label for="hospitalName">Hospital Name:</label>
      <input type="text" id="hospitalName" name="hospitalName"><br>
      <label for="leftSiteEMS">Left site at:</label>
      <input type="time" id="leftSiteEMS" name="leftSiteEMS"><br>
      <label for="emsAllClearTime">Time of All Clear:</label>
      <input type="time" id="emsAllClearTime" name="emsAllClearTime">
    </div>
    <div class="form-group">
      <h2>SITREP Report:</h2>
      <pre id="sitrepReport:"></pre>
      <button type="button" onclick="generateReport()">Generate SITREP</button>
      <button type="button" onclick="copyToClipboard()">Copy SITREP</button>
    </div>
</form>