How to launch an actual incognito window using playwright?

Our application is setup in such a way that the chrome browser by default will take my system credentials to launch the application. With playwright, the browser is detecting my user profile and unable to use test user account. I wanted to launch an actual incognito window and login as a ‘X’ test user and perform my testing scenarios.

FYI: I am able to achieve this manually but wanted to see if I could automate this.

FYI: I tried using browser.newContext() method but it is not working.

Any inputs please?

I tried using browser.newContext() method but it is not working.

How to add hours to “real-time” time? [duplicate]

I am building this weather app and want to display the temperature at current time, and also in the next few hours throughout the day, but I quickly run into the following problem:

I’ve chosen to display 5 more temperatures of 3 hours gap in between them, so you can see the temperature right now, in 3 hours from now, 6 hours from now and so on.
When by just adding 3 to the real time it surplus the 23 hour limit and goes to 24:00, 25:00 etc.
as seen in the picture, How can I prevent this?

enter image description here

let now = new Date();

let date = document.querySelector("#date");

let days = [
  "Sunday",
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday",
];
let day = days[now.getDay()];
let hour = now.getHours();
let minutes = now.getMinutes().toString().padStart(2, "0");

date.innerHTML = `${day} ${hour}:${minutes}`;

let hour1 = document.querySelector("#hourly1");
let hours1 = hour + 3;
hour1.innerHTML = `${hours1}:00`;

let hour2 = document.querySelector("#hourly2");
let hours2 = hour + 6;
hour2.innerHTML = `${hours2}:00`;

let hour3 = document.querySelector("#hourly3");
let hours3 = hour + 9;
hour3.innerHTML = `${hours3}:00`;

let hour4 = document.querySelector("#hourly4");
let hours4 = hour + 12;
hour4.innerHTML = `${hours4}:00`;

let hour5 = document.querySelector("#hourly5");
let hours5 = hour + 15;
hour5.innerHTML = `${hours5}:00`;

Have an error: “Column with id ‘id’ does not exist.” by @tanstack/vue-table (vue3)

I have a red error in a Browser console when creating a table by @tanstack/vue-table. It is error is not critical. If I change ‘name’ -> ‘id’ – do not have an error, but I do not need to show ‘id’ in my table from data). How can I hide/fix ‘Column with id ‘id’ does not exist.’ error?

My settings from official docs:

const columnHelper = createColumnHelper<any>();
const columns = [
  columnHelper.accessor('name', {
    header: 'Name'
  }),
];

why is my code fetching the same items twice when the page is loaded?

I am learning React and trying to fetch some data for a product list.

It is supposed to fetch only 2 items at first and fetch 2 more items when pressing the button, but it is now fetching the same items twice when the page is loading at first.

import { useEffect, useState, Fragment } from 'react';
import './style.css';

export default function LoadMoreData() {
  const [loading, setLoading] = useState(false);
  const [products, setProducts] = useState([]);
  const [count, setCount] = useState(0);
  const [disableButton, setDisableButton] = useState(false);

  const loadLimit = 10;
  let limit = 2;

  async function fetchProducts() {
    const dataUrl = `https://dummyjson.com/products?limit=${limit}&skip=${
      count === 0 ? 0 : count * limit
    }`;

    try {
      setLoading(true);
      const response = await fetch(dataUrl);
      const result = await response.json();

      if (result && result.products && result.products.length) {
        setProducts((prevData) => [...prevData, ...result.products]);
        setLoading(false);
      }

      console.log(result);
    } catch (e) {
      console.log(e);
      setLoading(false);
    }
  }

  useEffect(() => {
    fetchProducts();
  }, [count]);

  useEffect(() => {
    if (products && products.length === loadLimit) setDisableButton(true);
  }, [products]);

  if (loading) {
    return <div>Loading data! Please wait.</div>;
  }

  return (
    <Fragment>
      <div className='load-more-container'>
        <div className='product-container'>
          {products && products.length
            ? products.map((item) => (
                <div className='product' key={item.id}>
                  <img src={item.thumbnail} alt={item.title} />
                  <p>{item.title}</p>
                  <span>$ {item.price}</span>
                </div>
              ))
            : null}
        </div>
        <div className='button-container'>
          <button disabled={disableButton} onClick={() => setCount(count + 1)}>
            Load more products
          </button>
          {disableButton ? (
            <p>You have reached to {loadLimit} products!.</p>
          ) : null}
        </div>
      </div>
    </Fragment>
  );
}

I thought the bug maybe because I put the async function outside the useEffect, but still couldn’t solve the problem even though put it in the useEffect

