Why are ESLint errors not highlighted in the code?

ESLint errors are displayed in the console, but nothing is highlighted in the code itself. I guess the problem may be that I switched to another device and did something wrong in the project.

My IDE – WebStorm, going to Settings -> Language -> JavaScript -> ESLint, selected the Manual Eslint configuration item and specified the paths to ESLint and its configuration in the project, also added the ESLint plugin, but all this did not fix my problem

handle input box in map using Reactjs

<input
  type="text"
  id={`order_${i}`}
  name={`order_${i}`}
  style={{
    width: "50px",
    borderRadius: "100px",
    border: "none",
    textAlign: "center",
    background: "#d7eefc",
  }}
  value={sortOrder || folder.sort_order}
  onChange={(e) => setSortOrder(e.target.value)}
/>;

if i change any one value of input box then it is update all input box value in map

POST http://localhost:3000/api/auth/callback/credentials 403 (Forbidden) when submitting login form

I’m pretty new to Next and while doing an authentications system I noticed that I couldn’t login cause it kept giving me this POST http://localhost:3000/api/auth/callback/credentials 403 (Forbidden). The google authentication is working fine but I found out that if I remove the google provider section, the login is working fine. As if both couldn’t work together. Here is the code of my route.js in auth/[…nextauth] :

import NextAuth from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import CredentialProvider from 'next-auth/providers/credentials';
require('dotenv').config();
import User from '/models/user';
import { connectToDatabase } from "@utils/mongodb";

const bcrypt = require('bcrypt');

