Swiper does not work in separated Tab in PHP

In the <div class="B"> section, if I write:

<?php for ($i = 1; $ i <= 1; $i++) : ?>

it works, however this:

<?php for ($i = 1; $i <= 7; $i++) : ?> 

does not work like a photo.

Somebody knows why this happens?

[enter image description here](https://i.sstatic.net/nN7WnbPN.png)

My PHP code:

<?php

/**
 * Template Name: xxxxxx
 */

?>

<?php get_header(); ?>
<main>

    <section class="sec-t">
        <div class="cnt">
            <div class="store_info">
                <div class="A">
                    <div class="about-shop">
                        <div>
                            <div class="swiper-container main-image-container">
                                <div class="swiper-wrapper">
                                    <?php for ($i = 1; $i <= 17; $i++) : ?>
                                        <div class="swiper-slide">
                                            <img src="<?php imgurl(); ?>/store/xxx_store/xxx_store_inside/xxx_store_inside<?php echo $i; ?>.jpg" alt="xxx<?php echo $i; ?>">
                                        </div>
                                    <?php endfor; ?>
                                </div>
                                <?php
                                if ($i > 2): ?>
                                    <div class="swiper-pagination"></div>
                                <?php endif; ?>
                                <div class="swiper-button-next"></div>
                                <div class="swiper-button-prev"></div>
                            </div>
                        </div>
                        <div class="swiper-container seat-image-container">
                            <div class="swiper-wrapper">
                                <?php for ($i = 1; $i <= 7; $i++) : ?>
                                    <div class="swiper-slide">
                                        <img src="<?php imgurl(); ?>/store/xxx_store/xxx_c/xxx_c<?php echo $i; ?>.jpg" alt="c_seat_image<?php echo $i; ?>">
                                    </div>
                                <?php endfor; ?>
                            </div>
                            <?php
                            if ($i > 2): ?>
                                <div class="swiper-pagination"></div>
                            <?php endif; ?>
                            <div class="swiper-button-next"></div>
                            <div class="swiper-button-prev"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="B">
            <div class="cnt">
                    <div class="swiper-container seat-image-container">
                        <div class="swiper-wrapper">
                            <?php for ($i = 1; $i <= 7; $i++) : ?>
                                <div class="swiper-slide">
                                    <img src="<?php imgurl(); ?>/store/xxx_store/xxx_c/xxx_c<?php echo $i; ?>.jpg" alt="c_seat_image<?php echo $i; ?>">
                                </div>
                            <?php endfor; ?>
                        </div>
                        <?php

                        if ($i > 2): ?>
                            <div class="swiper-pagination2"></div>
                        <?php endif; ?>
                        <div class="swiper-button-next2"></div>
                        <div class="swiper-button-prev2"></div>
                    </div>
                </div>
            </div>
        </div>
        </div>

        </div>
    </section>

</main>

<script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>


<?php get_footer(); ?>

My main.js script:

document.addEventListener('DOMContentLoaded', function() {
    // When you click tab1
    document.getElementById('tab1').addEventListener('click', function() {
        document.querySelector('.A').style.display = 'block';
        document.querySelector('.B').style.display = 'none';
        // document.querySelector('.C').style.display = 'none';
        document.querySelector('#tab1').classList.remove('off');
        document.querySelector('#tab2').classList.remove('on');
        document.querySelector('#tab3').classList.remove('on');
        document.querySelector('#tab1').classList.add('on');
        document.querySelector('#tab2').classList.add('off');
        document.querySelector('#tab3').classList.add('off');
    });

    // When you click tab2
    document.getElementById('tab2').addEventListener('click', function() {
        document.querySelector('.A').style.display = 'none';
        document.querySelector('.B').style.display = 'block';
        // document.querySelector('.C').style.display = 'none';
        document.querySelector('#tab1').classList.remove('on');
        document.querySelector('#tab2').classList.remove('off');
        // document.querySelector('#tab3').classList.remove('on');
        document.querySelector('#tab1').classList.add('off');
        document.querySelector('#tab2').classList.add('on');
        // document.querySelector('#tab3').classList.add('off');
    });


});


document.addEventListener('DOMContentLoaded', function() {

    var swipers = document.querySelectorAll('.swiper-container');

    swipers.forEach(function(swiperContainer) {
        var slideCount = swiperContainer.querySelectorAll('.swiper-slide').length;

        if (slideCount <= 1) {
            swiperContainer.querySelector('.swiper-button-next').style.display = 'none';
            swiperContainer.querySelector('.swiper-button-prev').style.display = 'none';
        }

        new Swiper(swiperContainer, {
            loop: slideCount > 1,
            slidesPerView: 1,
            centeredSlides: false,
            effect: 'fade',
            pagination: {
                el: swiperContainer.querySelector('.swiper-pagination'),
                type: 'fraction',
            },
            fadeEffect: {
                crossFade: true
            },
            navigation: {
                nextEl: swiperContainer.querySelector('.swiper-button-next'),
                prevEl: swiperContainer.querySelector('.swiper-button-prev'),
            },
        });
    });
});

I tried this:

var swipers = document.querySelectorAll('.swiper-container');

but nothing happens.

Messages are not ordering correctly in Firebase(JS, HTML)

I created firebase website using JS and frontend

Eveything works correctly expect this one thing. My chats are not ordering by date correctly
This is what i see now:
Anastasia: Hello! (9/17/2024, 10:46:47 PM)
Anastasia: How are you? (9/17/2024, 10:47:06 PM)
Anastasia: Hallo (9/17/2024, 11:41:27 PM)
User2: Yep (9/17/2024, 10:49:16 PM)
User2: Good, thanks ! (9/17/2024, 10:47:23 PM)
User2: Hey (9/17/2024, 10:46:55 PM)
What I want to see:
User2: Hey (9/17/2024, 10:46:55 PM)
Anastasia: Hello! (9/17/2024, 10:46:47 PM)
Anastasia: How are you? (9/17/2024, 10:47:06 PM)
User2: Good, thanks ! (9/17/2024, 10:47:23 PM)
User2: Yep (9/17/2024, 10:49:16 PM)
Anastasia: Hallo (9/17/2024, 11:41:27 PM)

My code

document.addEventListener("DOMContentLoaded", () => {
  firebase.auth().onAuthStateChanged((user) => {
    if (user) {
      const chatId = new URLSearchParams(window.location.search).get("chatId");
      if (!chatId) {
        console.error("Invalid or missing chatId in URL.");
        return;
      }

      // Retrieve messages ordered by timestamp
      const messagesRefForDisplay = firebase
        .database()
        .ref(`chats/${chatId}/messages`)
        .orderByChild("timestamp");
      // Use a regular reference for sending messages
      const messagesRefForSending = firebase
        .database()
        .ref(`chats/${chatId}/messages`);

      // Function to get username from user ID
      function getUsername(userId, callback) {
        const userRef = firebase.database().ref(`users/${userId}`);
        userRef.once("value", (snapshot) => {
          const userData = snapshot.val();
          callback(userData.username);
        });
      }
      function formatTimestamp(timestamp) {
        const date = new Date(timestamp);
        return date.toLocaleString(); // Customize the format if needed
      }

      // Load messages ordered by timestamp
      messagesRefForDisplay.on("child_added", (snapshot) => {
        const message = snapshot.val();
        getUsername(message.senderId, (username) => {
          const messageElement = document.createElement("div");
          messageElement.classList.add("message");
          const formattedTimestamp = formatTimestamp(message.timestamp);

          messageElement.innerHTML = `<span class="sender">${username}:</span> ${message.message} <span class="timestamp">(${formattedTimestamp})</span>`;
          document.getElementById("messages").appendChild(messageElement);

          // Auto scroll to the bottom after a new message is added
          document.getElementById("messages").scrollTop =
            document.getElementById("messages").scrollHeight;
        });
      });

      // Send message
      document.getElementById("sendMessage").addEventListener("click", () => {
        const messageInput = document.getElementById("messageInput");
        const messageText = messageInput.value.trim();
        if (messageText) {
          // Use the unfiltered messagesRef for sending
          messagesRefForSending
            .push({
              message: messageText,
              senderId: user.uid, // Use user.uid here
              timestamp: Date.now(),
            })
            .then(() => {
              console.log("Message sent successfully");
            })
            .catch((error) => {
              console.error("Error sending message:", error);
            });
          messageInput.value = ""; // Clear the input
        }
      });
    } else {
      console.log("User is not logged in.");
    }
  });
});

Vue JS change to-be-edited variable depending on parameter passed into function

Hi JS (and general) newbie here,

I’m currently trying to make simple webpage with Vue JS which has clickable content which results in that section expanding to reveal more content.

I did this with a boolean variable “expanded” which gets toggled on-click.

<q-card @click="expand_header()">
<div v-show="expanded">
export default {
  setup() {
    return {
      expanded: ref(false),
    };
  },
}
expand_header: function () {

      this.expanded = !this.expanded;

    },

However, because I am trying to add this functionality to multiple boxes, I wanted to abstract this functionality and pass a paramater when the function is called which will edit the corresponding variable, and I was wondering what the correct syntax would be.

Newbiew instincts told me to pass a number parameter into the function which will edit one of similar variables like so:

@click="expand_header(1)"
@click="expand_header(2)"
<div v-show="expanded1">content<div>
<div v-show="expanded2">content<div>

export default {
  setup() {
    return {
      expanded1: ref(false),
      expanded2: ref(false),
    };
  },
}
expand_header: function (num) {

      this.expanded[num] = !this.expanded[num];

    },

or so:

expand_header: function (num) {

      this.expanded + num = !this.expanded + num;

    },

however this is clearly not the correct syntax.

I was not sure where I could find documentation or guides on JS syntax for this type of problem, so any input or docu recommendation would be greatly appreciated!

Javascript html table get clicked cell value and column(th) ID

i am trying to get a clicked Table Cell value and corresponding Column ID (th.id)
i need in the $msg the following.

  • Clicked Cell Value (easy (e.target.innerHTML)
  • Get the cellIndex from the cell (td) (easy e.target.cellIndex)
  • corresponding column (th) ID for the same e.target.cellIndex
    *** when i comment the foreach the code work.
    the foreach apparently not working
    Please help
    function onTableCellClicked(e){
     //  alert('table cell clicked value ='+e.target.innerHTML);
       if(e.target.innerHTML && window.chrome.webview){
        $ind=e.target.cellIndex
        $Msg=e.target.innerHTML
       var TTH = document.getElementById('NGTable1 th');
       TTH.forEach(function(th) {
         if (th.cellIndex==$ind){$Msg=$Msg+'|'+th.id}
        })
       window.chrome.webview.postMessage($Msg);
     }  
   }

How to Remove Hash from index.js and index.runtime.js in Parcel with parcel-namer-hashless?

I’m working on a TypeScript project where I’m using Parcel v2.x for bundling, and I want to remove the hash from the output filenames (particularly from index.js and index.runtime.js).

I’ve been using the parcel-namer-hashless plugin, and while it successfully removes the hash from most of my files (like favicon.ico, esp32.js, etc.), I’m still encountering issues with the index.js and index.runtime.js files. They continue to have a hash in their filenames, despite my efforts to configure the plugin to remove them.

Here’s what I’ve tried so far:

Configured parcel-namer-hashless in package.json:

{
  "name": "typescript",
  "version": "1.0.0",
  "description": "This an example of using esptool-js with parcel and typescript",
  "source": "src/index.html",
  "scripts": {
    "genDocs": "cd ../.. && npm run genDocs && mkdir -p examples/typescript/dist && cp -r docs examples/typescript/dist && cd examples/typescript",
    "dev": "npm run clean && npm run genDocs && parcel src/index.html",
    "build": "npm run clean && npm run genDocs && parcel build src/index.html --no-optimize --public-url ./",
    "clean": "rimraf dist .parcel-cache",
    "test": "echo "Error: no test specified" && exit 1",
    "postbuild": "mv dist/index.runtime.*.js dist/index.runtime.js"
  },
  "parcelIgnore": [
    "./docs/.+"
  ],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "parcel": "^2.8.3",
    "parcel-namer-hashless": "^1.0.6",
    "parcel-resolver-ignore": "^2.1.5",
    "rimraf": "^4.1.2",
    "typescript": "^4.9.4",
    "web-serial-polyfill": "^1.0.15"
  },
  "parcel-namer-hashless": {
    "include": [
      ".js$",           
      ".ico$"           
    ]
  }
}

Configured the .parcelrc file:

{
  "extends": "@parcel/config-default",
  "resolvers": [
    "parcel-resolver-ignore",
    "..."
  ],
  "namers": [
    "parcel-namer-hashless"
  ]
}

Cleared the Parcel cache and rebuilt multiple times.

Despite these efforts, index.runtime.js still havs hashes appended to them. The build output looks like this:

dist/index.runtime.298534a0.js

All other files are correctly renamed without hashes.

I also tried adding a post-build script to manually rename the files, but I’d prefer to have a cleaner solution within Parcel if possible.
My Questions:

How can I ensure that index.runtime.js are generated without hashes using Parcel and parcel-namer-hashless?
Is there a better way to configure Parcel or the parcel-namer-hashless plugin to handle runtime files?
Is there a specific reason why Parcel insists on adding a hash to runtime files, and how can this behavior be overridden?

Any advice or suggestions would be greatly appreciated. Thanks in advance!

I also tried it with a custom-namer.js with the same output:

const { Namer } = require('@parcel/plugin');

module.exports = new Namer({
  async name({ bundle }) {
    const entryAsset = bundle.getMainEntry();

    // Handle the main HTML or JS entry point (index)
    if (entryAsset && entryAsset.filePath.includes('index')) {
      // Check if it's a runtime file (Parcel auto-generates runtime bundles)
      if (bundle.type === 'js' && !bundle.isInline && bundle.needsStableName && bundle.isSplittable === false) {
        // Ensure the runtime script is named without a hash
        return `index.runtime.js`;
      }
      
      // For regular 'index.js' or 'index.html'
      return `index.${bundle.type}`;
    }

    // For all other entry points, use the original file name without hash
    if (entryAsset) {
      const originalName = entryAsset.filePath.split('/').pop().split('.')[0]; // Get original name without extension
      return `${originalName}.${bundle.type}`;
    }

    // Fallback for other dynamically generated chunks or assets
    const id = bundle.id.slice(0, 8); // Shorten bundle ID to 8 characters for uniqueness
    return `bundle-${id}.${bundle.type}`;
  }
});

How can I modify my multi-item carousel to slightly show the next item? (Bootstrap 5)

I have a multi-item carousel in Bootstrap 5.
Four items are visible on screen, and the slide allows to move forward one item at a time.

What I would like to do is to show a bit of the next item on screen (about 10% of it). So the user can see what’s coming. That is, without ceasing to have the four main items centered on screen.

I have seen examples of carousels with one item per slide that can do this. But I haven’t been able to make it with a multi-item carousel.

This is an example of what I have: https://codepen.io/Leticia-Techera/pen/KKjjoGB

let items = document.querySelectorAll('.carousel .carousel-item')

items.forEach((el) => {
    const minPerSlide = 4
    let next = el.nextElementSibling
    for (var i=1; i<minPerSlide; i++) {
        if (!next) {
            // wrap carousel by using first child
            next = items[0]
        }
        let cloneChild = next.cloneNode(true)
        el.appendChild(cloneChild.children[0])
        next = next.nextElementSibling
    }
})
.carousel-control-next, .carousel-control-prev {
    position: unset;
    width: 5%;
}
.buttons-container{
    display: flex;
}
.carousel-control-prev-icon, .carousel-control-next-icon{
    background-color:black;
}

@media (max-width: 767px) {
    .carousel-inner .carousel-item>div {
        display: none;
    }

    .carousel-inner .carousel-item>div:first-child {
        display: block;
    }
}

.carousel-inner .carousel-item.active,
.carousel-inner .carousel-item-next,
.carousel-inner .carousel-item-prev {
    display: flex;
}

/* medium and up screens */
@media (min-width: 768px) {

    .carousel-inner .carousel-item-end.active,
    .carousel-inner .carousel-item-next {
        transform: translateX(25%);
    }

    .carousel-inner .carousel-item-start.active,
    .carousel-inner .carousel-item-prev {
        transform: translateX(-25%);
    }
}

.carousel-inner .carousel-item-end,
.carousel-inner .carousel-item-start {
    transform: translateX(0);
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container text-center my-3">
    <div class="row mx-auto my-auto justify-content-center">
        <div id="recipeCarousel" class="carousel slide" data-bs-ride="carousel">
            <div class="carousel-inner" role="listbox">
                <div class="carousel-item active">
                    <div class="col-md-3">
                        <div class="card ratio ratio-1x1 bg-primary">
                        </div>
                    </div>
                </div>
                <div class="carousel-item">
                    <div class="col-md-3">
                        <div class="card ratio ratio-1x1 bg-secondary">
                        </div>
                    </div>
                </div>
                <div class="carousel-item">
                    <div class="col-md-3">
                        <div class="card ratio ratio-1x1 bg-success">
                        </div>
                    </div>
                </div>
                <div class="carousel-item">
                    <div class="col-md-3">
                        <div class="card ratio ratio-1x1 bg-danger">
                        </div>
                    </div>
                </div>
                <div class="carousel-item">
                    <div class="col-md-3">
                        <div class="card ratio ratio-1x1 bg-warning">
                        </div>
                    </div>
                </div>
                <div class="carousel-item">
                    <div class="col-md-3">
                        <div class="card ratio ratio-1x1 bg-info">
                        </div>
                    </div>
                </div>
            </div>
            <div class="buttons-container">
                <a class="carousel-control-prev bg-blue w-aut" href="#recipeCarousel" role="button" data-bs-slide="prev">
                    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                </a>
                <a class="carousel-control-next bg-blue w-aut" href="#recipeCarousel" role="button" data-bs-slide="next">
                    <span class="carousel-control-next-icon" aria-hidden="true"></span>
                </a>
            </div>
        </div>
    </div>
</div>

Is there a way to modify it to achieve what I want?
Thanks!!

CORS error while trying to run an AWS lambda function

I’m trying to run a lambda function from my front-end website but I keep getting a CORS error.

The front-end code that should contact the lambda function is the following:

    const handleSubmit = async (e) => {
        e.preventDefault();
        setIsSubmitting(true);
        setSubmitMessage('');

        try {
            const response = await fetch('https://foobar.lambda-url.eu-west-2.on.aws/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(formData),
            });

            if (response.ok) {
                setSubmitMessage('Your request has been submitted successfully!');
                setFormData({
                    name: '',
                });
            } else {
                throw new Error('Form submission failed');
            }
        } catch (error) {
            console.error('Error:', error);
            setSubmitMessage('An error occurred. Please try again later.');
        } finally {
            setIsSubmitting(false);
        }
    };

The error is the following:

Access to fetch at 'https://foobar.lambda-url.eu-west-2.on.aws/' from origin 'https://my-website.amplifyapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.Understand this error
index.js:29 
        
POST https://foobar.lambda-url.eu-west-2.on.aws/ net::ERR_FAILED

index.js:50 Error: TypeError: Failed to fetch
    at index.js:29:36

CORS are active on AWS. The thing that I find strange is that the request on the chrome network tab display “Provisional Header are shown”:

enter image description here

And if I use the same parameter but using the terminal and curl the call goes through without any problem, for example:

curl -X POST 'https://foobar.lambda-url.eu-west-2.on.aws/' 
-H 'Content-Type: application/json' 
-d '{"name":"test test"}'

Here’s the lambda function:

import { SES } from "@aws-sdk/client-ses";
const ses = new SES({ region: 'eu-west-2' });

export async function handler(event) {
  if (event.httpMethod === "OPTIONS") {
    return {
      statusCode: 200,
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "Content-Type",
        "Access-Control-Allow-Methods": "POST, OPTIONS",
      },
      body: JSON.stringify({ message: "Preflight check successful" }),
    };
  }

  let formData;

  if (event.body) {
    try {
      formData = JSON.parse(event.body);
    } catch (error) {
      console.error("Error parsing event body:", error);
      return {
        statusCode: 400,
        headers: {
          "Access-Control-Allow-Origin": "*",
        },
        body: JSON.stringify({ message: "Invalid JSON" }),
      };
    }
  } else {
    return {
      statusCode: 400,
      headers: {
        "Access-Control-Allow-Origin": "*",
      },
      body: JSON.stringify({ message: "No body provided" }),
    };
  }

  const params = {
    Destination: { ToAddresses: ["my-email-address"] },
    Message: {
      Body: { Text: { Data: JSON.stringify(formData, null, 2) } },
      Subject: { Data: "form info" },
    },
    Source: "some-user",
  };

  try {
    await ses.sendEmail(params);

    return {
      statusCode: 200,
      body: JSON.stringify({ message: "Email sent successfully" }),
    };
  } catch (error) {
    console.error(error);
  } finally {
    console.log("finished");
  }
}

