Subtitles aren’t being burnt into the video | embedding srt into video frames

Describe the bug

I’m trying to burn a subtitles.srt file onto the video (having the subtitle embeded within the frames themselves)

To Reproduce

both `input.mp4` and `subtitles.srt` are available to the WASM FFMPEG FS
const converted = await ffmpegRef.current.exec([
    '-i', "input.mp4", // Input File
    '-i', 'subtitles.srt',  // Burn subtitles into video
    '-vf', 'subtitles=subtitles.srt',  // Burn subtitles into video
    "output.mp4" // Output File
]);

Expected behavior

The Subtitles should be burned into the video.

Desktop:

  • OS: Windows 10
  • Browser Chrome
  • Version 122.0.6261.94 (Official Build) (64-bit) (cohort: M122 Rollout)

Additional context

Example extract from the subtitles.srt file

1
00:00:00,280 --> 00:00:01,379
Hi,

2
00:00:01,379 --> 00:00:01,679
and

3
00:00:01,679 --> 00:00:01,980
welcome

4
00:00:01,980 --> 00:00:02,200
to

5
00:00:02,200 --> 00:00:03,220
ClipDrop.

6
00:00:03,799 --> 00:00:03,919
Congratulations

7
00:00:03,919 --> 00:00:04,400
on

8
00:00:04,400 --> 00:00:04,719
being

9
00:00:04,719 --> 00:00:05,040
selected

10
00:00:05,040 --> 00:00:05,259
to

11
00:00:05,259 --> 00:00:05,480
do

Deploy to Vercel

I have a next.js projekt that works perfectly in the development mode. But wenn i want to deploy it to vercel i get the Errors: “Compiler server unexpectedly exited with code: null and signal: SIGKILL
” and “ReferenceError: location is not defined”.
Vercel Deploy Console

"use client";
import { useAuthState } from "react-firebase-hooks/auth";
import { useEffect, useState } from "react";
import React from "react";
import { auth } from "@/app/firebase/config";
import { useRouter } from "next/navigation";
import { signOut } from "firebase/auth";
import updateGitHubRepository from "@/app/api/updateRepo.mjs";
import updateImage from "./api/updateImage.mjs";
import { ToastContainer, toast, Bounce } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

export default function Home() {
  const [user] = useAuthState(auth);
  const [userSession, setUserSession] = useState(null);
  const [displayName, setDisplayName] = useState("");
  const [role, setRole] = useState("");
  const [bioDE, setBioDE] = useState("");
  const [bioEN, setBioEN] = useState("");
  const [avatar, setAvatar] = useState("");
  const [index, setIndex] = useState("");
  const [file, setFile] = useState("");
  const router = useRouter(); // Move the useRouter hook inside useEffect

  // Load user session from sessionStorage when component mounts
  useEffect(() => {
    const sessionUser = sessionStorage.getItem("user");
    setUserSession(sessionUser);
  }, []);

  // Load GitHub file when user.displayName changes
  useEffect(() => {
    const loadGitHubFile = async () => {
      const fileUrl =
        "RAW MEMBER JSON FILE";
      try {
        const response = await fetch(fileUrl);
        if (!response.ok) {
          throw new Error(
            `Fehler beim Abrufen der Datei. Status: ${response.status}`
          );
        }
        const fileContent = await response.json();
        const members = fileContent.members;
        const index = members.findIndex((item) => item.id === user.index);
        const gitDisplayName = members[index].name;
        const gitRole = members[index].description;
        const gitBioDE = members[index].biographie.de;
        const gitBioEN = members[index].biographie.en;
        const gitImg = members[index].img;
        if (index !== -1) {
          setDisplayName(gitDisplayName || "");
          setRole(gitRole || "");
          setBioDE(gitBioDE || "");
          setBioEN(gitBioEN || "");
          setIndex(index || "");
          const inputPath = gitImg;
          const baseUrl = "https://www.DOMAIN.de/";

          // Verwenden Sie die URL-Klasse, um den vollständigen Pfad zu erstellen
          const fullPath = inputPath.replace("../", baseUrl);
          setAvatar(fullPath);
        }
        return { gitDisplayName, gitRole, gitBioDE, gitBioEN, gitImg, index };
      } catch (error) {
        console.error(
          "Fehler beim Laden der Datei von der URL:",
          error.message
        );
      }
    };
    if (user && user.displayName) {
      loadGitHubFile();
    }
  }, [user, router]); // Include router as a dependency
  const handleFileUpload = async (event) => {
    const file = event.target.files[0];
    console.log(file);
    const url = URL.createObjectURL(file);
    setAvatar(url);
    setFile(file);
    // Hier können Sie den Dateiupload-Code hinzufügen
  };
  const handleUploadtoGithub = async (index, fields, img) => {
    // Hier können Sie den Dateiupload-Code hinzufügen
    try {
      let link = avatar;
      if (file) {
        const uploadFile = file;
        const newFileNameWithoutExtension = "avatar"; 

        const extension = uploadFile.type.split("/")[1];
        const newFileName = `${newFileNameWithoutExtension}.${extension}`;

        const newFile = new File([uploadFile], newFileName, {
          type: uploadFile.type,
        });
        link = await updateImage(newFile);
        console.log(link);
      }
      const build = {
        id: index + 1,
        name: fields.name,
        description: fields.role,
        img: link || "",
        biographie: {
          de: fields.biographie.de,
          en: fields.biographie.en,
        },
      };

      await updateGitHubRepository(
        "USERNAME",
        "REPOSITORY",
        "BRANCH",
        "FILE",
        `members.${index}`,
        build,
        process.env.NEXT_PUBLIC_GITHUB_API_KEY
      );
      toast.success("Erfolgreich Hochgeladen!");
    } catch (error) {
      toast.error("Fehler beim Hochladen!");
      console.error("Fehler beim Laden der Datei von der URL:", error.message);
    }
  };
  return (
//HTML
  );
}