const authOptions = {

    pages: {
        signIn: "/auth/login",
      },

    session: {
        jwt: true,
    },

    providers: [
        GoogleProvider({
            name: "Google",
            id: "google",
            type: "oauth",
            clientId: process.env.GOOGLE_CLIENT_ID,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET
        }),
        CredentialProvider({
            credentials: {
                email: { type: "email" },
                password: { type: "password"},
            },
   
            async authorize(credentials, _req) {
        
                console.log(credentials)

                const { email, password } = credentials;
        
                try {
                    await connectToDatabase();
                    const userExists = await User.findOne({ email: email });
                    console.log(userExists)
                    if (!userExists) {
                        return new Response("User does not exist", { status: 401 });
        
                    } else {
        
                        if (bcrypt.compareSync(password, userExists.password)) {
                            {return userExists;
                        } else{
                            console.log("incorrect password");
                            return new Response("Incorrect password", { status: 401 });
                        }
                    }
        
                } catch (error) {
                    console.log(error);
                    return new Response("An error occurred", { status: 500 });
                }
            },
        }),
    ],


    callbacks: {

        async signIn({ user, profile, account }) {

            if(account.provider === 'google'){

            const { id, name, email, image } = user;

            try {
                const res = await fetch('http://localhost:3000/api/user', {
                    method: 'POST',
                    body: JSON.stringify({
                        name,
                        email,
                        password: id,
                        image
                    }),
                    headers: {
                        'Content-Type': 'application/json'
                    },
                });

                if (res.ok) {
                    return user;
                } else if(res.status === 200){
                    return user;
                } 
                    
            } catch (error) {
                    console.log(error);
            }
        }
        },
        
    },

};

const handler = NextAuth(authOptions);

export { handler as GET, handler as POST }


After some debugging I also found out that apparently, the error occurs when I return the value at the end of the authorize function here :

if (bcrypt.compareSync(password, userExists.password)) {return userExists;}

but still can’t figure out how to fix it

Inquiry Regarding Push Notification Retrieval from Third-Party Web Application

I hope this message finds you well.
I am currently working on a project where I need to retrieve push notifications from a third-party web application using either Python or Java Script. Before proceeding, I wanted to inquire whether anyone in community has encountered a similar challenge and if there are any recommended solutions or best practices.
I would greatly appreciate any insights, experiences, or guidance from the community to ensure that I am approaching this task in the most effective and efficient manner.

Thank you in advance for your time and assistance.

Forex trade outcome calculator

I’m trying to build an application which calculates the result of a forex trade.

I have managed to build something which calculates the next result with the previous result of the calculated trade, the problem I am facing is that the previous trade my not actually be closed before the next trade is calculated, resulting in the wrong balance being used ( a balance which is only available in the future once the trade is closed)

Example

            const trades = [{
                  pair: "EURCAD",   
                  entryDate: "01/01/24",
                  entryTime: "12:10",
                  exitDate: "01/01/24"
                  exitTime: "13:10",}

              {
                  pair: "AUDUSD",   
                  entryDate: "03/01/24",
                  entryTime: "17:40",
                  exitDate: "05/01/24"
                  exitTime: "22:40"},

               {
                  pair: "EURUSD",   
                  entryDate: "04/01/24",
                  entryTime: "16:15",
                  exitDate: "12/01/24"
                  exitTime: "13:10"},
   
        
        
        ]

Here is the function that I’ve created so far.

I have also created a working Codepen which can be found here

Code Pen

    const run = async () => {

  const markets = [
    { label: "GBP/CAD", ticker: "GBPCAD", pipDistance: 0.0001 },
    { label: "AUD/USD", ticker: "AUDUSD", pipDistance: 0.0001 },
    { label: "EUR/USD", ticker: "EURUSD", pipDistance: 0.0001 },
    { label: "EUR/CAD", ticker: "EURCAD", pipDistance: 0.0001 },
  ];
  const allTradesArray = [
    {
      _id: "65b26a76fb5bea9618e111ca",
      pair: "EURCAD",
      direction: "Short",
      created: {
        $date: "2024-01-01T04:10:55.000Z",
      },
      entryDate: "01/01/24",
      entryTime: "12:10",
      exitDate: "01/01/24",
      exitTime: "13:10",
      openPrice: "1.47363",
      closePrice: "1.48200",
      stopLossPips: "86",
      fee: "0",
    },
    {
      _id: "65b26b87fb5bea9618e111de",
      pair: "EURUSD",
      direction: "Long",
      created: {
        $date: "2024-01-04T04:10:55.000Z",
      },
      entryDate: "04/01/24",
      entryTime: "16:15",
      exitDate: "12/01/24",
      exitTime: "19:00",
      openPrice: "1.47363",
      closePrice: "1.48255",
      stopLossPips: "29.5",
      fee: "0",
    },
    {
      _id: "65b26c49fb5bea9618e111fc",
      pair: "AUDUSD",
      direction: "Short",
      created: {
        $date: "2024-01-05T09:40:55.000Z",
      },
      entryDate: "03/01/24",
      entryTime: "17:40",
      exitDate: "05/01/24",
      exitTime: "22:40",
      openPrice: "1.46509",
      closePrice: "1.46809",
      stopLossPips: "10",
      fee: "0",
    },
    {
      _id: "65b27fc6fb5bea9618e1137e",
      pair: "GBPCAD",
      direction: "Short",
      created: {
        $date: "2024-01-09T04:10:55.000Z",
      },
      entryDate: "09/01/24",
      entryTime: "12:10",
      exitDate: "10/01/24",
      exitTime: "15:01",
      openPrice: "1.46509",
      closePrice: "1.46809",
      stopLossPips: "30",
      fee: "0",
    },
  ];



  const calculateFields = async (allTrades) => {
    let trades = allTrades;
    let profitLossDollar;
    let profitLossPercentage;
    let rollingReturnPercentage;


    let startingBalance = 50000;
    let balance = startingBalance;
 

    // account for slippage eg. if trade loses by 0.5 of a pip lets call it a breakeven
    const slippageTrades = true;

    let virtualFields = [];
    let returnTotals = [];
    let note;
    let reason;

    const checkTypeOfPair = (p) => {
      const pairObject = markets.find((m) => m.ticker === p);

      const schema = { pipDistance: pairObject?.pipDistance };

      return schema;
    };
    const calculateDollarPipRisk = (balance, stopLossPips) => {
      const dollarValueRiskPerTrade = (1 / 100) * balance;
      const perPipValue = dollarValueRiskPerTrade / stopLossPips;
      return {
        riskValue: parseFloat(dollarValueRiskPerTrade.toFixed(2)),
        valuePerPip: parseFloat(perPipValue.toFixed(2)),
      };
    };
    const calculateOutcomeOfSlippage = (
      closePrice,
      openPrice,
      direction,
      pair
    ) => {
      const typeofPair = checkTypeOfPair(pair);

      if (closePrice === "") {
        return "In Progress";
      }

      if (closePrice === openPrice) {
        return "Breakeven";
      }

      if (direction === "Long") {
        if (closePrice < openPrice) {
          const amountOfPipsLostBy =
            (openPrice - closePrice) / typeofPair.pipDistance;
          if (parseFloat(amountOfPipsLostBy.toFixed(1)) <= 0.5) {
            return "Breakeven";
          } else {
            return "Loss";
          }
        } else if (closePrice > openPrice) {
          const amountOfPipsWonBy =
            (closePrice - openPrice) / typeofPair.pipDistance;
          if (parseFloat(amountOfPipsWonBy.toFixed(1)) <= 0.5) {
            return "Breakeven";
          } else {
            return "Win";
          }
        }
      } else if (direction === "Short") {
        if (closePrice > openPrice) {
          const amountOfPipsLostBy =
            (closePrice - openPrice) / typeofPair.pipDistance;
          if (parseFloat(amountOfPipsLostBy.toFixed(1)) <= 0.5) {
            return "Breakeven";
          } else {
            return "Loss";
          }
        } else if (closePrice < openPrice) {
          const amountOfPipsWonBy =
            (openPrice - closePrice) / typeofPair.pipDistance;
          if (parseFloat(amountOfPipsWonBy.toFixed(1)) <= 0.5) {
            return "Breakeven";
          } else {
            return "Win";
          }
        }
      }
    };
    const calculateOutcome = (
      closePrice,
      openPrice,
      direction,
      pair,
      slippage
    ) => {
      if (closePrice === "") {
        return "In Progress";
      }

      if (closePrice === openPrice) {
        return "Breakeven";
      }

      if (direction === "Long") {
        if (closePrice < openPrice) {
          return "Loss";
        } else if (closePrice > openPrice) {
          return "Win";
        }
      } else if (direction === "Short") {
        if (closePrice > openPrice) {
          return "Loss";
        } else if (closePrice < openPrice) {
          return "Win";
        }
      }
    };
    const workOutWinLoseInPips = (
      outcome,
      direction,
      closePrice,
      openPrice,
      pair
    ) => {
      let pipsWonBy;
      let pipsLostBy;

      const typeofPair = checkTypeOfPair(pair);
      if (outcome === "Breakeven" || outcome === "In Progress") {
        pipsWonBy = 0;
        pipsLostBy = 0;
      }
      // handle longs
      if (direction === "Long" && outcome === "Win") {
        const amountOfPipsWonBy =
          (closePrice - openPrice) / typeofPair.pipDistance;
        pipsWonBy = parseFloat(amountOfPipsWonBy.toFixed(1));
        pipsLostBy = 0;
      } else if (direction === "Long" && outcome === "Loss") {
        const amountOfPipsLostBy =
          (openPrice - closePrice) / typeofPair.pipDistance;
        pipsLostBy = parseFloat(amountOfPipsLostBy.toFixed(1));
        pipsWonBy = 0;
      }
      // handle Shorts
      if (direction === "Short" && outcome === "Win") {
        const amountOfPipsWonBy =
          (openPrice - closePrice) / typeofPair.pipDistance;
        pipsWonBy = parseFloat(amountOfPipsWonBy.toFixed(1));
        pipsLostBy = 0;
      } else if (direction === "Short" && outcome === "Loss") {
        const amountOfPipsLostBy =
          (closePrice - openPrice) / typeofPair.pipDistance;
        pipsLostBy = parseFloat(amountOfPipsLostBy.toFixed(1));
        pipsWonBy = 0;
      }

      return { pipsLostBy: pipsLostBy, pipsWonBy: pipsWonBy };
    };

    for (let index = 0; index < trades.length; index++) {
      const trade = trades[index];


      const outcome = calculateOutcome(
        trade.closePrice,
        trade.openPrice,
        trade.direction,
        trade.pair
      );

      const outcomeOfSlippage = calculateOutcomeOfSlippage(
        trade.closePrice,
        trade.openPrice,
        trade.direction,
        trade.pair
      );

      const { riskValue, valuePerPip } = calculateDollarPipRisk(
        balance,
        trade.stopLossPips
      );

      const { pipsWonBy, pipsLostBy } = workOutWinLoseInPips(
        !slippageTrades ? outcomeOfSlippage : outcome,
        trade.direction,
        trade.closePrice,
        trade.openPrice,
        trade.pair,
        slippageTrades
      );
      const fee = parseFloat(trade.fee);
      const fee_cleaned = Math.abs(fee);
      const feeAsDecimal = parseFloat(
        ((fee_cleaned / balance) * 100).toFixed(2)
      );

      if (outcome === "Win") {
        // calculate percentagte return or loss for this trade
        profitLossPercentage = ((valuePerPip * pipsWonBy) / balance) * 100;
        profitLossPercentage = parseFloat(profitLossPercentage.toFixed(2));
        // calculate dollar return or loss for this trade
        profitLossDollar = valuePerPip * pipsWonBy;
        profitLossDollar = parseFloat(profitLossDollar.toFixed(2));

        // calculate balance after broker fees
        if (fee < 0) {
          balance = balance + pipsWonBy * valuePerPip - fee_cleaned;
 
          profitLossDollar = profitLossDollar - fee_cleaned;
          profitLossPercentage = profitLossPercentage - feeAsDecimal;
        } else if (fee > 0) {
          balance = balance + pipsWonBy * valuePerPip + fee_cleaned;
    
          profitLossDollar = profitLossDollar + fee_cleaned;
          profitLossPercentage = profitLossPercentage + feeAsDecimal;
        } else if (fee === 0) {
          balance = balance + pipsWonBy * valuePerPip;
        
        }
      } else if (outcome === "Loss") {
        // calculate percentagte return or loss for this trade
        profitLossPercentage = ((valuePerPip * pipsLostBy) / balance) * 100;
        //convert to negative number
        profitLossPercentage = -Math.abs(
          parseFloat(profitLossPercentage.toFixed(2))
        );
        // calculate dollar return or loss for this trade
        profitLossDollar = valuePerPip * pipsLostBy;
        //convert to negative number
        profitLossDollar = -Math.abs(parseFloat(profitLossDollar.toFixed(2)));

        if (fee < 0) {
          balance = balance - pipsLostBy * valuePerPip - fee_cleaned;
       
          profitLossDollar = profitLossDollar - fee_cleaned;
          profitLossPercentage = profitLossPercentage - feeAsDecimal;
        } else if (fee > 0) {
          balance = balance - pipsLostBy * valuePerPip + fee_cleaned;
      
          profitLossDollar = profitLossDollar + fee_cleaned;
          profitLossPercentage = profitLossPercentage + feeAsDecimal;
        } else if (fee === 0) {
          balance = balance - pipsLostBy * valuePerPip;
         
        }
      } else if (outcome === "Breakeven" || outcome === "In Progress") {
        // calculate percentagte return or loss for this trade
        profitLossPercentage = 0;
        // calculate dollar return or loss for this trade
        profitLossDollar = 0;

        if (fee < 0) {
          balance = balance - fee_cleaned;
   
          profitLossDollar = profitLossDollar - fee_cleaned;
          profitLossPercentage = profitLossPercentage - feeAsDecimal;
        } else if (fee > 0) {
          balance = balance + fee_cleaned;
       
          profitLossDollar = profitLossDollar + fee_cleaned;
        } else if (fee === 0) {
          //  balance stays the same
        }
      }

      returnTotals.push(profitLossPercentage);

      let returnTotals_sum = returnTotals.reduce(function (a, b) {
        return a + b;
      });
      // rolling percentage
      const priceDifference = balance - startingBalance;

      const percent = (priceDifference / startingBalance) * 100;

      rollingReturnPercentage = parseFloat(percent.toFixed(2));

      const newTrade_virtual = {
        _id: trade._id,
        riskValue: parseFloat(riskValue.toFixed(2)),
        valuePerPip: parseFloat(valuePerPip.toFixed(2)),
        profitLossDollar: parseFloat(profitLossDollar.toFixed(2)),
        profitLossPercentage: parseFloat(profitLossPercentage.toFixed(2)),
        outcome: slippageTrades ? outcomeOfSlippage : outcome,
        rollingBalance: balance.toFixed(2),
        rollingReturnPercentage: rollingReturnPercentage,
        openPrice: trade.openPrice,
        closePrice: trade.closePrice,
        pair: trade.pair,
        direction: trade.direction,
        stopLossPips: trade.stopLossPips,
        entryDate: trade.entryDate,
        entryTime: trade.entryTime,
        exitDate: trade.exitDate,
        exitTime: trade.exitTime,
        fee: trade.fee,
        returnTotals: returnTotals_sum.toFixed(2),
      };


      virtualFields.push(newTrade_virtual);

      // console.log("percentage return", returnTotals_sum.toFixed(2));
      // console.log("dollar return", priceDifference.toFixed(2));
      // console.log("balance", balance.toFixed(2));
    } // end of Alltrades for loop
    console.log("virtualFields", virtualFields);
  };

  await calculateFields(allTradesArray);
};

run()

Fixing Java Script ‘Uncaught in promise TypeError’

The error states it cannot read the property ‘add’ of Utils.js:94. Line 94 is the bracket } above ‘Return a string…’