What am I missing?

Prevent window.close after redirect to a custom protocol URL

I need to redirect a page to an URL, using a custom protocol, to open a local application. After the redirection is done and the application is called, the page needs to be closed using window.close() function.

If the protocol of the redirection is not recognized, nor the user explicitly allowed this protocol, an warning popup is presented by the browser (not my code), informing the not recognized protocol and asking the user to confirm the opening of the application.

enter image description here

The user also have the option of click in “always allow” (the explicity consent) to prevent the warning popup be presented in the next time.

My original code is this:

<html>

<head>
    <script src="https://code.jquery.com/jquery-3.7.1.slim.js"
        integrity="sha256-UgvvN8vBkgO0luPSUl2s8TIlOSYRoGFAX4jlCIm9Adc=" crossorigin="anonymous"></script>
</head>

<script>
    $(document).ready(function () {
        window.location = "custom_app_protocol://commands/goto?some_parms";
        window.close();
    });
</script>
<body>
    Redir test.
</body>
</html>

This code above works fine if the warning popup is not presented (protocol recognized or explicit consent already given). Then, the application is called and the page is closed.

But, if the warning popup is presented, the page is closed without perform the app call.

An option would be include a timeout after the call:

$(document).ready(function () {
    //window.location = "custom_app_protocol://commands/goto?some_parms";
    window.location = "cherwellclient://commands/goto?rectype%3DDevelopmentRequest%26PublicID%3D1617";
    setTimeout(function () {
        window.close();
    }, (5000));
});