I tried serveral methods to solve the problem but nothing worked out.

Getting Error: page.goto: Test ended. in playwright

I am trying to create a function like this in playwright. By the way, I am new to playwright.

import { expect } from "@playwright/test";
import { EnvCredentials } from "../helpers/getEnvCredentials";

export class PW {
    static async visit(page, routeName) {
       await page.goto(EnvCredentials.getCredsValue("BASE_URL") + routeName);
    }
}

That visit() method above is being called in this function

static async uiLogin(username, password, page) {
   const loginPage = new LoginPage(page);

   PW.visit(page, route_root_page);
   await loginPage.enterUsername(username);
   await loginPage.enterPassword(password);
   await loginPage.clickLoginBtn();
}

Upon running, I am getting this error

Error: page.goto: Test ended.
Call log:

  • navigating to “https://latest.frankiefinancial.io/”, waiting until “load”
    at portalhelpersplaywrightMethods.ts:6
    4 | export class PW {
    5 | static async visit(page, routeName) {
    6 | await page.goto(EnvCredentials.getCredsValue(“BASE_URL”) + routeName);
    | ^
    7 | }
    8 |

enter image description here

On click function is not working in script though models and views are ok and original template is working perfectly

In product_detail.html:

{% extends 'partials/base.html'%}


{%load static%}

{% block content %}
    <style>
            /* Basic Styling */
      html, body {
        height: 100%;
        width: 100%;
        margin: 0;
        font-family: 'Roboto', sans-serif;
      }

      .containerbox {
        max-width: 1200px;
        margin: 0 auto;
        padding: 15px;
        display: flex;
      }

      /* Columns */
      .left-column {
        width: 65%;
        position: relative;
      }

      .right-column {
        width: 35%;
        margin-top: 60px;
      }


      /* Left Column */
      .left-column img {
        width: 70%;
        position: absolute;
        left: 0;
        top: 0;
        opacity: 0;
        transition: all 0.3s ease;
      }

      .left-column img.active {
        opacity: 1;
      }


      /* Right Column */

      /* Product Description */
      .product-description {
        border-bottom: 1px solid #E1E8EE;
        margin-bottom: 20px;
      }
      .product-description span {
        font-size: 12px;
        color: #358ED7;
        letter-spacing: 1px;
        text-transform: uppercase;
        text-decoration: none;
      }
      .product-description h1 {
        font-weight: 300;
        font-size: 52px;
        color: #43484D;
        letter-spacing: -2px;
      }
      .product-description p {
        font-size: 16px;
        font-weight: 300;
        color: #86939E;
        line-height: 24px;
      }

      /* Product Configuration */
      .product-color span,
      .cable-config span {
        font-size: 14px;
        font-weight: 400;
        color: #86939E;
        margin-bottom: 20px;
        display: inline-block;
      }

      /* Product Color */
      .product-color {
        margin-bottom: 30px;
      }

      .color-choose div {
        display: inline-block;
      }

      .color-choose input[type="radio"] {
        display: none;
      }

      .color-choose input[type="radio"] + label span {
        display: inline-block;
        width: 40px;
        height: 40px;
        margin: -1px 4px 0 0;
        vertical-align: middle;
        cursor: pointer;
        border-radius: 50%;
      }

      .color-choose input[type="radio"] + label span {
        border: 2px solid #FFFFFF;
        box-shadow: 0 1px 3px 0 rgba(0,0,0,0.33);
      }

      .color-choose input[type="radio"]#red + label span {
        background-color: #C91524;
      }
      .color-choose input[type="radio"]#blue + label span {
        background-color: #314780;
      }
      .color-choose input[type="radio"]#black + label span {
        background-color: #323232;
      }

      .color-choose input[type="radio"]:checked + label span {
        background-image: url(images/check-icn.svg);
        background-repeat: no-repeat;
        background-position: center;
      }

      /* Cable Configuration */
      .size-choose {
        margin-bottom: 20px;
      }

      .size-choose button {
        border: 2px solid #E1E8EE;
        border-radius: 6px;
        padding: 13px 20px;
        font-size: 14px;
        color: #5E6977;
        background-color: #fff;
        cursor: pointer;
        transition: all .5s;
      }

      .size-choose button:hover,
      .size-choose button:active,
      .size-choose button:focus {
        border: 2px solid #86939E;
        outline: none;
      }

      .size-config {
        border-bottom: 1px solid #E1E8EE;
        margin-bottom: 20px;
      }

      .size-config a {
        color: #358ED7;
        text-decoration: none;
        font-size: 12px;
        position: relative;
        margin: 10px 0;
        display: inline-block;
      }
      .size-config a:before {
        content: "?";
        height: 15px;
        width: 15px;
        border-radius: 50%;
        border: 2px solid rgba(53, 142, 215, 0.5);
        display: inline-block;
        text-align: center;
        line-height: 16px;
        opacity: 0.5;
        margin-right: 5px;
      }

      /* Product Price */
      /*.product-price {
        display: flex;
        align-items: center;
      }

      .product-price span {
        font-size: 26px;
        font-weight: 300;
        color: #43474D;
        margin-right: 20px;
      }*/

      .cart-btn {
        display: inline-block;
        background-color: #FFB6C1;
        border-radius: 6px;
        font-size: 16px;
        color: #FFFFFF;
        text-decoration: none;
        padding: 12px 30px;
        transition: all .5s;
      }
      .cart-btn:hover {
        background-color:  #ff0000;
      }
      .buynow-btn {
        display: inline-block;
        background-color: #FFB6C1;
        border-radius: 6px;
        font-size: 16px;
        color: #FFFFFF;
        text-decoration: none;
        padding: 12px 30px;
        transition: all .5s;
      }
      .buynow-btn:hover {
        background-color:  #ff0000;
      }

      /* Responsive */
      @media (max-width: 940px) {
        .container {
          flex-direction: column;
          margin-top: 60px;
        }

        .left-column,
        .right-column {
          width: 100%;
        }

        .left-column img {
          width: 300px;
          right: 0;
          top: -65px;
          left: initial;
        }
      }

      @media (max-width: 535px) {
        .left-column img {
          width: 220px;
          top: -85px;
        }
      }
        .product-price {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            text-align: center;
        }

        .price {
            font-size: 24px;
            font-weight: bold;
            color: #333; /* Price color */
            margin-bottom: 5px;
        }

        del {
            color: #999; /* Old price color */
            font-size: 18px;
        }


    </style>
    <meta name="robots" content="noindex,follow" />

  </head>

  <body>
    <main class="containerbox">

      <!-- Left Column / Headphones Image -->
      <div class="left-column">
        {%  for p in p_image  %}
        <img data-image="black" src="{{  p.images.url  }}" alt="Hi1">
        {%  endfor  %}
        <!-- {%  for q in p_image  %}
        <img data-image="blue" src="{{  q.images.url  }}" alt="Hi2">
        {%  endfor  %} -->
        <img data-image="red" class="active" src="{{p.image.url}}" alt="Hi">
        <!-- <p class="showcase-badge">{{p.get_percentage|floatformat:0}}% off</p> -->
      </div>


      <!-- Right Column -->
      <div class="right-column">

        <!-- Product Description -->
        <div class="product-description">
          <span>{{p.vendor}}</span>
          <h1>{{p.title}}</h1>
          <p>{{p.description}}</p>
        </div>

        <!-- Product Configuration -->
        <div class="product-configuration">

          <!-- Product Color -->
          <div class="product-color">
            <span>Color</span>

            <div class="color-choose">
                {% for c in colors %}
              <div>
                <input data-image="{{c.code}}" type="radio" id="{{c.code}}" name="color" value="{{c.code}}" checked>
                <label for="red"><span></span></label>
              </div>
              {% endfor %}
              <!-- <div>
                <input data-image="blue" type="radio" id="blue" name="color" value="blue">
                <label for="blue"><span></span></label>
              </div>
              <div>
                <input data-image="black" type="radio" id="black" name="color" value="black">
                <label for="black"><span></span></label>
              </div> -->
            </div>

          </div>

          <!-- Cable Configuration -->
          <div class="size-config">
            {% for s in sizes %}
            <span>Sizes</span>

            <div class="size-choose">
              <button>{{s.name}}</button>
            </div>
            {% endfor %}

            <a href="#">How to configurate your headphones</a>
          </div>
        </div>

        <!-- Product Pricing -->
        <div class="product-price">
          <p class="price">New Price: {{p.price}} </p>

          <del>Old Price: {{p.old_price}}</del>
        </div>
          <a href="#" class="cart-btn">Add to cart</a>
          <a href="#" class="buynow-btn">Buy Now</a>
        <!-- </div> -->
      </div>
    </main>

    <!-- Scripts -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js" charset="utf-8"></script>
    <script>
            $(document).ready(function() {

      $('.color-choose input').on('click', function() {
          var productColor = $(this).attr('data-image');

          $('.active').removeClass('active');
          $('.left-column img[data-image = ' + productColor + ']').addClass('active');
          $(this).addClass('active');
      });

      });

    </script>
  </body>
{% endblock content %}

