Playwright Error when clicking Anchor Element

I have following anchor Element on the page for which I am writing Playwright Tests

 <a _ngcontent-ng-c643490139="" mat-menu-item="" tabindex="0" class="mat-mdc-menu-item mat-mdc-focus-indicator ng-tns-c2786309385-2 ng-star-inserted" href="/event-partner" role="menuitem" aria-disabled="false" style="">
<span class="mat-mdc-menu-item-text"><span _ngcontent-ng-c643490139="">Eventpartner</span></span><div matripple="" class="mat-ripple mat-mdc-menu-ripple"></div>
<!---->
</a>

Its an anchor Tag with a role of menuitem. Accessing it via following locator should work:

await page.getByRole('menuitem', { name: 'Eventpartner' }).click();

But I get the following error in my Test:

Error: locator.click: Test timeout of 30000ms exceeded.

Call log:

  • waiting for getByRole(‘menuitem’, { name: ‘Eventpartner’ })
    • locator resolved to …
  • attempting click action
    2 × waiting for element to be visible, enabled and stable

    • element is visible, enabled and stable
    • scrolling into view if needed
    • done scrolling
    • … from … subtree intercepts pointer events
    • retrying click action
    • waiting 20ms
    • waiting for element to be visible, enabled and stable
  • element was detached from the DOM, retrying

How can I fix this issue?

The website here removes the Element referred to by locator resolved to in the above error message.

<a tabindex="0" role="menuitem" mat-menu-item="" href="/event-partner" aria-disabled="false" _ngcontent-ng-c2888663785="" class="mat-mdc-menu-item mat-mdc-focus-indicator ng-tns-c2786309385-2 ng-star-inserted">…</a>

Trying to use Mutation Observer, handling “dynamic” objects for page-switching effect

I have a mutation observer set up – it’s meant to track changes in the amount of elements added to a div “box” on the page, and if there are too many visible elements added (more than 6), it’s supposed to add page navigation buttons which would allow to switch between page 2 (elements beyond the 6th one) and back to page one (which shows first 6 elements).

This is achieved by first setting up this “storage” object outside of the mutation observer:

storedNodes = {
    nodesToStay: {
    }, 
    nodesToMove: {
    }
}

Then I make an array by using querySelectorAll on all nodes within this box that fit the “visible” requirement like this: const elementsToStay = Array.from(textField.querySelectorAll(":scope > div:not(.gone)")) and get their IDs with this mapping method: idOfStayingElements = elementsToStay.map(node => node.id)

After that, I sort my nodes like this:

if (elementsToStay.length > 0) {
  for (let i = 0; i < Math.min(6, elementsToStay.length); i++) {
      storedNodes["nodesToStay"][elementsToStay[i].id] = elementsToStay[i];
  }
}

if (elementsToStay.length > 6) {
   const elementsToMove = elementsToStay.slice(6);
   idOfMovedElements = elementsToMove.map(node => node.id);

   for (let i = 0; i < elementsToMove.length; i++) {
        storedNodes["nodesToMove"][elementsToMove[i].id] = elementsToMove[i];
        document.getElementById(idOfMovedElements[i])?.remove();
        delete storedNodes["nodesToStay"][elementsToMove[i].id];
   }
}

Once the amount of keys in the storedNodes[“nodesToMove”] gets to 1 or more, I add page navigation with event listeners.

If “page 2” or “page 1” button is clicked, I use the replaceChildren() on the box holding elements to remove all previously present nodes.

Page 1 button is only supposed to be visible if we’re viewing the second ‘page’ (to allow us to go back to ‘staying’ elements), and Page 2 button is only supposed to be visible if we’re on first ‘page’.

When page 1 is clicked, this happens:

pageOne.classList.add("invisible");
pageTwo.classList.remove("invisible");
for (let id of idOfStayingElements) {
    if (storedNodes["nodesToStay"][id]) {
       textField.appendChild(storedNodes["nodesToStay"][id]);
    }
} 

When page 2 is clicked, this happens:

pageOne.classList.remove("invisible");
pageTwo.classList.add("invisible");
for (let id of idOfMovedElements) {
        if (storedNodes["nodesToMove"][id]) {
           textField.appendChild(storedNodes["nodesToMove"][id]);
        }
    }

Invisible class sets opacity to 0 and visibility to hidden.

The problem is, page 1 event listener doesn’t actually do anything, even though page 2 button works as intended.

As I’ve tested this further, I see that the issue lies specifically in this line: elementsToStay = Array.from(textField.querySelectorAll(":scope > div:not(.gone)"))
As once we get to the next page, all child elements of textField get removed, and we’re only left with elements that were previously stored within elementsToMove… so that becomes the new contents of elementsToStay

