How to change the Header hrml of react bootstrap accordion when clicked

I have a React Bootstrap4 Accordion component that is working 90% correctly.

function ContextAwareToggle({ children, eventKey, callback }) {
  const currentEventKey = useContext(AccordionContext);

  const decoratedOnClick = useAccordionToggle(
    eventKey,
    () => callback && callback(eventKey),
  );

  const isCurrentEventKey = currentEventKey === eventKey;

  let toggleText;
  if (isCurrentEventKey) {
    toggleText = '<h3>Up arrow &#5169;</h3>'
  } else {
    toggleText = '<h3>Down arrow &#5167;</h3>'
  }

  return (
    <Accordion.Toggle
      as={Card.Header}
      style={{ backgroundColor: isCurrentEventKey ? '#87CEEB' : '#00BFFF' }}
      onClick={decoratedOnClick}
    >
    {
      (isCurrentEventKey && <h3>Up arrow &#5169;</h3>) ||
      (!isCurrentEventKey && <h3>Down arrow &#5167;</h3>)
    }

    </Accordion.Toggle>
  );
}

return (
  <Container>
    <h2>Title: </h2> click on the arrow below.
    <Accordion defaultActiveKey="0">
      <Card>
        <Card.Header>
          <ContextAwareToggle eventKey="0">
          </ContextAwareToggle>
        </Card.Header>
        <Accordion.Collapse eventKey="0">
          <Card.Body>
            Accordion Body text
          </Card.Body>
        </Accordion.Collapse>
      </Card>
    </Accordion>
)

When I click the card.header, the show/hide action is correct. The background color of the header change is correct. However, the text in the header is shown as a literal text. I want the <h3> to be interpreted as an HTML tag instead of being displayed in plain text. I also want to show the HTML symbol for the Up and Down arrows instead of the whole ‘ᐯ’ being displayed as plain text.

Issue with API route and or nodemailer for contact form submissions, method not allowed error code 405

I have a contact form that I want to automate to send validated user input to an email address. I’m not sure what’s wrong at this point but I feel as though I’m not using nodemailer correctly. These are the relevant code snippets. Btw I’m using live server and running the server on the same port to not have a cross origin problem. And these are the errors I get when I try to submit a sample form submission

I did a lot it’s basically all in the code, I used the CORS package to solve the possible cross origin problem. The createTransport code block is not what it was before as I changed it due to a recommendation of a friend who looked through nodemailers documentation. I managed to solve some console error messages but the biggest one being the 405 error I can’t seem to fix. I’ve tried everything at this point

Console error messages

server.mjs:7 Uncaught SyntaxError: Cannot use import statement outside a module
index.js:198     POST http://127.0.0.1:5500/api/submit-form net::ERR_ABORTED 405 (Method Not Allowed)
submitFormData @ index.js:198
(anonymous) @ index.js:232
setTimeout (async)
(anonymous) @ index.js:231
index.js:203 Response Status Code: 405

html

        <section class="py-20">
            <div class="flex justify-center items-center w-screen h-screen bg-white">
                <div class="container mx-auto my-4 px-4 lg:px-20">
                    <form id="form" method="POST" class="w-full p-8 my-4 md:px-12 lg:w-9/12 lg:pl-20 lg:pr-40 mr-auto rounded-2xl shadow-2xl">
                        <div class="flex justify-center">
                            <h1 class="font-semibold text-5xl">Let Us Know What's On Your Mind</h1>
                        </div>
                        <div class="grid grid-cols-1 gap-4 md:grid-cols-2 mt-5">
                            <input id="fullName" autocomplete="off" required class="w-full bg-gray-200 text-gray-900 mt-2 p-3 rounded-lg focus:outline-none focus:shadow-outline" type="text" placeholder="Full Name*"/>

                            <input id="subject" autocomplete="off" required class="w-full bg-gray-200 text-gray-900 mt-2 p-3 rounded-lg focus:outline-none focus:shadow-outline" type="text" placeholder="Subject*"/>

                            <input id="emailAddress" autocomplete="off" required class="w-full bg-gray-200 text-gray-900 mt-2 p-3 rounded-lg focus:outline-none focus:shadow-outline" type="email" placeholder="Email Address* (Proper format please)"/>

                            <input id="phoneNumber" autocomplete="off" type="tel" required class="w-full bg-gray-200 text-gray-900 mt-2 p-3 rounded-lg focus:outline-none focus:shadow-outline" placeholder="Phone Number* (Proper format please)"/>
                        </div>
                        <div class="my-4">
                            <textarea id="message" autocomplete="off" required placeholder="Message* (40 character minimum)" class="w-full h-40 bg-gray-200 text-gray mt-2 p-3 rounded-lg focus:outline-none focus:shadow-outline"></textarea>
                        </div>
                        <div class="my-2 gap-6 w-full lg:w-1/4 flex">
                            <button id="cancel" class="text-base font-bold tracking-wide bg-red-600 text-white p-3 rounded-lg w-full focus:outline-none focus:shadow-outline">Cancel</button>
                            <button style="background-color: rgb(21, 128, 61);" id="submit" type="submit" class="text-base font-bold tracking-wide text-white p-3 rounded-lg w-full focus:outline-none focus:shadow-outline">Submit</button>
                        </div>
                    </form>
                </div>
            </div>
        </section>

index.js

const submitFormData = () => {
    const formData = new FormData(form);

    fetch('/api/submit-form', {
        method: 'POST',
        body: formData,
    })
    .then((res) => {
        console.log('Response Status Code:', res.status);
        if (res.ok) {
            form.reset();
            formSubmissionStatus.textContent = 'Form submitted successfully!';
            formSubmissionStatus.classList.remove('bg-black');
            formSubmissionStatus.style.backgroundColor = 'rgb(21, 128, 61)';
        } else {
            formSubmissionStatus.textContent = 'Form submission failed';
            formSubmissionStatus.classList.remove('bg-black');
            formSubmissionStatus.style.backgroundColor = '';
            formSubmissionStatus.classList.add('bg-red-600');
        }
    })
    .catch((error) => {
        console.error('Fetch Error:', error);
        formSubmissionStatus.textContent = 'An error occured, please try again.';
        formSubmissionStatus.classList.add('bg-black', 'text-white-700');
    });
};


form.addEventListener('submit', (e) => {
    e.preventDefault();
    if(formValidityCheck()) {
        submitButton.disabled = true;
        formSubmissionStatus.textContent = 'Submitting...';
        formSubmissionStatus.classList.add('bg-black', 'text-white');

        setTimeout(() => {
            submitFormData();
        }, 500);
    }
});

server.mjs

import nodemailer from 'nodemailer';
import dotenv from 'dotenv';
import express from 'express';
import cors from 'cors';
import { body, validationResult } from 'express-validator';
const port = process.env.PORT || 5500;
const app = express();
const corsOptions = {
    origin: 'http://127.0.0.1:5500/',
};


app.use(cors(corsOptions));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.post('/api/submit-form', [
    body('fullName').trim().isLength({ min: 2 }).escape(),
    body('subject').trim().isLength({ min: 3 }).escape(),
    body('emailAddress').trim().isEmail().normalizeEmail(),
    body('phoneNumber').trim().isMobilePhone('any').escape(),
    body('message').trim().isLength({ min: 40 }).escape(),
], async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
    }

    try {
        const { fullName, subject, emailAddress, phoneNumber, message } = req.body;

        const transporter = nodemailer.createTransport("SMTP",{
            host: "smtp-mail.outlook.com",
            port: 587,
            secure: false,
            auth: {
                user: process.env.EMAIL_USERNAME,
                pass: process.env.EMAIL_PASSWORD
            },
        });

        const mailOptions = {
            from: process.env.EMAIL_FROM,
            to: process.env.EMAIL_SENDER,
            subject: `New Contact Form Submission! ${subject}`,
            text: `Full Name: ${fullName}nEmail: ${emailAddress}nPhone: ${phoneNumber}nnMessage: ${message}`,
        };

        await transporter.sendMail(mailOptions);
        res.status(200).json({ message: 'Form submitted successfully' });
        console.log('Response Status Code:', 200);
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: 'Internal server error'});
        console.log('Response Status Code:', 500);
    }
});

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