I created this product-details html page Where I created checkbox(radio) but when I am clicking on the checkboxes it is not working
In the original template all the things are working perfectly. My views and model also are working perfectly.

To see my problem in detail please visit the link:

https://youtu.be/SAfs2UepWqc

you can see in the video that when I add a new color in products it is working(I mean previously in page page there are four colors after adding one there is five colors) but when I am clicking on the colors it is not changing the images.

Though I uploaded more than one image you can see In the below video by visiting the link:

https://youtu.be/BtRq0XeijmY

I have also an another question that it is possible that in css

.color-choose input[type="radio"]#red + label span {
        background-color: #C91524;
      }

instade of #red if i can put the colors which I created in admin pannel

Scroll right and left on click NextJs

I am using NextJs and i am trying to scroll horizontally using on button click. below my code

this is the page where i want to scroll the products menu horizontally.

"use client";
import React, { useRef } from "react";
import { PRODUCTS } from "@/data/products";
import ProductCard from "../components/ProductCard/page";
import BrandCard from "../components/BrandCard/page";
import { GrNext, GrPrevious } from "react-icons/gr";
const Index = () => {
  const slideRef = useRef();

  const onNext = () => {
    slideRef.current.scrollLeft += 200;
  };
  const onPrev = () => {
    slideRef.current.scrollLeft += 200;
  };
  return (
    <div className="flex m-auto rounded-md flex-col">
      <div className="flex flex-col w-full items-center bg-red-50">
        <div>
          <h2 className="mb-4 font-bold text-2xl text-slate-400">
            Latest Products
          </h2>
          <div className="flex gap-4">
            <button onClick={onPrev}>
              <GrPrevious />
            </button>
            <button onClick={onNext}>
              <GrNext />
            </button>
          </div>
        </div>
        <div
          className=" flex gap-5 overflow-scroll scrollbar-none scroll-smooth transition-all"
          ref={slideRef}
        >
          {PRODUCTS &&
            PRODUCTS.map((item) => (
              <ProductCard
                id={item.id}
                imageUrl={item.imageUrl}
                price={item.price}
                description={item.description}
              />
            ))}
        </div>
        <div>
          <BrandCard />
        </div>
      </div>
    </div>
  );
};