But, if the user doesn’t click in the warning popup before the timeout trigger the page closing command, the page will be closed without open the app.

So, my question is: there is an way to perform the window.close() only after the warning popup be closed?

Average problem in mixing line chart and bar chart

stack bilitz url = https://stackblitz.com/edit/stackblitz-starters-ws9ujj?file=src%2Fapp%2Fperformance-chart%2Fperformance-chart.component.ts

It should be exactly like this image, but when I change the data, it shifts directly and I did it with transformation scale to show it correctly. Otherwise, if you change the data a little, it will immediately get corrupted.

Temporary image made with smooth transform.

I tried to give the width with calculator but I didn’t get any results

retrieving information from a previous chat

Programmers, Engineers!
I am having this issue trying to retrieve data in the same session during chatting with this chat bot

@app.route("/chat", methods=["POST"])
def chat():
    try:
        user_input = request.json.get("message", "")
        session_id = request.json.get("session_id", str(uuid.uuid4()))  # Generate a new session ID if not provided
        user_name = request.json.get("name", "User")  # Extract user name if provided

        # Store or update the user's name in the conversation model
        conversation = Conversation.query.filter_by(session_id=session_id).first()
        if conversation:
            conversation.user_name = user_name
            conversation.user_message = user_input
        else:
          conversation = Conversation(session_id=session_id, user_name=user_name, user_message=user_input, bot_reply="")
            db.session.add(conversation)
        db.session.commit()

        # Retrieve conversation history
        conversations = Conversation.query.filter_by(session_id=session_id).all()
        conversation_history = [c.user_message for c in conversations]

        # Retrieve user name from session
        user_name = session.get("name", "User")

        # Generate response using OpenAI's API with a system message
        app.logger.info("Generating response with ChatGPT...")
        try:
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": f"You are a medical assistant. Your name is {user_name}. Provide accurate medical information and advice. If you are unsure about a medical issue, advise the user to consult a healthcare professional."},
                    {"role": "system", "content": "Conversation history: " + ", ".join(conversation_history)},
                    {"role": "user", "content": user_input}
                ],
                max_tokens=300,
                temperature=0.7
            )
            bot_reply = response['choices'][0]['message']['content'].strip()
            app.logger.info(f"ChatGPT reply: {bot_reply}")
        except Exception as e:
            app.logger.error(f"Error generating response with ChatGPT: {e}")
            bot_reply = "Error: Unable to generate response."

        # Update and store the conversation in the database
        app.logger.info("Updating conversation in database...")
        conversation.bot_reply = bot_reply
        db.session.commit()
        app.logger.info("Conversation updated successfully.")

        return jsonify({"response": bot_reply, "session_id": session_id, "name": user_name})

    except Exception as e:
        app.logger.error(f"Error processing request: {e}")
        return jsonify({"response": "Sorry, there was an error processing your request."})