I’ve tried to fix this logic by instead making an “allElements” array where format the above-mentioned nodeList, and then tried to extract 1 to 6 elements from allElements to our elementsToStay, but that didn’t fix this behavior as it’s doing the same thing that we were doing before, but in more steps.

At the moment I just need to figure out proper logic for “remembering” what was on the first page, but I’m a bit lost for how I can achieve that at this point.

Here’s the relevant bit of code: https://jsfiddle.net/nj6zk5de/

Here’s the code in bigger scheme of things (starts from line 1477): https://github.com/pilzpuffer/etch-a-sketch/blob/main/script.js

Symfony7 shared installations with cross repo and exclusive feature

I am trying to figure out what is the best approach to a reusable symfony application which has this key feature:

  • It uses a company shared private bundle which is being used in different projects (not just copies of the main app)
  • It has the main app which is the reusable one with optional feature that can be enabled via database
  • Each main app installation can have one or more extra feature bundle (which are extra private GIT repository). The key point here is that it may happen that for one installation i may want FeatureA to be in “beta mode” (so let’s say like a develop branch) while some other installation may still want the feature in “stable mode”. This would bring incoherence in my composer.json file and i can’t find any good solution to this issue.

For example let’s say my company shared private bundle is just a set of services that can handle some common utility tasks. The main app can be something like “stock management” then for some reason one installation may be needed to be used as a base for a book store, the other one for a shop center where each one has their own special needs to add extra feature around the base stock management layer

My question are:

  1. Has this approach have any sense at all? If not, what are the alternatives?
  2. If keeping everything separated as i said is doable, how should i handle different composer.json, assets (css/js), templates and more important symfony routes?

I would accept any answer that leads me to a solid, robust and maintainable long-term solution

I tried approaching the issue by creating 3 different repository: the shared private bundle, the main app and the feature bundle but i can’t seem to find the will to continue before i know if the decision made is solid enough to be used as base structure for the project

PHP variable as reference

I’m confused about the concept of variable in PHP.
As far as I know, a variable in PHP has a name ($p) and a value ('Carlo').

$p has an associated entry in symbol table, such an entry actually points to the memory area where the variable’s value is stored (i.e. the string 'Carlo').

Consider the following:

$n =& $p

$n basically is an alias of $p therefore it points to the memory area where $p points to.

From an “under the hood” viewpoint, does the PHP interpreter create a new entry in symbol table for $nor since it is an alias doesn’t have its own symbol table’s entry ?

Btw, suppose to define class Alpha with its properties and methods. Then does $c = new Alpha actually return a “reference” into the $c variable, in other words is $c value a reference in memory to an instance of class Alpha ?

Performance Regression with Imagick between PHP 7.2 and 8.2

I’m noticing a significant performance difference when running the same Imagick script on PHP 7.2 versus PHP 8.2. Here are the results I’ve gathered:

  • PHP 7.2, ImageMagick 7.0.7, Imagick 3.44: 3.8 seconds

  • PHP 8.2, ImageMagick 7.1, Imagick 3.7: 13.32 seconds

Same spec machine, tested on windows and centos with similar results.

I’m wondering if anyone has encountered similar issues or knows why this change between PHP versions might be affecting Imagick’s performance so drastically? Or know any fixes for this? Below is the test script I’m using (it does this on other functions too not just distorts, this is just an example):

<?php

$startTime = microtime(true);

// Get script directory
$script_path = dirname(__FILE__) . "/";

$controlPoints = [
    1.5,
    0, 0, 355, 70,
    0, 3708, 337, 974,
    1380, 0, 657, 105,
    1380, 3708, 654, 956,
];

echo "Doing Distortion 1n";

$design = new Imagick($script_path . 'input.png');

// Apply distortion
try {
    $design->distortImage(Imagick::DISTORTION_POLYNOMIAL, $controlPoints, true);
} catch (Exception $e) {
    echo "Error applying distortion: " . $e->getMessage() . "n";
}

// Write the distorted image to an output file
$design->writeImage($script_path . "testoutput.png");

$endTime = microtime(true);
$executionTime = ($endTime - $startTime);

echo "Execution Time: " . $executionTime . " secondsn";

Anyone has hints about what’s the problem here? – Laravel eager loading

simple example for my question

As you can see in the screenshot, there’s an error detected by Cursor IDE.

I specified the Model Contract as a type for a variable used in the function giveMeAContract.

But the problem is, at the function wtf() context,
the giveMeAContract() function seems to only want laravel query builder rather than a Model.