export default Index;

and the is the child component ProductCard

import React from "react";
import { PRODUCTS } from "@/data/products";
import Link from "next/link";
import Image from "next/image";

const ProductCard = () => {
  return (
    <div className="flex items-center justify-center gap-4">
      {PRODUCTS.map((item) => (
        <div className="flex flex-col gap-1">
          <div className=" h-[200px] w-52 bg-white  flex justify-center">
            <Link className="" href={`./productDetails/:${item.id}`}>
              <Image
                src={item.imageUrl}
                // layout="fill"
                // objectFit="cover"
                width={500}
                height={500}
                className="h-full w-full"
              />
            </Link>
          </div>
          <Link href={`./productDetails/:${item.id}`}>
            <p className="bg-white text-center text-accent text-base font-bold">
              {item.price} $
            </p>
            <p className="bg-white text-center text-base font-semibold">
              {item.description}
            </p>
            <button className="bg-accent p-4 w-full rounded-b-lg text-white text-center -text-base font-semibold">
              Add To Cart
            </button>
          </Link>
        </div>
      ))}
    </div>
  );
};

{
  /* <View>
  <View style={styles.cardView}>
    <TouchableOpacity
      onPress={() => {
        navigation.navigate("ProductDetails", {
          itemId: item.id,
          catId: item.categoryId,
          productTitle: item.title,
        });
      }}
      style={styles.imageView}
    >
      <Image style={styles.image} source={{ uri: item.image }} />
    </TouchableOpacity>
    <TouchableOpacity
      onPress={() => {
        navigation.navigate("ProductDetails", {
          itemId: item.id,
          catId: item.categoryId,
          productTitle: item.title,
        });
      }}
      style={styles.priceView}
    >
      <View>
        <Text style={styles.price}> ج.م {item.price}</Text>
      </View>
      <View style={styles.priceView}>
        <Text style={styles.description}>{item.description}</Text>
      </View>
    </TouchableOpacity>
    <TouchableOpacity
      onPress={() => {
        !authUser
          ? setModalVisible(true)
          : dispatch(cartActions.addToCart(item, 1));
      }}
      style={styles.addToCartView}
    >
      <Text style={styles.renderAddToCart}>اضف للسلة</Text>
    </TouchableOpacity>
  </View>
</View>; */
}
export default ProductCard;