This is not my code, I am using an RPG Maker and have had 0 response from the forums on this issue. Does anyone know what the error is and how I can fix it? Thank you. I’m happy to give extra information as needed.

/** Try catch for async functions

 *   @static
 *   @param {function} func - The async function to apply
 *   @returns {Promise<any>}
 */
static async tryCatch(func, that) {
    try {
        return await func.call(that);
    }
    catch (e) {
        window.onerror(null, null, null, null, e);
    }
}
/** Return a string of the date by passing all the seconds
 *   @static
 *   @param {number} total - Total number of seconds
 *   @returns {string}
 */

Is it possible to get path from Nextjs app router with id like [id] instead of a custom id

I am using nextjs App router and next-intl localize pathname api. I would like to know if its possible to get pathname just like we mention in the navigation file. Currently I get pathname from NextRequest with an id like /de/users/5 but I have it in my navigation file like /de/users/[id].

Maybe this is a completely wrong approach. It will be helpful for me if you guide me how do I solve this?

// navigation.ts
import {
 createLocalizedPathnamesNavigation,
 Pathnames
} from 'next-intl/navigation';

export const locales = ['en', 'de'] as const;
export const localePrefix = 'always'; // Default

// The `pathnames` object holds pairs of internal
// and external paths, separated by locale.
const privatePathnames = {
  // Dynamic params are supported via square brackets
  '/users/[id]': {
     en: '/users/[id]',
     de: '/benutzer/[id]'
  },
}
export const pathnames = {
// If all locales use the same pathname, a
// single external path can be provided.
'/': '/',

// If locales use different paths, you can
// specify each external path per locale.
'/about': {
  en: '/about',
  de: '/ueber-uns'
},
...privatePathnames,

} satisfies Pathnames<typeof locales>;