can anyone give me a hint where the bug would be? Thank you

Use Google reCAPTCHA v3 to conditionally load Dynamics Real-time Marketing Form in WordPress?

I have a Real-time marketing form from Dynamics 365 that I have embedded on my WordPress website via JavaScript in a raw code block via Elementor pagebuilder. I want to add a reCAPTCHA check, but I do not want to implement Dynamic form’s default captcha or their method for integrating Google reCAPTCHA. Instead, I want to know if it is feasible to only load the form when users pass the reCAPTCHA check.

Is this doable? And how would one go about achieving this?

Please let me know, any help or insight is appreciated, thank you!

I have checked the reCAPTCHA v3 documentation where it explains you can programmatically invoke the challenge which I understand. However, I do not understand how I can conditionally prevent the embedded form from loading. If someone can provide their insight on this that’d be great!

How to find object without existing property with JSONPath

I have the following json :

{
  "data": [
     {
       "name": "Peter",
       "excluder": 1
     }, 
     {
       "name": "Sansa"
     }
  ]
}

I want to obtain only elements without excluder property, using JSONPath or extended package jsonpath-plus :

[
  {
    "name": "Sansa"
  }
]

I know I can filter on elements with property excluder with $.data[?(@.excluder)]

Is it possible to filter on the non existance of a property ?

NavBar component isnt re-rendering when pinia store computed property is being changed (vue)

So i’m implementing an authentication in my project. (with firebase). I use vue(composition API), and pinia store.

I have very basic NavBar component with part of it looking like this:

<router-link to="/signin" v-if="!authStore.isAuth">
        <b>Login</b>
      </router-link>
      <router-link to="/signin" v-if="authStore.isAuth" @click.prevent="logout">
        <b>Logout</b>
      </router-link>`

The pinia store part looks like this:

export const useAuthStore = defineStore("auth", () => {
  const userInfo = ref({
    token: "",
    userId: "",
    refreshToken: "",
    expiresIn: "",
    userProfileData: {},
  });

  const isAuth = computed(() => {
    if (userInfo.value.token === "") {
      return false;
    } else {
      return true;
    }
  });

So when user logins, my NavBar component still has Login link. It doesnt re-render at all. It only works when i REFRESH the page, then it works.
In dev tools, isAuth always changes when user logins. And its value displayed correctly in console when i click debug button that i made on my NavBar. I tried to use “storeToRefs” like that:

const { userInfo } = storeToRefs(authStore);

const isAuth = computed(() => {
  return userInfo.value.token !== "";
});

and then in template:

<router-link to="/signin" v-if="!isAuth">
 <b>Login</b>
</router-link>

Nothing seems to be working.
Also tried removing computed property, adding computed in the NavBar component etc etc. It all doesnt work. NavBar component just doesnt reflect any changes in store. Why isnt it reactive? How to make it reactive? What is the common and correct way to do that?

How to Make React Skeleton Loader Responsive with Different Line Counts for Desktop and Mobile?

I’m currently working on a React project where I’m using react-loading-skeleton to implement loading skeletons. I would like to make the skeleton responsive so that it displays a different number of lines depending on the screen size. Specifically, I want to show:

  • 3 lines on desktop screens
  • 5 lines on mobile screens

This is to maintain the content’s height and avoid any sudden layout shifts when the actual content loads.

Here is a simplified version of my code:

{loading ? (
  <SkeletonTheme baseColor="#222222" highlightColor="#000">
    <Skeleton height="24px" count={3} width="100%" borderRadius="4px" />
  </SkeletonTheme>
) : (
  <MyText>
    Lorem ipsum dolor sit amet consectetur, adipisicing elit. Suscipit, dolor. Lorem ipsum 
    dolor sit amet consectetur, adipisicing elit. Suscipit, dolor. Lorem ipsum dolor sit 
    amet consectetur, adipisicing elit. Suscipit, dolor?
  </MyText>
)}

How can I modify the skeleton loader to display 3 lines on desktop and 5 lines on mobile while maintaining the content’s height to avoid jumping content?

Swiper.js changes slides incorrectly. How does the slideNext and slidePrev methods work?

I have custom carousel with 3 elements, active element of it is bigger than other elements.

When I click to the next/prev slide, its seems like ±translate-x-[calc(size-of-active-element+some-space)].

Here is the video. I fixed the screen shaking issue.

Here is my code

{/* Other stuff */}
<div className="w-full relative">
                <Swiper
                    slidesPerView={1}
                    spaceBetween={10}
                    loop={true}
                    slideToClickedSlide={true}
                    navigation={{
                        nextEl: '.no-bro',
                        prevEl: '.yes-bro',
                    }}
                    modules={[Navigation]}
                    breakpoints={{
                        1280: {
                            slidesPerView: 3,
                            spaceBetween: 20,
                        },
                        728: {
                            slidesPerView: 2,
                            spaceBetween: 20,
                        },
                    }}
                >
                    {test.map(image => (
                        <SwiperSlide key={image.id} className="bg-secondary">
                            {({ isActive }) => (
                                <div
                                    className={cn(
                                        'transition-all ease-in-out',
                                        isActive ? 'w-[450px] h-[460px]' : 'w-[310px] h-[380px]'
                                    )}
                                >
                                    {image.id}
                                </div>
                            )}
                        </SwiperSlide>
                    ))}
                </Swiper>
                {/* Other stuff */}
            </div>
{/* Other stuff */}
.swiper-slide {
    width: max-content !important;
}

I had to change ‘.swiper-slide’ constraints so its child element could have right size.

I tried to fix it without changing ‘.swiper-slide’ by setting size and absolute position to ‘.swiper-active-slide > child-element‘, but its grand-parent ‘.swiper’ has ‘overflow-hidden’, and setting it to visible shows other elements of list view that dont need to be seen.

Setting ‘loop={false}’ does not help.

Help please. I use Next.js/Tailwind/Swiper.js btw.

Three js inside and outside wheel and keydown

I have more than one canvas on an html page. Each canvas has a different scene. Some of them display a cube of images, and after them there is some html div, and then another canvas with movement that depends on the movement of the mouse and key down. How do I control the movement images of the mouse outside the page, then the movement of the mouse inside the canvas after reach the canvas, and after completing the movement of the canvas, it returns Control to browse the rest of the page, noting that I want to start moving inside the Canvas after reaching the Canvas

in few words: when scrolling or key down when arrive to specific canvas start the movement inside the canvas and after movement complete continue scrolling the other parts of the page and I need do reverse the movement when click on key up or weel other side and after reach the first of the movement continue to above parts of the page

I tried everything and when wheel or key down the page and canvas move together

How to access the data via context menu in uplot-vue graph

I have a simple graph with data plotted from 5 different features showing their speed over time. When a user right clicks on data on the graph, I display a context menu with a few options, one of them being a simple “Get Info” option where I’d like to display a dialog containing more detailed data about the feature they clicked on.

I’m having a hard time getting to the data within the graph. So far I have tried using the uplot cursor.idxs to get the location of the click from this example with no success:
https://jsfiddle.net/w07t8q4g/

I am not sure how to accomplish this. Can anyone help? Thanks so much!

This is my component code so far:

<template>
<div @contextmenu.prevent="showContextMenu($event)">
  <ContextMenu
      v-model="showMenu"
      :x="menuX"
      :y="menuY"
      :actions="contextMenuActions"
      @action-clicked="handleMenuAction"
    />
      <v-main class="pa-0">
        <v-container fluid >
              <v-card >
                <div id="uplot-Container" style="min-height: 350px; max-height: 400px;">
                <UplotVue ref="timelineContainer" :options="options" :data="plotData" :key="graphKey" />
              </div>
              </v-card>
        </v-container>
      </v-main>
</div>
</template>

<script setup>
import {onMounted, onUpdated, ref, watch} from 'vue'
import "uplot/dist/uPlot.min.css";

import UplotVue from 'uplot-vue';
import ContextMenu from '@/components/ContextMenu.vue';
import {useState} from "@/store/State"
const stateStore = useStateStore()

import {storeToRefs} from 'pinia'

const graphKey = ref(0)
const timelineContainer = ref(null)
const height = ref(null)
const width = ref(null)

const showMenu = ref(false)
const menuX = ref(0)
const menuY = ref(0)

const contextMenuActions = ref([
  { label: 'Get Info', action: 'getInfo', icon: 'mdi-information-box-outline', disabled: false },
  { label: 'Sync', action: 'sync', icon: 'mdi-autorenew', disabled: false },
]);

const plotData = stateStore.plotData

const showContextMenu = (event) => {
  //the context menu adds pixels to the x and y to show it offset, so get the correct pixel that was actually right clicked to find feature
  event.preventDefault()

  //this is the pixel location for the menu based on where the user right clicked and what gets passed to the contextMenu component for placement on screen.
  menuX.value = event.clientX
  menuY.value = event.clientY
  showMenu.value = true
}

function handleMenuAction(action){
  console.log(action)
  console.log('x: '+menuX.value + ' ' +'y: '+menuY.value)`enter code here`
  if (action === 'getInfo') {
    //Get the feature's data at the location of the click

//THIS DOESN'T WORK - TypeError: Cannot read properties of undefined (reading 'idxs')
    const [xIdx, yIdx] = timelineContainer.value.cursor.idxs

    const xVal = timelineContainer.value.data[0][xIdx]
    const yVal = timelineContainer.value.data[1][yIdx]
    const xPos = timelineContainer.value.valToPos(xVal, 'x');
    const yPos = timelineContainer.value.valToPos(yVal, 'y');
    let popup = document.createElement("div");
    popup.classList.add("popup");
    popup.textContent = yVal;
    popup.style.left = xPos + "px";
    popup.style.top = yPos + "px";

    timelineContainer.value.over.appendChild(popup);
  }
}

const options = ref({
  Title: "Plotted Data",
    drawOrder: ["series", "axes"],
    axes: [
      {
        side:0,
        stroke: "white",
        ticks: {
          stroke: "#808080"
        },
        grid: {
          stroke: "rgba(236, 236, 236, 0.5)"
        }
      },
      {
        stroke: "white",
        ticks: {
          stroke: "#808080"
        },
        grid: {
          stroke: "rgba(236, 236, 236, 0.5)"
        },
        
      }
    ],
    series: [
      {
        label: 'Timstamp'
      },
      {
        label: 'CM',
        stroke: "red",
        width: 4
      },
      {
        label: "NC",
        stroke: "green",
        width: 4
      },
      {
        label: "OE",
        stroke: "blue",
        width: 4
      },
      {
        label: "SB",
        stroke: "orange",
        width: 4
      },
      {
        label: "ST",
        stroke: "yellow",
        width: 4
      },
    ],
    scales: { x: { time: true } },
  },)



onUpdated(() => {
  graphKey.value++
  const element = document.getElementById('uplot-Container')
  const positionInfo = element.getBoundingClientRect()
  const height = positionInfo.height
  const width = positionInfo.width
 
  options.value = {
    ...options.value,
    height: height - 50,
    width: width - 30
  }
})

onMounted(() => {
 console.log(plotData.value)
})

This is what the graph looks like with the 5 different features and its data over time

How to enable a submit button if form fields are auto-filled by the browser using saved credentials on page load?

I’m working on a login form where the submit button should be enabled only if both the username and password fields are filled. My current JavaScript code works fine when the user manually enters the credentials or if they are auto filled by the browser at a later stage, but it doesn’t work as expected when the fields are pre-filled by the browser’s saved credentials upon page load.
Here’s my code in the script tag inside a razor file:

function validateForm() {
    var username = document.getElementById('Username').value;
    var password = document.getElementById('Password').value;
    var submitButton = document.getElementById('ActionSubmit');

    if (username && password) {
        submitButton.disabled = false;
        submitButton.style.backgroundColor = '#abcdef';
        submitButton.style.color = '#000000';
        submitButton.style.cursor = 'pointer';
    }
    else {
        submitButton.disabled = true;
        submitButton.style.backgroundColor = '#fedcba';
        submitButton.style.color = '#ffffff';
        submitButton.style.cursor = 'not-allowed';
    }
}

document.getElementById('Username').addEventListener('input', validateForm);
document.getElementById('Password').addEventListener('input', validateForm);

window.addEventListener('load', function () {
    validateForm();
});

The submit button remains disabled if the browser automatically fills in the username and password fields using saved credentials when the page loads. The button only gets enabled if the user manually interacts with the page (even a simple click anywhere on the screen fixes it) after the page has loaded.

I suspect this issue occurs because my validateForm function is executed before the browser has a chance to populate the fields with the saved credentials, and since no further interaction happens, the function doesn’t get called again.

Any advice on handling this would be greatly appreciated!

How to implement a Javascript confirm dialog in Selenium JavascriptExecutor

Is it possible to return a value from a Javascript confirm dialog via Selenium JavascriptExecutor ?
so the test code can determine if tester clicks OK or Cancel ?
I tried this code:

    JavascriptExecutor js = (JavascriptExecutor) driver;

    String result =
        (String)
            js.executeScript(
                "var confirmed = confirm('Press a button Either OK or Cancel'); return confirmed ? 'true' : 'false';");

   WebDriverWait waitForAlert = new WebDriverWait(driver, Duration.ofSeconds(10));
   waitForAlert.until(ExpectedConditions.not(ExpectedConditions.alertIsPresent())); 

   System.out.println("Confirmed: " + result);  // null

Seems like the confirm dialog is running asynchronously so
assignment for the return variable happens before the dialog has returned anything.

Getting javax.crypto.BadPaddingException: Decryption error in Java backend while decrypting Encrypted Text from JavaScript frontend using node-forge

I am generating RSA Key pair of 2048 key size in Java as shown below:

public KeyPair generateRSAKeyPair() {
        KeyPair pair = null;
        try {
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
            generator.initialize(2048, new SecureRandom());
            pair = generator.generateKeyPair();
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return pair;
    }

I am using above key for encryption and decryption in backend and sending it to frontend and using same for other RSA encryptions which are working fine but now I am using node-forge library for doing ‘RSA-OAEP’ encryption in frontend and I want to decrypt it in backend in java using Algorithm – ‘RSA/ECB/OAEPWithSHA-256AndMGF1Padding’ but I am getting ‘javax.crypto.BadPaddingException: Decryption error’ Exception. I tried everything suggested in other similar node-forge encryption and java backend decryption questions and solutions suggested on Stack overflow, github, etc but nothing is working. I also tried using ‘md – SHA 256’ and ‘mgf1 SHA 1’ as well as ‘mgf1 SHA 256’ in both frontend JS node-forge encryption as well as backend but nothing seems to be working. I also tried using Bouncy castle but then it gave illegal block exception or something.

Below is front end side node-forge encryption:

{
  // var publicKey = forge.pki.publicKeyFromPem("-----BEGIN PUBLIC KEY-----n" + rsaPubKey + "n-----END PUBLIC KEY-----");
        var pemPublicKey=convertBase64ToPem(rsaPubKey);
        var publicKey=forge.pki.publicKeyFromPem(pemPublicKey);
        // var strKeyValueBytes = forge.util.createBuffer(strKeyValue).getBytes();
        var encKeyValue = forge.util.encode64(publicKey.encrypt(strKeyValue, 'RSA-OAEP', {
            md: forge.md.sha256.create(),
            mgf1: {
                md: forge.md.sha1.create()
            }
        }));
    }
function convertBase64ToPem(base64Key){
    var derKey=forge.util.decode64(base64Key);
    var asn1Obj=forge.asn1.fromDer(forge.util.createBuffer(derKey, 'binary'));
    var publicKey=forge.pki.publicKeyFromAsn1(asn1Obj);
    return forge.pki.publicKeyToPem(publicKey);
}

As seen above, I tried multiple ways to convert string rsa public key generated in Java backend to node-forge public key and it is working fine and encrypting fine but in decrypting when I use Private key in backend, I am getting exception. I checked modulus and exponent on frontend and backend and the key is fine and same on frontend as the one in backend but still I am getting exception. I tried more than 15 questions and solutions mentioned in those on Stack overflow alone

Below is backend side code where I decrypt node-forge encrypted data using ‘RSA/ECB/OAEPWithSHA-256AndMGF1Padding’ Algorithm:

{

                            OAEPParameterSpec oaepParameterSpec = new OAEPParameterSpec("SHA-256", "MGF1",
                                    MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT);
                            
                            Provider bcProvider = new BouncyCastleProvider();
                            Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding"); /// ECB/OAEPWithSHA-256AndMGF1Padding
                            PrivateKey pvtKey = (PrivateKey)httpSession.getAttribute(ISecurityConstants.RSA_PRIVATE_KEY);

                            if(null  != cipher && null != pvtKey ){
                                cipher.init(Cipher.DECRYPT_MODE, pvtKey, oaepParameterSpec);
//                                cipher.init(Cipher.DECRYPT_MODE, pvtKey);
                                String keyValue = new String(cipher.doFinal(java.util.Base64.getDecoder().decode(encKeyValue)));
                                if(!keyValue.trim().isEmpty()) {
                                    httpSession.setAttribute(localKeyName, keyValue);
                                    responseMsg = "success";
                                }
                            }

                        }

As you can see, above I have tried manually setting OAEPParameterSpec to try encryption and decryption with MGFI SHA 256 as well as MGFI SHA 1 but nothing is working, I also tried changing provider and using BouncyCastleProvider instead of default provider but still I am getting exception.

I am not able to resolve this at all. Please help me resolve this issue. I am so stressed and frustrated like I literally have tried every solution suggested online and on AIs like Gemini and Chatgpt but nothing is working.

Please help me resolve this issue. Your help is highly appreciated.