I a have searched a lot to check this code, i found that it is working fine in react applications, but not with Nextjs

How can I display error messages in a readable way in the Javascript Console?

I am currently working with Angular JS, and sometimes I get some error messages in the console with content like that :

angular.js:15697  **Error: [$injector:unpr] http://errors.angularjs.org/1.8.2/$injector/unpr?p0=eProvider%20%3C-%20e%20%3C-%20AppyController**
    at angular.js:99:1
    at angular.js:4991:19
    at Object.d [as get] (angular.js:5151:32)
    at angular.js:4996:28
    at d (angular.js:5151:32)
    at e (angular.js:5176:58)
    at Object.invoke (angular.js:5200:18)
    at S.instance (angular.js:11814:24)
    at p (angular.js:10627:33)
    at g (angular.js:9942:13)

Do you know how can I simply display those messages in a human-readable way ?

Thanks in advance,

I try a tutorial where I dragged a file named angular.js or angular.min.js, in the main directory,
but it still did not work …

Flyway-node library throwing the following error: end of central directory record signature not found

I am trying to migrate my sql files using the following code

 const flywayApi = new Flyway(flywayConfig)
    flywayApi.migrate().then(response => {
        if (!response.success) {
            // Handle failure case
            console.log(`Unable to execute migrate command. Error: ${response.error.errorCode}`);
        }
        else {
            console.log('Database migration successful!');
            // Handle response
        }
    }).catch(err => {
        console.log(`Unable to execute migrate command. Error: ${err}`);
    })