export const {Link, redirect, usePathname, useRouter, getPathname} =
   createLocalizedPathnamesNavigation({locales, localePrefix, pathnames});

In middleware I am checking if its a private route and user don’t have a token then redirect the user to home page

// middleware.ts
import createMiddleware from 'next-intl/middleware';
import {locales, localePrefix} from './navigation';

const publicRoutes = ["/", "/en", "/de"];
// process "privatePathnames" and returns ["/en/users/[id]", "/de/users/[id]"]
const privateRoutes = privatePathMakerWithLocale(); 
export default async function middleware(req: NextRequest) {
   const intlMiddleware = createMiddleware({
    // A list of all locales that are supported
     locales,
     localePrefix,
     pathnames,
     // Used when no locale matches
     defaultLocale: 'en'
   });
   const res = intlMiddleware(req);
   let isVerifiedUser = false;
   const {pathname, origin} = req.nextUrl;
   const locale = req.cookies.get('NEXT_LOCALE')?.value || defaultLocale;
   if (publicRoutes.includes(pathname) && isVerifiedUser) {
      console.log("public route");
      return NextResponse.redirect(`${origin}/${locale}/users`);
   }
   // here the pathname is "/de/benutzer/5" while privateRoutes has ["/en/users/[id]", "/de/users/[id]"]
   if (privateRoutes.includes(pathname) && !isVerifiedUser) { 
      console.log("private route");
      return NextResponse.redirect(`${origin}/${locale}`);
   }
}
export const config = {
  // Match only internationalized pathnames
  matcher: ['/', '/(de|en)/:path*']
};

