Vue 3.2 Select changes subsequent select

I have two selects, material and color1. I want to change options of color1 element when material is changed. Here’s what I have so far:

Script setup:

const data = ref({
    materialType: 'none',
    colors: MyData.MaterialColors['none']
});

const chgMatl = ($event) => {
    data.materialType = $event.target.value
    data.colors = MyData.MaterialColors[data.materialType];
    return data.colors
}

Vue Template:

<FormKit v-model="data.materialType" @change="chgMatl($event)" type="select" name="material" label="Material" validation="required" :options="MyData.Materials"></FormKit>
<FormKit type="select" name="color1" label="Color" validation="required" :options="data.colors"></FormKit>

Sample MyData.MaterialColors:

{
   a: { 1: '1', 2: '2', 3: '3' },
   b: { 1: '1', 2: '2', 3: '3' },
   c: { 1: '1', 2: '2', 3: '3' }
}

When MyData.Materials is changed, it’s value is a. This sets data.materialType = a, which plugs into MyData.MaterialColors[a] and returns { 1: ‘1’, 2: ‘2’, 3: ‘3’ } which then populates the colors element’s :options.

I was able to make this work alternatively by putting MyData.MaterialColors directly into :options. The dependent select element worked as required. However, the HTML element did not like having brackets [] in the :options field so it would not process properly. I could tell because the closing FormKit tag was red and angry. The view worked when Material changed, but model output did not save to the database.

<FormKit type="select" name="color1" label="Color" validation="required" :options="MyData.MaterialColors[data.materialType]"></FormKit>