config file is the following

    module.exports = function() {
    return {
        flywayArgs: {
            url: 'jdbc:postgresql://localhost:5432/gtjdb',
            schemas: 'public',
            locations: 'filesystem:migration/master',
            user: 'postgres',
            password: 'admin',
            sqlMigrationSuffixes: '.pgsql',
            baselineOnMigrate: true,
            baselineVersion:"0"
        },
        // Use to configure environment variables used by flyway
        env: {
            JAVA_ARGS: '-Djava.util.logging.config.file=./conf/logging.properties',
        },
        version: '6.3.2', // optional, empty or missing will download the latest
        mavenPlugins: [{ // optional, use to add any plugins (ie. logging)
            groupId: 'org.slf4j',
            artifactId: 'slf4j-api',
            version: '1.7.25',
            // This can be a specifc url to download that may be different then the auto generated url.
            downloadUrl: 'https://repo1.maven.org/maven2/org/slf4j/slf4j-api/1.7.25/slf4j-api-1.7.25.jar',
        }, {
            groupId: 'org.slf4j',
            artifactId: 'slf4j-jdk14',
            version: '1.7.25'
        }],
        downloads: {
            storageDirectory: '/var/test', // optional, the specific directory to store the flyway downloaded files. The directory must be writable by the node app process' user.
            expirationTimeInMs: -1, // optional, -1 will never check for updates, defaults to 1 day.
        }
    };
};

folder tree is the following

enter image description here

I can’t figure out the issue here

Timestamp array list covert hours minutes Seconds into setInterval time for each 1 seconds

Hi everyone facing one issue in my react application where I have array of list timestamp's ex:([1651234567, 1651234568, 1651234569]) which I need to convert in to hours minutes & seconds like Ex:([17:46:7, 17:46:8, 17:46:9]) each seconds timer should increase with help of But in my current scenario this logic is not working.

The below code I have defined timestamp state array & also In useEffect I’m calling setInterval time on every 1 second. But below code timer remain constant. Please help on this.

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>

const ConvertTimer = () => {
    const [timestamp, setTimestamp] = useState([1651234567, 1651234568, 1651234569]);
  const [timeLeft, setTimeLeft] = useState([]);

  useEffect(() => {
    const timer = setInterval(() => {
      const newTimeLeft = timestamp.map((timestamp) => {
        const date = new Date(timestamp * 1000);
        const hours = date.getHours();
        const minutes = date.getMinutes();
        const seconds = date.getSeconds();
        return `${hours}:${minutes}:${seconds}`;
      });
      setTimeLeft(newTimeLeft);
    }, 1000);

    return () => clearInterval(timer);

    
  }, [timestamp]);
  return (
    <div>
      <h1>Time Left</h1>
      <ul>
        {timeLeft.map((time) => (
          <li key={time}>{time}</li>
        ))}
      </ul>
    </div>
  )
}

  

Next.js App Router using optional URL params

I am currently working on a project that should support various types of URL parameters. In Next.js, I am using the App Router, so only “next/navigation” is functional for me, not “next/router”.

I aim to construct my URL in the following format:

/Surveys/(shortname)/id/Report

Here, both ‘shortname’ and ‘id’ are variables. However, ‘id’ is always present in the URL, while ‘shortname’ is optional. For instance:

/Surveys/helloworld/123/Report

and

/Surveys/123/Report

Both URLs should direct me to the same page, where I have:

<h1>Survey shortname: helloworld</h1>
<p>ID: 123</p>

Or, when there is no ‘shortname’:

<h1>Survey</h1>
<p>ID: 123</p>

My initial approach was to use the Optional Catch-all Segments provided by Next.js. However, this didn’t work out because [[…shortname]] must be the last part of the URL, and it is crucial for me to have ‘Report’ at the end.