Video can’t be open in allure reporter using wdio-video-reporter

I have problem when using wdio-video-reporter.

I’m using allure reporter and want to add video reporter to it. I’ve read and follow instruction from documentation wdio website https://webdriver.io/es/docs/wdio-video-reporter/.

Here are my configure in wdio.config.js

const video = require('wdio-video-reporter');

reporters: [
    [videos, {
      saveAllVideos: true,
      videoSlowdownMultiplier: 3,
    }],
    ['allure', {
      outputDir: './allure-results',
      disableWebdriverStepsReporting: true,
      disableWebdriverScreenshotsReporting: true,
      useCucumberStepReporter: true,
      addConsoleLogs: true,
    }],
]

I found some stack here. I found in my allure report, the video like this can’t open
video can’t open.

And in My Terminal have error like this.

[0-39] node:internal/process/promises:279
[0-39]             triggerUncaughtException(err, true /* fromPromise */);
[0-39]             ^
[0-39] 
[0-39] Protocol error (Target.activateTarget): Target closed.
[0-39] ProtocolError: Protocol error (Target.activateTarget): Target closed.
[0-39]     at /home/ferdian/Documents/Automate/web-automation/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Connection.js:230:24
[0-39]     at new Promise (<anonymous>)
[0-39]     at CDPSession.send (/home/ferdian/Documents/Automate/web-automation/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Connection.js:226:16)
[0-39]     at Page._screenshotTask (/home/ferdian/Documents/Automate/web-automation/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Page.js:1984:28)
[0-39]     at /home/ferdian/Documents/Automate/web-automation/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Page.js:1981:62
[0-39]     at processTicksAndRejections (node:internal/process/task_queues:96:5) {
[0-39]   originalMessage: '',
[0-39]   [Symbol(originalCallSite)]: [
[0-39]     CallSite {},
[0-39]     CallSite {},
[0-39]     CallSite {},
[0-39]     CallSite {},
[0-39]     CallSite {},
[0-39]     CallSite {}
[0-39]   ],
[0-39]   [Symbol(mutatedCallSite)]: [
[0-39]     CallSite {},
[0-39]     CallSite {},
[0-39]     CallSite {},
[0-39]     CallSite {},
[0-39]     CallSite {},
[0-39]     CallSite {}
[0-39]   ]
[0-39] }