Issue with function ending before http request completes [duplicate]

I am creating a chat bot in DialogFlow CX that is calling a node.js function in Google Cloud Functions that makes an external API Call. As an aside I am new to all three of these but feel like I am pretty close. The problem I am running into is my google cloud function is finishing and sending a response back to DialogFlow Cx prior to my external api call finishing up. I know my external API call is working and finishing because in logs I see that after the main google cloud function completes that the results of the API call are logged, I just need it to finish before the main google cloud function can finish. Any help is appreciated. Below is the code and log messages.

Code

const functions = require('@google-cloud/functions-framework');
const https = require('https');

let orderStatus = "Unknown";

//helloHttp is entry point for google cloud 
exports.helloHttp =(req, res) => {
  
  const orderNumber = req.body.sessionInfo.parameters.ordernumber;
  console.log(orderNumber);
  
  orderStatus = getOrderStatus(orderNumber, orderStatus);
  

  const jsonResponse = {
    fulfillment_response: {
      messages: [
        {
          text: {
            text: [orderStatus],
          },
        },
      ],
    },
  };
  res.status(200).send(jsonResponse); 
  console.log(orderStatus)
};

function getOrderStatus(orderNumber, orderStatus){

  var options = {
    'secret stuff'
  };

  var req = https.request(options, (res) => {
    console.log('statusCode:', res.statusCode);

    let rawData = ''
    res.on('data', chunk => {
      rawData += chunk
    })

    res.on('end', () => {
      const parsedData = JSON.parse(rawData)
      console.log(parsedData);
      orderStatus = parsedData.order.status;
      console.log(orderStatus);
    })
  });

  req.on('error', (e) => {
    console.error(e);
  });
  
  req.end();

  return orderStatus

};