Consequently, I considered working with slugs like [shortname] and [id] as folders. But this didn’t work out either because I couldn’t operate without ‘shortname’.

Next, I tried working with rewrite rules in my next.config.mjs. For example:

/** @type {import('next').NextConfig} */
const nextConfig = {
    async rewrites() {
        return [
            {
                source: '/Surveys/:shortname/:id/Reports',
                destination: '/Surveys/Reports/[...slugs]',
            },
        ];
    },
};

export default nextConfig;

The idea was to trick Next.js into believing that the catch-all is at the end. Unfortunately, this didn’t work out either.

I would appreciate any assistance you can provide. If u can give an example project, with an improved folder-structure and using tsx, I would be very grateful!

Vue.js – I’m getting nowhere very very slowly

Everything appears to be unable to resolve the file paths for Home and App. I have even fed all of my files to AI and had it check. I’ve got nothing.

from main.js in the src folder:

import Home from ‘@views/Home.vue’; // Using alias
import App from ‘@src/App.vue’; // Using alias

from index.js in the router folder:

import Home from ‘@views/Home.vue’;
import App from ‘@src/App.vue’;

App.vue:

<template>
<div id="app">
</div>
</template>

<script>
export default {
name: 'App',
};
</script>

<style>
</style>

Home.vue:

<template>
<div class="flex justify-center items-center h-screen ">
<div class="bg-white p-10 rounded-lg shadow-lg">
<h2 class="text-2xl mb-4">Sign in</h2>
<form class="flex flex-col space-y-4">
<input type="email" placeholder="Email" class="border p-2" />
<button class="bg-blue-500 text-white p-2 rounded">Send Code</button>
</form>
</div>
</div>
</template>
<script>
export default {
name: 'Home',
};
</script>
<style scoped>
</style>

I’ve tried everything I could think of, and everything AI could think of. It’s an empty, brand new project. There’s not much to check.

How to create a MongoDB Array and use it on node.js?

I am creating a Discord Bot, this is a problem I faced when I try to create an Array of data for MongoDB.

I don’t have a bigger knowledge of MongoDB. So actually I don’t know how to work with MongoDB arrays.

CountersSchema.js

const {Schema, model} = require('mongoose');

const countersSchema = new Schema({
    Guild: { type: String, required: true },
    Counters: [
        {
            Names: { type: String, required: true },
            Types: { type: String, required: true },
            Channels: { type: String, required: true }
        }
    ]
});

module.exports = model(`counters`, countersSchema);

I tried to create an array in here. I’m not sure whether this is correct or wrong.

The thing I want to do is, let users create counters for their Discord servers. And I want them to only allow max 5 counters per server. So I created this schema to store that data for each counter they create.

I want this Guild value to be unique. which is the id of the server. And I want Names , Types & Channels to be an arrays of up to 5 values and falls under the Guild value.

Counters.js

const counterChannels = require('../../Schemas/CountersSchema');

const data = async (interaction) => {
    try {
        return await counterChannels.findOne({ Guild: interaction.guild.id });
    } catch (error) {
        console.error('Error while fetching counters:', error);
        return null;
    }
};

const existingCounter = await data(interaction);

if (existingCounter) {
    // Check if the maximum number of counters is reached
    if (existingCounter.Counters.length >= 5) {
       return;
    };

    await counterChannels.updateOne(
    { Guild: guild.id },
    {
        $push: {
        Counters: {
            Names: givenName, // givenName Declaration not included.
            Types: counterType, // counterType Declaration not included.
            Channels: createdCounter.id // createdCounter Declaration not included.
        }
        }
    }
    );

} else {
    await counterChannels.create({
    Guild: guild.id,
    Counters: [{
        Names: givenName,
        Types: counterType,
        Channels: createdCounter.id
    }]
    });
}

This is only a part of the Counters.js file. This is how I tried to find if there are any previous data is available in the db.
And if no data available, I want to create a new entry under the guild id and assign these 3 values to that array.
If previous data available, I only want to assign new values to the array and keep the Guild as it is.

So, I want your help in here to correctly do this. I don’t think I have done this correctly.