What should i do for this error? where i must add some setting to add video reporting. Because I read in the documentation say like this:

Adding the Allure reporter as well, automatically updates the reports with videos without any need to configure anything 🙂

I already try use any version of wdio-video-reporter, but it can’t solved.

I expect i can use video reporter that include in allure reporter.

Thankyou.

using Formik lib with next.js

“How can I handle ‘CredentialsSignin’ error in Next.js with Formik and NextAuth, preventing automatic redirection and displaying a custom error message?”

I’m working on a sign-in functionality using Next.js, Formik, and NextAuth. When I include redirect: false in the signIn options, I encounter a ‘TypeError: Failed to construct ‘URL’: Invalid base URL’ in the console. If I remove redirect: false, the app redirects to’http://localhost:3000/auth/signin?error=CredentialsSignin’, but the error message isn’t rendered on the page,

counsol.log mess:Error during sign-in: TypeError: Failed to construct ‘URL’: Invalid base URL
at signIn (react.js:157:19)
at async onSubmit

. How can I handle the ‘CredentialsSignin’ error, prevent the automatic redirection, and display a custom error message without encountering the URL construction error?”

"use client";
// Import necessary modules and components
import { XMarkIcon } from "@heroicons/react/24/outline";
import { Button, Input } from "@material-tailwind/react";
import AuthFormContainer from "@/app/components/AuthFormContainer";
import React from "react";
import Link from "next/link";
import * as yup from "yup";
import { signIn } from "next-auth/react";
import { toast } from "react-toastify";
import { useFormik } from "formik";
import { redirect, useRouter } from "next/navigation";
import { fail } from "assert";

// Define validation schema
const validationSchema = yup.object().shape({
  email: yup.string().email("Invalid email").required("Email is required"),
  password: yup
    .string()
    .min(8, "Password must be at least 8 characters")
    .required("Password is required"),
});

// Component function
export default function SignIn() {
  const router = useRouter();

  // Formik hook to handle form state and validation
  const {
    values,
    touched,
    errors,
    isSubmitting,
    handleSubmit,
    handleBlur,
    handleChange,
  } = useFormik({
    initialValues: { email: "", password: "" },
    validationSchema,
    onSubmit: async (values, action) => {
      try {
        action.setSubmitting(true);

        // Validate form fields using Yup
        await validationSchema.validate(values, { abortEarly: false });

        // Sign in using next-auth

        const signInResponse = await signIn("credentials", {
          ...values,
          redirect: false,
        });
        if (
          signInResponse?.error == "CredentialsSignin" &&
          signInResponse?.status == 404
        ) {
          toast.error("Email OR password mismatch");
          router.push("/auth/signup");
        }

        // Handle other errors or successful sign-in
        if (signInResponse) {
          toast.success("success to sign-in");
          router.push("/");
        }
      } catch (error) {
        console.error("Error during sign-in:", error);
        toast.error("Error during sign-in");
      } finally {
        action.setSubmitting(false);
      }
    },
  });

  // Helper function to check if there are errors for a field
  type valueKeys = keyof typeof values;
  const error = (name: valueKeys) => {
    return errors[name] && touched[name] ? true : false;
  };

  // Render the component
  return (
    <AuthFormContainer title="Sign In" onSubmit={handleSubmit}>
      <Input
        name="email"
        label="Email"
        value={values.email}
        onChange={handleChange}
        onBlur={handleBlur}
        error={error("email")}
        crossOrigin={undefined}
      />
      <Input
        name="password"
        label="Password"
        value={values.password}
        onChange={handleChange}
        onBlur={handleBlur}
        error={error("password")}
        type="password"
        crossOrigin={undefined}
      />
      <Button
        type="submit"
        className="w-full bg-blue-600"
        placeholder="Sign in"
        disabled={
          isSubmitting || Object.values(errors).some((error) => error !== "")
        }
      >
        Sign in
      </Button>
      <div className="flex items-center justify-between">
        <Link href="/auth/signup">Sign up</Link>
        <Link href="/auth/forget-password">Forget password</Link>
      </div>
      <div className="">
        {Object.values(errors).map((item, _index) => (
          <div key={item} className="space-x-1 flex items-center text-red-500">
            <XMarkIcon className="w-4 h-4" />
            {item && <p className="text-xs">{item}</p>}
          </div>
        ))}
      </div>
      <p id="error-message-container" style={{ display: "none" }}>
        Error messages will be inserted here
      </p>
    </AuthFormContainer>
  );
}