Problem is, the error message coming from the red underline says that you have to put a Model in it not the query builder. I think it’s exactly opposite of what I did.

Plus, it only happens when I eager load the collection.

Any hint for this? I solved it by a type hinting annotation but it is just temporary I guess.

Convert Markdown response to HTML

I am getting the output from API in markdown where it could have nested list data and when I am converting this markdown to html it makes all the (-) in list and do not create nested list if there was my output from API is

so please provide me a js function to convert this md to html

TypeScript errors with react-webcam in React application

I’m encountering TypeScript errors when using react-webcam in my React TypeScript project. I’ve followed the official documentation, but I’m still getting Type errors.

Errors

  1. First webcam error:

    Cannot use namespace 'Webcam' as a type.ts(2709)

  • Source of the error:
const webcamRef = useRef<Webcam>(null);
2. *Second webcam error*:

JSX element type 'Webcam' does not have any construct or call signatures.ts(2604) 'Webcam' cannot be used as a JSX component.

My codes:

import React, { useRef } from 'react';
import Webcam from 'react-webcam';


function MyComponent() {
  // Type errors occur here
  const webcamRef = useRef<Webcam>(null);
  
  
  const captureImage = () => {
    if (webcamRef.current) {
      const imageSrc = webcamRef.current.getScreenshot();
      // Do something with imageSrc
    }
  };
  
  return (
    <div>
      {/* TypeScript complains about these components */}

      <Webcam  {/* Second react-webcom occurs here */}
        audio={false}
        ref={webcamRef}
        screenshotFormat="image/jpeg"
        videoConstraints={{ facingMode: 'environment' }}
      />
    </div>
  );
}

I’ve tried importing the types in various ways but haven’t found a solution. Any ideas what might be causing these TypeScript errors?

Problem with slider(Splidejs) scrolling using touchpad on macOS

I made a slider using splidejs, but ran into a problem: on macOS, the slider doesn’t scroll with a horizontal touchpad swipe, even though everything works fine on Windows. What is the problem? Here is an example on jsfiddle: https://jsfiddle.net/p039k4cu/4/

const splide = document.querySelector('.slider');

const interval = 5000; // The autoplay interval duration in milliseconds 
const speed = 1000; // Slider transition speed in ms
const dragMinThreshold = { // Minimum distance in pixels to start dragging
  mouse: 0,
  touch: 10,
};
const flickPower = 500; // Determine the power of "flick". The larger number this is, the farther the carousel runs.
const wheelMinThreshold = 20; // The threshold to cut off the small delta produced by inertia scroll.
const wheelSleep = 500; // The sleep duration in milliseconds until accepting next wheel.

const splideInstance = new Splide(splide, {
  autoWidth: true,
  arrows: false,
  pagination: false,
  updateOnMove: true,
  autoplay: false,
  interval,
  perPage: 1,
  type: 'loop',
  gap: '1rem',
  drag: true,
  dragMinThreshold,
  flickMaxPages: 1,
  flickPower,
  speed,
  snap: false,
  wheelMinThreshold,
  wheelSleep,
});

let lastTime = 0
function onWheel(e) {
  if (e.cancelable) {
    const { deltaX } = e;
    const backwards = deltaX < 0;
    const timeStamp = e.timeStamp;
    const min = splideInstance.options.wheelMinThreshold || 20;
    const sleep = splideInstance.options.wheelSleep || 300;

    if (Math.abs(deltaX) > min && timeStamp - lastTime > sleep) {
      splideInstance.go(backwards ? '<' : '>');
      lastTime = timeStamp;
    }
  }
}

splide.addEventListener('wheel', onWheel);

splideInstance.mount();

PS: I don’t have any macOS device, so I cannot debug. Any help will be very much appreciated.

How do i resolve this drive error issue on my appscript ? How do i improve this program so it can take more large array (can take 40 index on array)?

i have this code that can copy and edit spreadsheet in the same parent folder. A few months ago it still work but now i get this error message “Exception: Service error: Drive“. Here’s the code

var outlet = [
["p1", "place1", "great place 1"], 
["p2", "place2", "great place 2"],
];

function looping() {
    for (var i = 0; i < outlet.length; i++) {
      duplicate(outlet[i][2], i);
      Logger.log(outlet[i][1]);
    }
}

function duplicate(nama, i) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ssid = ss.getId();
  const ssdrive = DriveApp.getFileById(ssid);
  const parent = ssdrive.getParents().next();

  const newss = ssdrive.makeCopy(nama, parent);
  const newurl = newss.getUrl();

  modify(newurl, i);
  debugger;
}