There is one more thing. That is how to call the data using the array.

ServerCounters.js

const serverCounters = require('../Schemas/CountersSchema');

async execute (member) {
   const data = await serverCounters.find({Guild: member.guild.id});
   if(!data.length) return;

   const counterType = data.map(doc => doc.Types);
   const counterChannel = data.map(doc => doc.Channels);
   const counterName = data.map(doc => doc.Names);
}

in this code, I want to check is there counter data available for the server. just like the previous Counters.js file. After that, I want to devide the data according to the values of Types. So let’s say if one of the values in Types array is 'Total Members', then I want to get the values of the other two arrays that are included along with the 'Total Members' for Types.

So, this is what I’m looking for the help with.

  • Create 3 arrays with up to 5 different values. Named Types , Names , and Channels under the Guild.
  • Check if there are already 5 values for that 3 arrays under the interacting guild’s id. (in Counters.js)
  • If no data available, create new entry for that guild.
  • If less than 5 values available, insert current data to that 3 arrays also.
  • Find corresponding values of the Names and Channels arrays using values of Types array.

Using new google routes api – how can I render (show) route result to a map?

Using “old” google directions api we had directionsService for encapsulating rest query & directionsRenderer to show results to the map.

Directions API example for javascript:

    // 1. init route config
    let route = {
      origin: {
        ...
      },
      destination: {
        ...
      },
      ...
    }

    // 2. link map to renderer
    this.directionsRenderer.setMap(this.map);

    // 3. make request
    this.directionsService
    .route(direction)
    .then((response) => {
      // 4. render route on map
      this.directionsRenderer.setDirections(response);
    })

As for the new routes api: directionsService can be replaced by raw query code (or nodejs lib), but what about directionsRenderer?
How can I apply response[‘routes’] to the map?

I can’t see any examples in official docs, as well as no client library for JS.

React query not refreshing list results

I have a list query that returns an array of orders, that specifically have a value of acceptedAt: null. I then have a mutation that on click of a button updates the value of acceptedAt to a date.

The mutation invalidates the server key used on the list end point to “refresh” the list, however for some reason the item that i have just updated, remains in the list, but with the acceptedAt set. (obviously its refreshing the values of the list items, but not the list itself.)

Here is the query:

export const useOrderList = <TData = OrderListResponseType,>(
  params: OrderListParametersType,
  options?: ApiV2InfiniteQueryOptions<TData>,
) => {
  const { business } = useSellarCurrentBusiness();
  const { user } = useFirebaseUser();
  console.log({ params });
  return useInfiniteQuery({
    queryKey: [user?.uid, business?.id, ServerStateKeys.Orders, params],
    queryFn: ({ pageParam }) =>
      apiV2Request({
        user,
        business,
        method: "get",
        path: `orders`,
        params: {
          ...params,
          offset: pageParam,
        },
      }).then((data) => apiV2AssertResponse<TData>(data).data),
    ...getDefaultInfiniteQueryOptions({ ...options, limit: params.limit }),
  });
};

and here is the mutation:

export const useOrderAccept = (id: number) => {
  const { business } = useSellarCurrentBusiness();
  const { user } = useFirebaseUser();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: () =>
      apiV2Request({
        user,
        business,
        method: "post",
        path: `orders/v2/${id}/accept`,
      }).then(
        (response) =>
          apiV2AssertResponse(response)
            .data as OrderV2Dto.OrderAcceptResponseType,
      ),
    onSuccess: (response) => {
      queryClient.invalidateQueries({
        queryKey: [user?.uid, business?.id, ServerStateKeys.Orders],
      });
      queryClient.setQueriesData<InfiniteData<OrderListResponseType>>(
        {
          predicate: ({ queryKey }) => {
            return (
              queryKey[0] === user?.uid &&
              queryKey[1] === business?.id &&
              queryKey[2] === ServerStateKeys.Orders &&
              typeof queryKey[3] === "object"
            );
          },
        },
        (data) => {
          if (!data?.pages) return data;
          return {
            ...data,
            pages: data.pages.map((page) =>
              page.map((order) =>
                order.id === response.id ? response : order,
              ),
            ),
          };
        },
      );
    },
  });