Is there a way to have data in the options field with brackets, or can this be represented another way that will produce the necessary information? Or is there a way to set the options directly from the chgMatl function, like jQuery $(‘#color1’).val()? I’m open to a solution from any possibility. Thanks!

Discord/node.js regex match, replace string, extract replaced string

Firstly, I’m a total noob to node.js and coding but have been teaching myself so apologies if this is just totally stupid/simple.

The intention is, someone posts a twitter link, the bot takes the message content, replaces twitter.com/x.com with “fxtwitter.com”, extracts the corrected URL and posts it in the channel, replying to the user.

I’ve managed to get this working fine by having the bot send content: twitterReplace but obviously that quotes the whole message, I only want the URL.

So far I have this. I hope you can see what I’m trying to do here. I’m not even sure if let twitterReplaced = twitterReplace is actually needed.

Bear with me…..

client.on("messageCreate", async (message) => {
  const twitterTest = new RegExp(/b(httpsb://(x.com/|twitter.com/))(.*/status)/gm);
  if (message.author.bot) return;
  if (
    twitterTest.test(message.content)
  ) {
    let twitterReplace = message.content.replace(
      /b(httpsb://(x.com|twitter.com))/gm,
      "https://fxtwitter.com"
    );
    let twitterReplaced = twitterReplace
    let twitterCut = new RegExp(/gb(httpsb://(fxtwitter.com)).+?(?=?)/gm)
    let twitterFixed = twitterCut.match(twitterReplaced) 
    message.reply({content: twitterFixed, allowedMentions: {repliedUser: false}});
  }
});

However the above gives an error that an empty message can’t be sent.

Any help is greatly appreciated.

Border bottom & text color is not changing on Active Menu using Tailwind CSS, React, & string interpolation

I have created a header menu on which I want to show the border-bottom of the red color & text-color of black on the active menu. To achieve this I am using the useLocation() function from the react-router-dom but it is not showing up.

import { useLocation, useNavigate } from "react-router-dom";


const Header = () => {
    const location = useLocation();
    const navigate = useNavigate();

    const checkPath = (path) => {
        console.log(location.pathname, path);
        if (path === location.pathname) return true;
        else return false;
    }

    return (
        <div className="bg-white border-b shadow-sm sticky top-0 z-50">
            <header className="flex justify-between items-center px-3 max-w-6xl mx-auto">
                <div>
                    <img src="https://static.rdc.moveaws.com/images/logos/rdc-logo-default.svg" alt="" className="h-5 cursor-pointer" onClick={() => navigate('/')} />
                </div>
                <div>
                    <ul className="flex gap-5">
                        <li className={`py-6 text-sm border-b-[3px] text-gray-500 font-semibold border-b-transparent ${checkPath("/") && "text-black border-b-red-500"}  cursor-pointer`} onClick={() => navigate('/')}>Home</li>
                        <li className={`py-6 text-sm border-b-[3px] text-gray-500 font-semibold border-b-transparent ${checkPath("/offers") && "text-black border-b-red-500"}  cursor-pointer`} onClick={() => navigate('/offers')}>Offers</li>
                        <li className={`py-6 text-sm border-b-[3px] text-gray-500 font-semibold border-b-transparent ${checkPath("/sign-in") && "text-black border-b-red-500"} cursor-pointer`} onClick={() => navigate('/sign-in')}>Sign In</li>
                    </ul>

                </div>

            </header>
        </div>
    )
}

export default Header

This is the GitHub link of the repository: https://github.com/olifarhaan/griha-milan

How to replicate the issue

Clone the repository on your local machine.
Run the following script npm install

I tried everything but the I think the tailwind css is not overriding the previous classes I used console.log after && then it is showing in the console.

React native google sign in not working in release version on android

I have a react native expo project with react-native-google-signin module (and also with other modules) and I setup the way the documentations described. I made an OAuth client on google console and copied the SHA1 from the output of this command: keytool -list -v -keystore app/debug.keystore. I found this command from this article.

The app works when I run in development mode using my phone. I build the release using eas and it’s run perfectly on my phone but when I sent the release apk to my friend the google sign in appeared but not loged in even when he selected his own google account the sign in window just closed but no error appeared.

I don’t know what could be the problem because I followed the guide from here.

I also setup the firebase and added the google-services.json but it dind’t helped.

Next.js 13 global context using layout.js

I am trying to use Next.js to create a web app with authentication and global user state. Once a user is signed in I would like to display the user in the navbar, and also share that user state with the child components which may make API calls that require the user information. I am using Next.js 13 with the app directory and the app/layout.js file to store my navbar and user state.

My issue is that the navbar in app/layout.js is able to consistently display the username once it is decoded from the JSON web token, however this is not displayed within my child component (app/loginsuccess/page.jsx) which needs to have the user state too.

context/MyContext.js

import { createContext, useState } from "react";

const MyContext = createContext({
  value: null, 
  setValue: () => {}, 
});

export const MyProvider = ({ children }) => {
  const [value, setValue] = useState(null); 
  
  return (
    <MyContext.Provider value={{ value, setValue }}>
      {children}
    </MyContext.Provider>
  );
};

export default MyContext;

app/layout.jsx

"use client";

import "./globals.css";
import Link from "next/link";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Cookies from "js-cookie";
import { MyProvider } from "@/context/MyContext";

const getUserFromJWTCookie = async () => {
  const authToken = Cookies.get("token");
  const response = await fetch("/api/session", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ token: authToken }),
  });
  const responseData = await response.json();
  const username = responseData.username;
  if (username) {
    console.log("getUserFromJWTCookie", username);
    return username;
  }
};

export default function RootLayout({ children }) {
  const router = useRouter();
  const [user, setUser] = useState("");

  useEffect(() => {
    (async () => {
      const user = await getUserFromJWTCookie();
      setUser(user);
      if (!user) {
        router.replace("/logintest");
      }
    })();
  }, [router]);

  return (
    <MyProvider value={{ value: user, setValue: setUser }}>
      <html lang="en">
        <body>
          <nav className="bg-gray-800 text-white p-4">
            <ul className="flex justify-center space-x-4">
              <li className="hover:bg-gray-700 rounded-md p-2">
                <Link href="/show">
                  <h1 className="text-xl font-semibold">Shows</h1>
                </Link>
              </li>
              <li className="hover:bg-gray-700 rounded-md p-2">
                <Link href="/user">
                  <h1 className="text-xl font-semibold">Users</h1>
                </Link>
              </li>
              <li className="hover:bg-gray-700 rounded-md p-2">
                <Link href="/loginsuccess">
                  <h1 className="text-xl font-semibold">{user}</h1>
                </Link>
              </li>
            </ul>
          </nav>
          <main>{children}</main>
        </body>
      </html>
    </MyProvider>
  );
}

app/loginsuccess/page.jsx

"use client";

import { useContext, useState, useEffect } from "react";
import MyContext from "@/context/MyContext";

const ProtectedPage = () => {
  const { value } = useContext(MyContext);
  const [user, setUser] = useState("");

  useEffect(() => {
    setUser(value);
  }, [value]);

  return <div>Welcome! {user}</div>;
};

export default ProtectedPage;

Any help in making this render at the same time in my child component is greatly appreciated 🙂

Is it a good practice to use .mjs instead of declearing the package/script as module? [closed]

Using the .mjs file extension for JavaScript files indicates that the file is an ES module. When using this convention, i don’t necessarily need to declare the package as a module with "type"="module" in the package.json file or use the module script tag. Instead, the file extension itself signals that the file should be treated as a module.

  1. Is it a good practice to use this convention instead of declearing the whole package as module? Because this provides a clear and explicit indication that this file is intended to be treated as a module.
  2. Will code behave exactly the same in both cases? Meaning that there is no single difference between using .mjs and type=module!?

Change useRef value before the html renders (React Functional Component)

Hey everyone i trying to change the value of useRef before the html renders I tried to do that in useEffect but useEffect runs after the html is ready so can’t use useEffect
So what i am trying to do is reset the value of ultiDayPlaceHFactor variable value to 0 before the html renders because i am updating the value of ultiDayPlaceHFactor for next or previous week events

below is that code Please check it out

const Week = ({ events, weekDates, currentDate, toggle }: Props) => {
  const { startHour: START_HOUR, endHour: END_HOUR } = useStore();

  const [multiDayEvents, setMultiDayEvents] = useState<any[]>([]);
  const [showAllMultiDEvents, setShowMultiDEvents] = useState<boolean>(false);
  // const [multiDPlaceHeight, setMultiDHeight] = useState<number>(0);

  const hours = eachMinuteOfInterval(
    {
      start: new Date(new Date().setHours(START_HOUR)).setMinutes(0),
      end: new Date(new Date().setHours(END_HOUR)).setMinutes(0),
    },
    { step: 60 }
  );


  const multiDayPlaceHFactor = useRef(0);
  const computeMultiDPHeight = (val: number) => {
    return val > 2 && !showAllMultiDEvents ? 3 * 28 : val * 28;
  };

  // useEffect(() => {
  //   multiDayPlaceHFactor.current = 0;
  //   // eventsIndexes.current = [];

  //   console.log('------------------------------------');
  //   console.log(multiDayPlaceHFactor, 'Height factor');
  //   // console.log(eventsIndexes, 'event indexes');
  // }, [weekDates, showAllMultiDEvents]);

  console.log(multiDayPlaceHFactor, 'height factor');

  return (
    <React.Fragment>
      <div className="w-100">
        <div id="day-layout-table" className="mt-3">
          <table className="e-schedule-table border mb-0">
            <tbody>
              <tr>
              
                <td>
                  <div className="e-date-header-container">
                    <div className="e-date-header-wrapper">
                      <table className="e-schedule-table">
                        <colgroup>
                          <col></col>
                          <col></col>
                          <col></col>
                          <col></col>
                          <col></col>
                          <col></col>
                          <col></col>
                        </colgroup>
                        <thead>
                          <tr>
                            {(weekDates || []).map((e) => {
                              const today = e;
                              const eachFirstDayInCalcRow = isSameDay(
                                weekDates[0],
                                today
                              )
                                ? today
                                : null;
                              const todayEvents = events.filter(
                                (e: {
                                  startDate: number | Date;
                                  endDate: number | Date;
                                }) =>
                                  (eachFirstDayInCalcRow &&
                                    areIntervalsOverlapping(
                                      {
                                        start: e.startDate,
                                        end: e.endDate,
                                      },
                                      {
                                        start: startOfDay(today),
                                        end: endOfDay(today),
                                      }
                                    ) &&
                                    differenceInDaysOmitTime(
                                      new Date(e.startDate),
                                      new Date(e.endDate)
                                    ) > 1) ||
                                  (isSameDay(e.startDate, today) &&
                                    differenceInDaysOmitTime(
                                      new Date(e.startDate),
                                      new Date(e.endDate)
                                    ) > 1)
                              );

                              // console.log(todayEvents, 'today events');

                              const prevNextEvents = events.filter((e) => {
                                const isWithinToday =
                                  areIntervalsOverlapping(
                                    {
                                      start: e.startDate,
                                      end: e.endDate,
                                    },
                                    {
                                      start: startOfDay(today),
                                      end: endOfDay(today),
                                    }
                                  ) &&
                                  differenceInDaysOmitTime(
                                    e.startDate,
                                    e.endDate
                                  ) > 1;

                                return isWithinToday;
                              });

                              ///////////////////////////////// 
                              /////////////////////////////////
                              / HERE IS THE UPDATE VALUE CODE /
                              ///////////////////////////////// 
                              /////////////////////////////////
                              if (
                                prevNextEvents.length >
                                multiDayPlaceHFactor.current
                              )
                                multiDayPlaceHFactor.current =
                                  prevNextEvents.length;
                              /////////////////////////////////
                              /////////////////////////////////
                              / HERE IS THE UPDATE VALUE CODE /
                              ///////////////////////////////// 
                              /////////////////////////////////

                              let eventsIndexes: any = [];

                              return (
                                <td
                                  className="e-all-day-appointment-wrapper"
                                  key={uuid()}
                                >
                                  <RenderMultidayEvents
                                    multiDayEvents={todayEvents}
                                    prevNextEvents={prevNextEvents}
                                    showMultiDEvents={showAllMultiDEvents}
                                    eventsIndexes={eventsIndexes}
                                    weekStart={startOfDay(weekDates[0])}
                                    weekEnd={endOfDay(
                                      weekDates[weekDates.length - 1]
                                    )}
                                  />
                                  {prevNextEvents.length > 2 &&
                                    !showAllMultiDEvents && (
                                      <div className="px-1">
                                        <button
                                          onClick={() =>
                                            setShowMultiDEvents(
                                              !showAllMultiDEvents
                                            )
                                          }
                                          className="e-more-indicator fs-7 btn btn-secondary p-1 w-100 text-start position-absolute"
                                          data-count="1"
                                          data-group-index="0"
                                          style={{
                                            top: `${3 * 32}px`,
                                            left: 0,
                                          }}
                                        >
                                          +{prevNextEvents.length - 2}&nbsp;more
                                        </button>
                                      </div>
                                    )}
                                </td>
                              );
                            })}
                          </tr>
                        </thead>
                        <tbody>
                          <tr></tr>
                          <tr className="e-header-row">
                            {(weekDates || []).map((date, i) => (
                              <td
                                colSpan={1}
                                key={uuid()}
                                className={
                                  isSameDay(date, currentDate)
                                    ? 'fw-normal text-center align-middle text-Capitalize text-primary border-start'
                                    : 'fw-normal text-center align-middle text-Capitalize border-start'
                                }
                                style={{ width: '116.6px' }}
                              >
                                <div className="e-header-cells">
                                  {format(date, 'd EEE')}
                                </div>
                              </td>
                            ))}
                          </tr>
                          <tr className="e-all-day-cells">
                            {(weekDates || []).map((e) => {
                              return (
                                <td
                                  key={uuid()}
                                  style={{
                                    height: `${computeMultiDPHeight(
                                      multiDayPlaceHFactor.current
                                    )}px`,
                                  }}
                                  className="border-start"
                                >
                                  <div></div>
                                </td>
                              );
                            })}
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  </div>
                </td>
              </tr>

              <tr>
                <td>
                  <div
                    style={{ height: DEFAULT_SHEDULAR_HEIGHT }}
                    className="e-time-cells-wrap"
                  >
                    <table>
                      <tbody>
                        {(hours || []).map((time, idx) => (
                          <tr key={uuid()}>
                            <td
                              style={{ height: CELL_HEIGHT }}
                              className="calendar-td calendar-td-w border-top py-0 align-middle"
                            >
                              <span className="fs-7">
                                {format(time, 'h:mm a', { locale: enUS })}
                              </span>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </td>
                <td>
                  <div
                    style={{ height: DEFAULT_SHEDULAR_HEIGHT }}
                    className="e-content-wrap"
                  >
                    <table className="e-schedule-table">
                      <colgroup>
                        <col></col>
                        <col></col>
                        <col></col>
                        <col></col>
                        <col></col>
                        <col></col>
                        <col></col>
                      </colgroup>
                      <thead>
                        <tr>
                          {(weekDates || []).map((date, i) => (
                            <td
                              key={uuid()}
                              className="e-day-wrapper overflow-visible"
                            >
                              <div className="e-appointment-wrapper">
                                <RenderEvents
                                  day={date}
                                  events={getAppointmentsByDates(date, events)}
                                />
                              </div>
                            </td>
                          ))}
                        </tr>
                      </thead>
                      <tbody>
                        {(hours || []).map((time, idx) => (
                          <tr key={idx}>
                            {(weekDates || []).map((date) => (
                              <td
                                key={uuid()}
                                aria-label={date.toISOString()}
                                style={{ height: CELL_HEIGHT }}
                                className="calendar-td calendar-td-w border-start border-top text-nowrap day-time-w fs-8 py-0 align-middle"
                              ></td>
                            ))}
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </React.Fragment>
  );
};```

WordPress admin-ajax.php what is search parameter

I am new to php and wordpress.
On admin-ajax.php is there a search parameter i can add ?
These parameters are in the ajax post;

action: rblivep
data[uuid]: uid_search_0
data[name]: grid_small_1
data[posts_per_page]: 8
data[pagination]: infinite_scroll
data[crop_size]: foxiz_crop_g1
data[entry_category]: bg-1
data[entry_meta][]: date
data[review]: replace
data[sponsor_meta]: 1
data[entry_format]: bottom
data[excerpt_source]: tagline
data[paged]: 1
data[page_max]: 28
data[processing]: true
data[page_next]: 2
search_query: phones

I added this to the paramters to return only search results but it did not worked.
search_query: phones

No matter what paramter i added i couldn’t get it to give the search results.

VIDEO in video = createCaputure(VIDEO) is not recognized by IDE [closed]

I downloaded p5 from the official p5-website and tried to use my webcam. But the VIDEO argument is not recognized by my IDE and therefore what my webcam captures isn’t displayed at the website. I tried it in VS-Code an Webstorm but in both IDE’s it didn’t work. I couldn’t find any helpful tips on the internet so please help me. 🙂 and merry Christmas to everbody 🙂

let video;
function setup() {
 createCanvas(640, 520);
 video = createCapture(VIDEO);
 video.hide();
}

function draw() {
 background(0);
  // put drawing code here
}

HTML

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

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>p5.js example</title>
  <style>
    body {
      padding: 0;
      margin: 0;
      background-color: #1b1b1b;
    }
  </style>
  <script src="../p5.min.js"></script>
  <script src="https://unpkg.com/ml5@latest/dist/ml5.min.js"></script>
  <!-- <script src="../addons/p5.sound.js"></script> -->
  <script src="sketch.js"></script>
</head>

<body>
  <main>
  </main>
</body>

</html>

Troubleshooting Google Analytics Integration in a React/Next.js App

I’m encountering issues with setting up Google Analytics in my React/Next.js application. I’ve created a GoogleAnalytics component as follows:

// GoogleAnalytics.tsx

import Script from "next/script";

const GoogleAnalytics = () => {
  return (
    <>
      <Script
        src={`https://www.googletagmanager.com/gtag/js?id=G-SMWF3K8CDQ`}
        strategy="afterInteractive"
      />
      <Script id="google-analytics" strategy="afterInteractive">
        {`
          window.dataLayer = window.dataLayer || [];
          function gtag(){dataLayer.push(arguments);}
          gtag('js', new Date());

          gtag('config', 'G-SMWF3K8CDQ');
        `}
      </Script>
    </>
  );
};

export default GoogleAnalytics;

This component is imported and used in my layout.tsx file like this:

// layout.tsx

import React from "react";
import Head from "next/head";
import "./css/style.css";
import Analytics from "@/components/Analytics";
import { Inter } from "next/font/google";
import Header from "@/components/ui/header";
import Banner from "@/components/banner";

const inter = Inter({
  subsets: ["latin"],
  variable: "--font-inter",
  display: "swap",
});

export const metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <Head>
        <Analytics /> {/* Use the Analytics component inside the Head component */}
      </Head>
      <body
        className={`${inter.variable} font-inter antialiased bg-white text-gray-900 tracking-tight`}
      >
        <div className="flex flex-col min-h-screen overflow-hidden supports-[overflow:clip]:overflow-clip">
          <Header />
          {children}
          <Banner />
        </div>
      </body>
    </html>
  );
}

When I use the Google Tag Assistant to check for the tag while running the app in development mode on localhost, it doesn’t detect anything.

Questions:

  1. Have I configured the Google Analytics script integration correctly in a React/Next.js environment?
  2. Is there a specific setup or modification required for Google Analytics to work correctly on localhost or in development mode?
  3. Are there known issues or additional steps I should be aware of for integrating Google Analytics with Next.js?

I appreciate any insights or suggestions to resolve this issue.

Styles on a class added by ClassList isn’t working

My code seems to be fine, when I console.log the class name it shows that the class is added, but the styles are not working. It was working just fine before but idk what triggered this problem now.
Any help would be appreciated!

JS code:

let maxAmountMessageTimeoutId;
// Max Amount Added Message Visibility
export function displayMaxAmountMessage(productId) {
  const maxAmountMessage = document.querySelector(`.js-max-amount-message-${productId}`);

  maxAmountMessage.classList.add("max-amount-message-visible");

  if (maxAmountMessageTimeoutId) {
    clearTimeout(maxAmountMessageTimeoutId);
  }

  const timeoutId = setTimeout(() => {
    maxAmountMessage.classList.remove("max-amount-message-visible");
  }, 2000);

  maxAmountMessageTimeoutId = timeoutId;
  console.log(maxAmountMessage.className);
}

CSS code:

.max-amount-message {
  color: red;
  font-size: 15px;
  opacity: 0;
}

.max-amount-message-visible {
  opacity: 1;
}

I tried putting the function in the main file, and put “let maxAmountMessageTimeoutId;” before the click event listener out of scope as a global variable but nothing I try works. If I delete the line “let maxAmountMessageTimeoutId;” then the message appears but invokes errors and clearTimeout doesn’t work obviously.

Discord does not show bot status

My aim was to reflect the player status, but the status does not appear normally, nor does the status appear in any way.

client.once('ready', () => {
  console.log(`Bot Durumu Aktif!`);

  setInterval(updateStatusFromLink, 1 * 60 * 1000);
});

async function updateStatusFromLink() {
  try {
    const response = await axios.get(link);
    const html = response.data;

    const $ = cheerio.load(html);
    const targetSpan = $(targetDivSelector);

    const playerStatus = targetSpan.text();

    // Botun durumunu güncelle
    client.user.setActivity(playerStatus, { type: 'PLAYING' });

    console.log('Oyuncu Durumu:', playerStatus);
  } catch (error) {
    console.error('Veriyi alma hatası:', error.message);
  }
}

Best js library for pdf editing

i am completely new in programing and this will be my second project. I am trying to build a webpage that allows users to copy data from pdf such as text and strings and paste it in desired destination. I did try chatgpt before for help but things didn’t work, can any help me with this specifically what library I should use and potential bugs I should be looking out for, I have tried chatgpt before but that code is throwing unknown errors, and they are quite impossible to solve as most of time I am going in loop with them

How should I call Set?

let a = new Set();

let b = new Set();

a.add(1);

a.add(2);

a.add(3);

b.add(a);

console.log(b); //Set(1) {Set(3)}

console.log(b.has(Set(3))); // error

Why? then, how can I call Set?

And I expected that

console.log(b.has({1,2,3})); // true