Logs

2023-09-18 17:44:12.522 EDT
getOrder382rngukw4pe Function execution started

2023-09-18 17:44:12.551 EDT
getOrder382rngukw4pe 46824

2023-09-18 17:44:12.739 EDT
getOrder382rngukw4pe Unknown

2023-09-18 17:44:12.740 EDT

getOrder382rngukw4pe Function execution took 217 ms, finished with status code: 200

2023-09-18 17:44:12.792 EDT
getOrder382rngukw4pe statusCode: 200

2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe {

2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe order: {

2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe delivery: null,

2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe external_reference_number: null,

2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe id: ‘46824’,

2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe pickup: null,

2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe return: null,

2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe shipping: null,

2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe status: ‘cancelled’

2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe }

2023-09-18 17:44:12.795 EDT
getOrder382rngukw4pe }

2023-09-18 17:44:12.795 EDT

Thought maybe this is an async problem but not really sure how to address

javascript is not updating the timer after a while

i tested a simple timer code for showing timer in website. The timer working fine when i am on the page. But when i go the another page or site, after a while when i come back to the timer page i see that timer did not worked correctly in the interval.
Suppose i leave the page for 5 minutes. So when I will come back, I should see 00:05:00. But it is displaying 00:01:00 (around).
But if i dont leave the page it is working fine.
What is the solution?

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1 id="time"></h1>
    <script>
        timerElement = document.getElementById("time");
        let seconds = 0, minutes = 0, hours = 0;
        timerInterval = setInterval(function () {
            seconds++;

            if (seconds === 60) {
                seconds = 0;
                minutes++;

                if (minutes === 60) {
                    minutes = 0;
                    hours++;
                }
            }

            const formattedTime = `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
            timerElement.textContent = formattedTime;
        }, 1000);
    </script>
</body>

</html>

Even I deployed this on github page. But result is same.

zod “optional()” but disallow undefined value

I have a following zod example:

const objectSchema = z.object({
  optional: z.string().optional(),
  other: z.string(),
});

In typescript, optional field key?: string will be converted to key?: string | undefined. But it’s strictly different during the runtime check.
The previous one during the runtime check could be interpreted as the optional must be string if it exists, hence optional: undefined is an invalid input.

So, is there any way I can do with zod that makes the undefined an invalid input.

hence

  objectSchema({ other: "other" }) //pass.
  objectSchema({ optional: undefined, other: "other" }) // fail
  objectSchema({ optional: "str", other: "other" }) // pass

ERROR: THREE.PlaneBufferGeometry is not a constructor

i don’t know where is the problem but on console says this error:

THREE.PlaneBufferGeometry is not a constructor

thats the code


function particleSetup() {
    let loader = new THREE.TextureLoader() ;

    loader. load("smoke.png", function (texture){
        portalGeo = new THREE.PlaneBufferGeometry(350, 350);
        portalMaterial = new THREE.MeshStandardMaterial({
            map: texture,
            transparent: true
        });

        smokeGeo = new THREE.PlaneBufferGeometry(1000,1000);
        smokeMaterial = new THREE.MeshStandardMaterial ({
            map: texture,
            transparent: true
        });

        for (let p=880;p>250;p--) {
            let particle = new THREE.Mesh(portalGeo,portalMaterial);
            particle.position.set (
                0.5 * p * Math.cos ( (4 * p * Math.PI) / 180),
                0.5 * p * Math.sin ( (4 * p * Math.PI) / 180),
                0.1 * p
            );
            particle.rotation.z = Math.random() *360;
            portalParticles.push(particle);
            scene.add(particle);
        }

        for (let p=0;p<40;p++) {
            let particle = new THREE.Mesh (smokeGeo, smokeMaterial);
            particle.position.set (
                Math.random () * 1000-500,
                Math.random () * 400-200,
                25
            );
            particle.rotation.z = Math.random () *360;
            particle.material.opacity = 0.6;
            portalParticles.push (particle);
            scene.add (particle);
        }

        clock = new THREE.Clock ();
        animate ( );

    });
}

These are my first tests with three.js, I’ve searched everywhere but I don’t understand the problem, i think is something with PlaneBufferGeometry

How to console.log the current time of functions being called/executed (JavaScript)?

I’m building this webscraper app and I wanted to console the time my functions are being executed. Reason is I wanted to better control when each of my functions are going to be executed to avoid flooding the website with requests at the same time. These are async functions as I need certain lines to be executed before others. I was able to ‘organize’ them and choose which one is going to be executed first by using promises. Now I’d like to console.log the time each function is being executed so I can better setTimeout each of them.

A small sample of my code follows:

scrapeCheese()
.then(scrapeCheeseBlock)
.then(mediumCheeseSlices)

/* Scrape refrigeratedFoodSection */

function scrapeCheese() {
}
.
.
.

function scrapeCheeseBlock() {
}
.
.
.

function mediumCheeseSlices() {
  return new Promise(function (resolve, reject) {
    async function scrapeUrl(url) {
      const browser = await puppeteer.launch({ headless: "new" });

I’ve tried building a scraperTimer but it didn’t work. It brings back the same time for all functions even tough I have called the timer inside of each of my scraping functions:

const scrapeClock = new Date();
const hour = scrapeClock.getHours();
const min = scrapeClock.getMinutes();
const second = scrapeClock.getSeconds();
const scrapeTimer = hour+':'+min+":"+second

Screenshot of terminal

I’m new to this so I still not understanding if functions are all called at the same time but executed in different times (because of the promises), or if they are actually being executed at different times (which is what I was expecting by using promises) and the problem resides in my scrapTimer being faulty.

module not found error when trying to import components

I am working on my portfolio website and am learning NEXT.JS because I want to deploy with vercel. Not sure why but I am getting a module not found error and it is related to my imports but my pathing is correct and my file names match so I am not sure why this is happening. I am exporting my functions in each file as well. Any help would be appreciated.

These are my file names:

import ProjectCard from '../src/app/components/ProjectCard';
import AboutMe from '../src/app/components/AboutMe';
import ContactForm from '../src/app/components/ContactForm';
import Header from '../src/app/components/Header';

ProjectCard
Header
ContactForm
AboutMe

I do not get an error when I use standard camel casing for my file names instead of pascal naming convention but this would not properly call the functions from my path.

Static background with jQuery dRawr and canvas

My work has this program that needs people to draw their answers which we have all working but now they want to be able to have a image loaded into the canvas that is able to be drawn on. Again I was able to get this worked out.

However, this image is taken and drawn into the canvas meaning when someone erases or clears the drawing the image parts get erased or cleared etc… How can I make the image static and not able to be edited? I want only what they have drawn to be editable.

here’s my example:

html:

<div id="drawr-container" style="margin:20px;width:450px;height:450px;border:2px dotted gray;" img-src="<?php echo $response; ?>">
     <canvas id="canvas-<?php echo $modQuestions->section_num; ?>" class="question-canvas drawr-canvas"></canvas>
</div>

jquery:

$(document).ready(function() {
    if($(".question-canvas").length) {
    function init_canvas1(){
        $("#drawr-container .question-canvas").drawr({
            "enable_transparency" : false,
            "canvas_width" : 800,
            "canvas_height" : 600
        });
        $("#drawr-container .question-canvas").drawr("start");
        $("#drawr-container .question-canvas").drawr("load",$(this).parent().attr("img-src"));
    }
    init_canvas1();

$(".question-canvas").each(function(index) {
        var ctx = $(this)[0].getContext('2d');
        var img = new Image;
        if($(this).parent().attr("img-src")) {
            img.onload = function() {
                ctx.drawImage(img, 0, 0);
            }
            img.src = $(this).parent().attr("img-src");
        }     
    });

so this works if the response there in the img-src attribute is say “/assets/media/canvas_backgrounds/usmap.jpg” it will display the image but the user is able to edit it. I’ve searched a while now and am stumped,

Need postman to wait for the population of an array before running tests, tried lots and lot, it’s just not working :(

Consider the script below, I need the 2nd for loop to finish running before the tests are run, I have tried lots, the only thing that works is setting interval, but this is problematic as it sporadically fails when run on postman monitor, is there another surefire way to make sure these tests are not run until the for loop has completed and populated the transitionNamesArray?

var jsonData = pm.response.json();
var getStateByIdUrl = pm.environment.get("host") + "/" + pm.environment.get("project-key") + "/states/";
var authToken = pm.environment.get("ctp_access_token");
let transitionsArray = jsonData.transitions;
let transitionNamesArray = [];
let transitionIdsArray = [];

for (let i = 0; i < jsonData.transitions.length; i++) {
    transitionIdsArray.push(jsonData.transitions[i].id);
}

console.log(transitionIdsArray)

async function getTransitionNames() {
    for (let t = 0; t < transitionIdsArray.length; t++) {
        const getRequestTransitions = {
            url: getStateByIdUrl + transitionIdsArray[t],
            method: 'GET',
            header: {
                'Authorization': 'Bearer ' + authToken
            }
        };

        await pm.sendRequest(getRequestTransitions, (err, res) => {
            res = res.json();
            transitionNamesArray.push(res.name['en'])
            console.log(transitionNamesArray);
        })

    }
    pm.test("Transitions contain 'Partially Delivered' and 'Delivered'", () => {
        pm.expect(transitionNamesArray).to.include("Delivered");
        pm.expect(transitionNamesArray).to.include("Partially Delivered");
    })

}

getTransitionNames()

I have tried running the getTransitionNames() function within pm.test() function, thinking it would run the function before attempting the pm.expect(), no luck, have tried loads of things, with no luck, at my wits’ end, please help 🙁

findLast does not work on typescript and ask that findLast is not in schema

I am new to ts and i am struggling with making things work. This time, I have data as an array and i want to find last element in array that match a condition

const data = props.data as Array<MessageEvent<unknown>>;
const objectData = data.findLast((element as MessageEvent<unknown>) => {
      return element.topic == CAMERA_TRACK_TOPIC;
    }) as MessageEvent<Epm5Msg>;

i am getting error in findLast stating that

Property ‘findLast‘ does not exist on type type1 ( i removed the type schema but it was type schema of MessageEvent<unknown>.

can anyone help me on this.

How to make relational Prisma query with multiple conditions?

I’m a little confused on what options to pass in to items.findMany to achieve the particular result I’m looking for.

My DB Schema looks like this:

enum progress_status {
  validating
  valid
  invalid
}

model items {
  id               String
  item_name     String
  status           item_status  
}

model item_status {
  id            String        
  item_id       String
  status        progress_status
}

I’d like to query for all items where item_name starts with a certain value (For a search feature), and where its status is a certain status. So for example, get all items that start with foo and have a status of valid

So far I have the text query working with:

  const result = await client.items.findMany({
    where: {
      item_name: {
        startsWith: query,
      }
    },
    orderBy: {
      project_name: 'asc',
    }
  });

But I’m having trouble adding the condition for the status. I know I can include the status data with an include parameter, but I am uncertain how to additional filter results by status.

How can I run .exe files with electron already built?

I tried these steps:
exec("./public/Tools/DJOULECO-CLI-MOUSE/dist/FILE.exe");

And this:
exec(file://${path.join(__dirname, "../build/Tools/DJOULECO-CLI-MOUSE/dist/FILE.exe")});

Nothing works

The intention is to run the .exe files with electronic already built because without building the exec("./public/Tools/DJOULECO-CLI-MOUSE/dist/FILE.exe"); it works perfectly