This is the chat i had with the AI:
Hi there my name is Osama

Hello, Osama! How can I assist you with your medical questions or concerns today?

what is my name

I’m sorry, I don’t have access to your personal information such as your name. How can I assist you today?

Me: Hi there my name is osamah

ChatBot: Hello, Osamah! How can I assist you today?

Me: what is my name

ChatBot: I’m sorry, but I don’t have access to that information. How can I assist you today?

this is my app.js that i spent hours trying to find if id does not run the session correctly:

function App() {
  const [chatHistory, setChatHistory] = useState([]);
  const [message, setMessage] = useState('');
  const [loading, setLoading] = useState(false);
  const [sessionId, setSessionId] = useState('');
  const [userName, setUserName] = useState('');

  // Initialize a new session ID when the component mounts
  useEffect(() => {
    const initSession = async () => {
      try {
        const response = await axios.post('http://localhost:5000/chat', { message: '' });
        setSessionId(response.data.session_id);
        console.log('Session initialized:', response.data);
      } catch (error) {
        console.error('Error initializing session:', error);
      }
    };
    initSession();
  }, []);

  const handleSendMessage = async () => {
    if (message.trim() === '' || !sessionId) return;

    setChatHistory([...chatHistory, { role: 'user', content: message }]);

    try {
      setLoading(true);
      const response = await axios.post('http://localhost:5000/chat', {
        message: message,
        session_id: sessionId,
        name: userName
      });
      console.log('Response from server:', response.data);
      setChatHistory(prev => [
        ...prev,
        { role: 'assistant', content: response.data.response }
      ]);
    } catch (error) {
      console.error('Error fetching data:', error);
      setChatHistory(prev => [
        ...prev,
        { role: 'assistant', content: 'Error: Unable to get a response.' }
      ]);
    } finally {
      setLoading(false);
      setMessage('');
    }
  };

  const handleUserNameChange = (event) => {
    setUserName(event.target.value);
  };

Configuring the Highcharts Library slider (stocks)

I have a stock chart of the Highcharts library. How to adjust the position of the right and left slider in the picture. I need that when I click on the “now” button, the left slider moves to today’s date, and the right one is at a distance from it, for example, 3 hours enter image description here

As I understood in this library, the position of the left slider is dancing from the position of the right one. I implemented moving the left slider for the number of seconds I needed. But it’s dancing from the same right-hand runner…

log in and sign up linked together

I tried to implement a login and signup system where both forms are linked together, allowing users to switch between them easily. I also set up a mock API to simulate backend interactions, but I’m facing several challenges:

  1. Form Switching: I’m having trouble toggling between the login and signup forms smoothly. The UI doesn’t update as expected, and sometimes it loses the user’s input or causes unexpected behavior.
  2. Mock API Handling: I set up a mock API to handle login and signup requests, but I’m not sure if I’m simulating the API responses correctly. I’m facing issues with returning success or error responses, and I’m unsure how to handle these responses properly on the frontend.
  3. Authentication State: Managing the user’s authentication state is proving difficult. I need to ensure that once a user successfully logs in or signs up, they are redirected appropriately, but my current implementation doesn’t handle this well.
  4. Validation and Error Handling: Implementing form validation for both login and signup forms has been challenging. I also need to show relevant error messages when something goes wrong, like invalid input or failed login attempts, but my current error handling is either incomplete or not working as expected.

I’m looking for detailed examples or guidance on how to address these issues effectively.

Execution contexts of exporting modules in call stack

Consider following code:

moduleA.js:

// moduleA.js
export const moduleVarA = "I am from moduleA";
export function greetA() {
    console.log("Hello from moduleA");
}

moduleB.js:

// moduleB.js
import { moduleVarA, greetA } from './moduleA.js';

console.log(moduleVarA); // "I am from moduleA"
greetA(); //"Hello from moduleA"

I want to ask what will be the order of execution contexts of above modules in call stack? I mean will after loading and executing module A its execution context be popped off from call stack OR it will remain there until execution contexts of all importing modules(like moduleB) get finished?

Incorrect Jest Module Name Mapper: Could not locate module

I am using Jest v29.7.0 as well as babel-jest v29.7.0.

This is my jest.config.js file

module.exports = {
    transform: {
        '\.[jt]sx?$': 'babel-jest'
    },
    rootDir: './',
    verbose: true,
    setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
    moduleDirectories: ['node_modules', '<rootDir>/public/js'],
    moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx', 'json', 'node'],
    moduleNameMapper: {
        '^components/(.*)$': '<rootDir>/public/js/components/$1',
    },
    extensionsToTreatAsEsm: ['.jsx'],
    transformIgnorePatterns: ['/node_modules/'],
    testEnvironment: 'jsdom',
    collectCoverage: true,
    coverageDirectory: '<rootDir>/test/output/coverage',
    coverageReporters: ['html', 'text-summary'],
    testTimeout: 10000,
    roots: ['./public/js/components', './test/spec'],
    collectCoverageFrom: ['./public/js/**/*.{js,jsx}']
};

When trying to run one particular test: npm run test-jest -- test/spec/components/UserProfile/Account/Payments.spec.js

Error from Jest

Test suite failed to run

    Configuration error:
    
    Could not locate module components/UserProfile/Account/Payments mapped as:
    /Users/XXXXXXX/repo/public/js/components/$1.
    
    Please check your configuration for these entries:
    {
      "moduleNameMapper": {
        "/^components/(.*)$/": "/Users/XXXXXXX/repo/public/js/components/$1"
      },
      "resolver": undefined
    }

      2 | import { render, screen, fireEvent } from '@testing-library/react';
      3 | import '@testing-library/jest-dom';
    > 4 | import Payments from 'components/UserProfile/Account/Payments';
        | ^
      5 |
      6 | // Mock implementations
      7 | const mockGetState = jest.fn();

      at createNoMappedModuleFoundError (node_modules/jest-resolve/build/resolver.js:759:17)
      at Object.require (test/spec/components/UserProfile/Account/Payments.spec.js:4:1)
          at runMicrotasks (<anonymous>)

In my project I don’t use extensions when importing, for example I use import Payments from 'components/UserProfile/Account/Payments'; without having to use .jsx and my Webpack config understands this.

But I am new to Jest and don’t know how to get it to understand the imports without extensions when using them in tests.

My Simple failing test

import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
import Payments from 'components/UserProfile/Account/Payments';

describe('Payments Component', () => {
    beforeEach(() => {
        jest.clearAllMocks();
    });

    it('renders without crashing', () => {
        render(<Payments />);
    });
});

babel.config.js

module.exports = {
    presets: ['@babel/preset-env', '@babel/preset-react']
};

jest.setup.js

import '@testing-library/jest-dom';

What am I missing?

Loading form data in modal window

I have a webpage, I’m building in vb.net. The page lists worship locations for parishes. At the bottom of the list is a link to add a new location. When the link is clicked, a modal window appears containing a form. The form is completed and submitted to a separate page for processing. Upon return, the new location is on the list.

Next to each location is a link, “Edit”. I want to load the location information into the modal window so the user can make changes and submit them to a processing page.

In order to get the modal window to open I use:

<a href="#AddWS"" class="texttrigger" data-toggle="modal">Add Worship Site</a>

I want to have the edit link call a piece of javascript in order to place the location info into a hidden form at the bottom of the page and submit with action=”thispage.aspx#editWS”. The URL in the address bar upon submission is correct but the modal window does not display.

<a href=""javascript:editWS(185)"" >Edit</a>

function editWS(LID) {
    
    if (LID == 185) {
       
        document.editLocation.ID.value = 185;
        document.editLocation.address.value = "123 Anywhere St.";
        document.editLocation.city.value = "clairmont";
        document.editLocation.state.value = "NY";
        document.editLocation.zip.value = "11111";
        document.editLocation.phone.value = "(012) 888-1682";
        document.editLocation.county.value = "8";
        document.editLocation.vicariate_ID.value = "4";
        document.editLocation.SeatingCapacity.value = "200";
        document.editLocation.submit();
    }
    
    
    if (LID == 220) {
       
        document.editLocation.ID.value = 220;
        document.editLocation.address.value = "6 Main St.";
        document.editLocation.city.value = "cloverfield";
        document.editLocation.state.value = "NY";
        document.editLocation.zip.value = "22222";
        document.editLocation.phone.value = "(333) 622-3191";
        document.editLocation.county.value = "6";
        document.editLocation.vicariate_ID.value = "4";
        document.editLocation.SeatingCapacity.value = "";
        document.editLocation.submit();
    }     
}  

<form name="editLocation" action="thispage.aspx#editWS" method="post">
<input type="hidden" name="ID" value="" />
<input type="hidden" name="address" value="" />
<input type="hidden" name="city" value="" />
<input type="hidden" name="state" value="" />
<input type="hidden" name="zip" value="" />
<input type="hidden" name="phone" value="" />
<input type="hidden" name="county" value="" />
<input type="hidden" name="vicariate_ID" value="" />
<input type="hidden" name="SeatingCapacity" value="" />
</form>

In the modal window, I plan to load the data from the form object.The user can then update the info and submit it to a processing page.