/*
import React, { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { toast } from "react-toastify";
import AuthFormContainer from "@/app/components/AuthFormContainer";
import { XMarkIcon } from "@heroicons/react/24/outline";
import { Button, Input } from "@material-tailwind/react";
import * as yup from "yup";

import { signIn } from "next-auth/react";
import startDb from "@/app/lib/db";

interface SignInValues {
  email: string;
  password: string;
}

const validationSchema = yup.object().shape({
  email: yup.string().email("Invalid email").required("Email is required"),
  password: yup
    .string()
    .min(8, "Password must be at least 8 characters")
    .required("Password is required"),
});

export default function SignIn() {
  const router = useRouter();

  const [values, setValues] = useState<SignInValues>({
    email: "",
    password: "",
  });
  const [touched, setTouched] = useState<Record<keyof SignInValues, boolean>>({
    email: false,
    password: false,
  });
  const [errors, setErrors] = useState<Record<keyof SignInValues, string>>({
    email: "",
    password: "",
  });

  const handleBlur = (field: keyof SignInValues) => {
    setTouched({ ...touched, [field]: true });
    validateField(field, values[field]);
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setValues({ ...values, [name]: value });
    validateField(name as keyof SignInValues, value);
  };

  const validateField = async (field: keyof SignInValues, value: string) => {
    try {
      await validationSchema.validateAt(field, { [field]: value });
      setErrors({ ...errors, [field]: "" });
    } catch (error) {
      if (error instanceof yup.ValidationError) {
        setErrors({ ...errors, [field]: error.message });
      } else {
        console.error("Unexpected error type:", error);
        // Handle other types of errors if needed
      }
    }
  };
  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    // Validate all fields before attempting to sign in
    await Promise.all(
      (Object.keys(values) as Array<keyof SignInValues>).map((field) =>
        validateField(field, values[field])
      )
    );

    // Check if there are any errors
    if (Object.values(errors).every((error) => error === "")) {
      try {
        const signInResponse = await signIn("credentials", {
          email: values.email,
          password: values.password,
**          redirect: false,
**        });
        await startDb();
        if (signInResponse?.error) {
          // Handle authentication error
          setErrors({ ...errors, email: "Invalid email or password" });
        } else {
          // Successful sign-in, redirect or update UI as needed
          router.push("/");
        }
      } catch (error) {
        console.error("Error during form submission:", error);
        toast.error("Error during form submission");
      }
    }
  };

  const errorsToRender = Object.values(errors).filter(Boolean);
  type valueKeys = keyof typeof values;

  const { email, password } = values;
  // const error = (name: valueKeys) => {
  //   return errors[name] && touched[name] ? true : false;
  // };
  const error = (name: keyof SignInValues) => {
    return errors[name] && touched[name] ? true : false;
  };

  return (
    <AuthFormContainer title="Sign In" onSubmit={handleSubmit}>
      <Input
        name="email"
        label="Email"
        value={email}
        onChange={handleChange}
        onBlur={() => handleBlur("email")}
        error={error("email")}
        crossOrigin={undefined}
      />
      <Input
        name="password"
        label="Password"
        value={password}
        onChange={handleChange}
        onBlur={() => handleBlur("password")}
        error={error("password")}
        type="password"
        crossOrigin={undefined}
      />
      <Button
        type="submit"
        className="w-full bg-blue-600"
        placeholder="Sign in"
      >
        Sign in
      </Button>
      <div className="flex items-center justify-between ">
        <Link href="/auth/signup">Sign up</Link>
        <Link href="/auth/forget-password">Forget password</Link>
      </div>
      <div className="">
        {errorsToRender.map((item, error) => {
          return (
            <div
              key={item}
              className="space-x-1 flex items-center text-red-500"
            >
              <XMarkIcon className="w-4 h-4" />
              <span className="text-xs">{item}</span>
            </div>
          );
        })}
      </div>
    </AuthFormContainer>
  );
}
*/

Send Automatically Message Appscript Line Notify

I have database google sheet who consist of several sheets. Let say in Sheet 2 has data in the range Sheet 2'!A1:C as pictured below:

enter image description here

My goal is i would like to send message line notify automatically if column Reminder Date (Sheet 2) is equal with date of today at 8 AM.