function modify(url, i) {
  const ssopen = SpreadsheetApp.openByUrl(url);
  const range1 = ssopen.getRange("A1");
  const range2 = ssopen.getRange("A2");
  const toko = ssopen.getDataRange();
  const real = outlet[i][1].replace("SPOKE SMG ","").replace(" ","")

  range1.setValue(outlet[i][0]);
  range2.setValue(outlet[i][1]);
  ssopen.setNamedRange(real, toko);
  Logger.log(outlet[i][0]);
  debugger;
}

sorry for the messy language

Scenario reads old data from the previous run

What I am trying to achieve is that it should filter users’ data in the first scenario which is currently working well and save in csv file which is also working.
When the 2nd scenario execution begins, it should read filtered data and run tests. This is not working as expected as it reads old data from the previous run. I have to run test twice for the desired result.

I am currently facing this challenge and wondering if you might be able to help me out. I’d appreciate any guidance or advice you could offer. Please suggest some better way of doing it. I have an alternative approach to handle this using

gauge.dataStore.scenarioStore.put("filteredUsers", filteredUsers).

But I want to see if the same can be achieved with csv as DataStore makes troubleshooting harder if there are many rows in a table. Thanks.

This is my spec file written in Gauge.

The problem lies in scenario 2
table: test_dataQA3users.csv

# Verify users
tags: filter

// scenario 1
## Populate CSV with users based on role
* Filter users data based on role
    |id     |name       |role       |
    |-------|-----------|-----------|
    |1      |Alice      |admin      |
    |2      |John       |editor     |
    |3      |Bob        |admin      |
    |4      |Shawn      |subscriber |
    |5      |Eve        |admin      |
    |6      |Tom        |editor     |
    |7      |Jenny      |author     |   

// scenario 2
## Verify the filtered users
table: test_dataQA3users.csv
* Show filtered users based on role on the console <id>, <name>, <role>

———————STEP IMPLEMENTATION———————-

"use strict"

const fs = require('fs');
const path = require('path');
const csv = require('csv-parser');

const filePath = path.join(process.cwd(), "test_data/QA3/users.csv");

beforeSpec(() => {
    if(fs.existsSync(filePath)) {
        // delete the existing file if it exists
        fs.unlinkSync(filePath);
        console.log("Deleted existing csv file");
    }
}, {tags: ["filter"]});

step("Filter users data based on role <table>", async (table) => {
    let testData = [];

    for(let i=0;i<table.rows.length;i++) {
        let obj = {
            id: table.rows[i].cells[0],
            name: table.rows[i].cells[1],
            role: table.rows[i].cells[2]
        }
        
        testData.push(obj);
    }

    console.log(testData)

    console.log(`ROLE from env: ${process.env.ROLE}`);

    let selectedRoles = process.env.ROLE ? process.env.ROLE.split(",").map(role => role.trim().toLowerCase()) : [];

    let filteredUsers;
    if(selectedRoles.length === 0) {
        console.log("No Role specified. Loading all users data");
        filteredUsers = testData; // Run all users data
    }else {
        console.log(`Filtering users based on roles: ${selectedRoles.join(",")}`);
        filteredUsers = testData.filter(user => selectedRoles.includes(user.role.toLowerCase()))
    }

    let csvContent = "id,name,rolen" + filteredUsers.map(u => `${u.id},${u.name},${u.role}`).join("n");

    try {
        // write filtered data to csv file synchronously
        fs.writeFileSync(filePath, csvContent, "utf8");
        console.log("Filtered data saved");
    } catch (err) {
        console.log("Error writing to CSV file", err);
    }

    new Promise(resolve => setTimeout(resolve, 300));
})

step("Show filtered users based on role on the console <id>, <name>, <role>", async (id,name,role) => {
    console.log(`ID is ${id}`);
    console.log(`Name is ${name}`);
    console.log(`Role is ${role}`);
});

——————————x—————————–

I am using following command to run test

set ROLE=editor && gauge run specsVerify_users2.spec --tags "filter"

ROLE is defined in properties file.

Handling CORS for publicly deployed npm package

I’m developing a npm package intended to be used in FrontEnd web. This package makes an API call to my Backend server. How can I handle CORS in my backend as the package will be used by others in their own domains?. I don’t want to store and whitelist the domains from everyone.

can i get page impression data of particular account using facebook market Ad Account, Insights facebook market api

can i get page based impression data of particular account using this api https://graph.facebook.com/v19.0/act_245199783381840/insights? just like Facebook platform
see following Facebook platform image

when i am using this API i’m getting response but it doesn’t have pages data…i want to see impression data by page wise

enter image description here