Before that, i have created App Script in google sheet but it not worked. Following my script:

enter image description here

https://docs.google.com/spreadsheets/d/1y6wJvlxi4WwD4RxpZQ0OpmhhCXCHfjBeZsujiAbQz-w/edit?usp=sharing

Sorry my script i put as picture and sheet because my script can not post in here.

Please give me advice where is the error in my code.

react native Amplify auth confirmSignUp CodeMismatchException

I’m doing my app users management with the Amplify Auth AmazonWebService
I can not figure out how to solve this problem :

After registering, users are receiving an email with a code to confirm it. When I try to send the code I have a Exception message saying “CodeMismatchException: Invalid verification code provided, please try again”.

When I tried the confirmationCode as ” 232353″, it throws ‘confirmationCode’ failed to satisfy constraint: Member must satisfy regular expression pattern: [S]+]

const handleSignUpConfirmation = async ({ username, confirmationCode }) => {
        try {
            const { isSignUpComplete, nextStep } = await confirmSignUp({
                username,
                confirmationCode
            });
        } catch (error) {
            console.log('error confirming sign up', error);
        }
    }



handleSignUpConfirmation({ username: username, confirmationCode: "232353" });

Anyone can help me to solve this error?

How to share the various assets present within the Nuxt 3 project with other Nuxt 3 project in same root folder?

I have a root folder which contains multiple Nuxt 3 projects, with the following folder structure:
root
–ProjectA
–ProjectB

ProjectB extends ProjectA and can use all the components from ProjectA within ProjectB. This is working fine. However, I am unable to use the various images, styles and themes present within the ProjectA/assets and ProjectB/public.

Can someone please let me know how can I use the ProjectA assets and public folder elements within ProjectB?

Following is the ProjectB/nuxt-config.ts which is extending components from ProjectA:

  // auto import components
components: [
  {
    path: '~/components',
    pathPrefix: false,
  },
  {
    path: "../ProjectA/components",
    pathPrefix: false,
  },
],

extends: ["../ProjectA"],


  buildModules: [
    {
      handler: require('../ProjectA/nuxt.config').default,
      vue: {
        config: {
          assetDirs: [
            'assets',
            'public'
          ]
        }
      }
    }
  ],

What additional changes needs to be done to the config so I can directly use the images and public folder elements in ProjectB?

Best Way to do Web Scrapping in React Native [closed]

I am making an app which involves Web scrapping from a certain site that site is popular (social media app)

now, i am using WebView

is there any solution .?

I basically want to Web scrap in react native

want to access the data in a certain div of that website

i have tried many ways,
using WebView inject java
tired to access the dom using it

but does not work

apexcharts update bar width in between column with group label

Hi I’m using apexcharts column group with label. Here’s the sample code from their demo

var options = {
      series: [{
      name: "sales",
      data: [{
        x: '2019/01/01',
        y: 400
      }, {
        x: '2019/04/01',
        y: 430
      }, {
        x: '2019/07/01',
        y: 448
      }, {
        x: '2019/10/01',
        y: 470
      }, {
        x: '2020/01/01',
        y: 540
      }, {
        x: '2020/04/01',
        y: 580
      }, {
        x: '2020/07/01',
        y: 690
      }, {
        x: '2020/10/01',
        y: 690
      }]
    }],
      chart: {
      type: 'bar',
      height: 380
    },
    xaxis: {
      type: 'category',
      labels: {
        formatter: function(val) {
          return "Q" + dayjs(val).quarter()
        }
      },
      group: {
        style: {
          fontSize: '10px',
          fontWeight: 700
        },
        groups: [
          { title: '2019', cols: 4 },
          { title: '2020', cols: 4 }
        ]
      }
    },
    title: {
        text: 'Grouped Labels on the X-axis',
    },
    tooltip: {
      x: {
        formatter: function(val) {
          return "Q" + dayjs(val).quarter() + " " + dayjs(val).format("YYYY")
        }  
      }
    },
    };

    var chart = new ApexCharts(document.querySelector("#chart"), options);
    chart.render();

I want to adjust the width of the bar per group such that the bars above the groupings 2019 and 2020 are almost non existent or much closer to each other.

I tried setting up the columnWidth: '30%' but it is just the bar width that has been adjusted. I want to close the gap in between bars per group.

I also tried computing it using the one posted here in stackoverflow using

var optimalColumnWidthPercent = 20 + (60 / (1 + 30*Math.exp(-seriesLength /3)));
plotOptions: {
  bar: {
    columnWidth: optimalColumnWidthPercent + "%"
  },
},

But it is not the thing I’m looking for. How can I achieve this behavior?