Reloading with frequent clicking on the Profile button

When I click on the profile link multiple times, the page keeps reloading and sending lots of requests before finally redirecting to the profile. How can I prevent the page from reloading and make it instantly follow the link??
I tried switch <a> on <Link> next js, but i’m not sure if CSS styling will be affected.

const NavProfile = () => (
        <>
            <NavbarLink href="/profile">
                <UIIcon
                    name="card"
                    className={styles.iconCard}
                />
                Основное
            </NavbarLink>
            
}

export const NavbarLink = ({ href, children, css, activePaths = [], target }) => (
    <li>
        <ActiveLink
            activePaths={activePaths}
            href={href}
            css={css}
            target={target}>
            {children}
        </ActiveLink>
    </li>
);
function ActiveLink({
    css,
    href,
    onClick,
    nofollow,
    includedPath,
    children,
    className,
    activePaths = [],
    changeLocation = true,
    allowAllPathsToBeActive,
    target
}) {
    const router = useRouter();

    const handleClick = e => {
        if (target !== "_blank") {
            e.preventDefault();

            if (onClick) onClick(e);

            if (changeLocation) router.push(href);
        }
    };

    const pathIncludesHref = (path, href) => {
        return (
            path.split("?")[0] === href ||
            path.split("#access_token")[0] === href ||
            path.split("access_token")[0] === href
        );
    };

    let active = "false";

    let path = router.asPath.split("/");
    if (path[path.length - 1] === "#") {
        path.pop();
    }
    path = path.join("/");
    path = path ? path : "/";

    if (
        pathIncludesHref(path, href) ||
        activePaths.includes(path) ||
        (allowAllPathsToBeActive && path.indexOf(href) !== -1) ||
        (includedPath && path.split("?")[0].includes(includedPath))
    ) {
        active = "true";
    }

    return (
        <a href={href} className={className} onClick={handleClick}
            active={active}
            target="_blank"
            style={css}>
            {children}
        </a>
    );
}

Why is this RxJS subscription never closed?

I have suspected memory leaks and stale RxJS subscriptions for a while in corporate software. I decided to investigate by writing the snippet below. It’s very simple. First, it loads RxJS. Second, it monkey patches Observable’s subscribe method in order to spy on it and monitor what’s going on. Third, I create the following subscription:

rxjs.interval(1_000).pipe(rxjs.take(3)).subscribe()

It’s just an Observable which emits one value every second and stop after three values. My monkey patched subscribe method reveals a few things. One of them is that this is not one subscription but two. Not very surprising, we have a pipe and so each operator (here only take(3)) will create an Observable subscribing to the previous one (here internal(1_000)).

But it reveals another much more surprising fact. After the three values have been emitted, one subscription is closed but not the other. It looks like the “source”, so interval(1_000), remains active forever. You can try for yourself using the snippet below. You will see both subscriptions printing the first three values to the console and then only one of them remains and keeps printing without stopping. I would expect both subscriptions to be closed. Why is it not the case?

// This script monkey patches Observable's subscribe method to spy on it

let subscriptionCount = 0;

const observables = [];
const subscriptions = [];
const values = [];

const originalSubscribe = rxjs.Observable.prototype.subscribe;

Error.stackTraceLimit = Infinity;

rxjs.Observable.prototype.subscribe = function(observerOrNext, error, complete) {
    if (!this.id) {
        this.id = observables.length;
        observables.push(this);
    }

    const subscriptionId = subscriptionCount++;

    const interceptValue = value => {
        console.log(`Subscription ${subscriptionId}: ${value}`);

        values[subscriptionId] = values[subscriptionId] || [];
        values[subscriptionId].push(value);

        if (subscriptions[subscriptionId]) {
            subscriptions[subscriptionId].lastValueDate = Date.now();
        }
    };

    let observer;
    if (typeof observerOrNext === 'function') {
        observer = value => {
            interceptValue(value);
            observerOrNext(value);
        };
    } else {
        observer = {
            next: value => {
                interceptValue(value);
                observerOrNext?.next?.(value);
            },
            error: err => {
                observerOrNext?.error?.(err);
            },
            complete: () => {
                observerOrNext?.complete?.();
            }
        };
    }

    const subscription = originalSubscribe.call(this, observer, error, complete);
    subscription.id = subscriptionId;
    subscription.observableId = this.id;
    subscription.creationDate = Date.now();
    subscription.trace = new Error().stack;
    subscriptions.push(subscription);

    return subscription;
}

// Here is the actual MRE

rxjs.interval(1_000).pipe(rxjs.take(3)).subscribe();
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/7.8.2/rxjs.umd.js"></script>

viewer._pages unexpectedly becomes empty in PDF.js PDFViewer instance

I’m integrating pdfjs-dist’s PDFViewer in a React project using the pdfjs-dist/web/pdf_viewer module. Everything works fine initially — the PDF loads, the pages render, and I’m able to interact with them.

However, at some point later in the flow, I’m noticing that viewer._pages (which initially holds all page references) becomes unexpectedly empty ([]). This is causing issues with a custom updateVisiblePages function I wrote to hide/show certain pages based on user interaction.

const updateVisiblePages = useCallback(
        (viewer: any) => {
            console.log(viewer, 'viewer updateVisiblePages before return')

            if (!viewer || !viewer._pages.length) return
            console.log(viewer, 'after return')
            const allPages = viewer._pages
            let updated = false
            allPages.length !== 0 &&
                allPages.forEach((page: any, index: number) => {
                    const pageNum = index + 1
                    if (!isSearchActive) {
                        if (
                            pageNum < (Number(selectedContent.startPage) ?? 1) ||
                            pageNum > (Number(selectedContent.endPage) ?? allPages.length)
                        ) {
                            if (!page.div.classList.contains('hidden-page')) {
                                page.div.classList.add('hidden-page') // Add class to hide
                                updated = true
                            }
                        } else {
                            if (page.div.classList.contains('hidden-page')) {
                                page.div.classList.remove('hidden-page') // Remove class to show
                                updated = true
                            }
                        }
                    } else {
                        if (page.div.classList.contains('hidden-page')) {
                            console.log(
                                '[DEBUG] Pages updated, removing hidden-page class when searching',
                            )
                            page.div.classList.remove('hidden-page') // Remove class to show
                            updated = true
                        }
                    }
                })

            if (updated) {
                viewer.update() // Ensure the viewer updates its rendering
                setVisiblePagesUpdated((prev) => !prev) // Trigger re-render
                updateHeight()
                window.addEventListener('resize', updateHeight)
                return () => window.removeEventListener('resize', updateHeight)
            }
        },
        [selectedContent, isSearchActive],
    )

And I’m setting up the viewer like this inside a useEffect:

const viewer = new PDFViewer({
    container: container,
    eventBus: eventBusInstance,
    enableWebGL: true,
    renderInteractiveForms: true,
    textLayerMode: 2,
    enhanceTextSelection: true,
});

viewer.setDocument(pdfDoc);

My questions:

What can cause viewer._pages to become empty after the PDF is loaded?

Is there a lifecycle method or event I should hook into to prevent accessing _pages at the wrong time?

Is there a better/official API for tracking rendered pages instead of relying on _pages (which I realize is a private field)?

Any help in understanding when or why _pages gets reset/cleared would be greatly appreciated!

I am having problems in integrating laravel with react should i keep on trying or shift the backend? [closed]

So I am having problems in integrating laravel with react there are only two errors that pop up with no solution even from chatgpt its either

  1. 404 | Not Found
  2. A blank page with the following lines in the terminal
    SyntaxError: Unexpected token ‘<‘, “<!DOCTYPE “… is not valid JSON

What should I do because at this point I have tried everything….

Every possible solution I could find

How can I execute a SQL-Select-Statement against a table in memory in SQL.js?

I use SQL.js and I need a solution in this framework.

I want to execute a SELECT-Statement against a table I retrieved from the database. Is there any way to achieve this?

I tried so far:

let table = db.exec("select * from Person")[0];
let res = db.exec("select * from @table", {"@table": table});

I’m aware that I could simply write db.exec("select * from Person") in this special case, but this is a simplified example. In my use case I get the table from another source.

How to create a trusted event of dragging a file into a drag-zone input using Playwright

In a Playwright test, I have an input field that is marked as a drag-and-drop zone for files that I want to test our logic on.

When trying to use Playwright’s page.dispatchEvent of drop, the created event has the value of isTrusted === false which is bad for me. Here’s a typescript example:

const buffer = readFileSync('file.txt')
const dataTransfer = await page.evaluateHandle(async (data) => {
    const dt = new DataTransfer();
    const file = new File([data], 'file.txt', { type: 'text/plain' })
    dt.items.add(file)
    return dt
}, buffer)

await page.dispatchEvent("#drag-area", "drop", { dataTransfer });

Another attempt was to use locator.dragTo from a custom element, but I couldn’t manage to add my file to the items.dataTransfer object – the element’s event listener did not contain my file after adding to event.dataTransfer.items

(This is a follow-up to this question: How to drag a file to a drag-zone input element using Playwright.
I have also checked out the Playwright issue about this to no avail: https://github.com/microsoft/playwright/issues/10667#issuecomment-998397241)

So, my question is, how do I create a drag-file event in Playwright with the property event.isTrusted=true and with a custom file?

Question to behavior of JS addEventListener (Seems to double fire)

I was looking to open a dropdown by button-click and close it when there is a click anywhere in the DOM (except dropdown). Now for some reason the way i was trying that did result in the event firing apparently twice. I was wondering why? Here’s some code with the core problem:

<!DOCTYPE html>
<html lang="">
  <head>
  </head>
  <body>
    <button id="btn">ABC</span>
  </body>
  <script>
    document.getElementById("btn").addEventListener("click", () => {
      console.log("fire");
      document.getElementsByTagName("body")[0].addEventListener("click", () => {
        console.log("fire");
      });
    });
  </script>
</html>

Facing issues with speaker audio going into mic for an Interruptible Voice Bot in Chrome

I am making a voice bot, which can be interrupted while speaking. I am using WebAudio APIs to get the float32 array of samples, to calculate average amplitude. If this crosses a certain threshold, then code assumes someone is speaking.

Now, when i run this on laptop speakers, the average amplitude i calculate in Javascript WebAudio APIs gets the speaker audio’s output. How do i ensure the speaker output doesnt go into the mic, just like Google Meet ?
I tried echoCancellation : {ideal: true}, and noiseSupression : {ideal: true} , but they dont help much.

Please let me know if more details are needed. i will be happy to provide.

Remove series markers from series in tradingview charts using lightweight charting library

Hi i am trying to draw a chart and markers on a series using trading view lightweight charting library. Below is my code how am i am adding a marker on a series.

(function anonymous(instance, properties, context

) {

let seriesID = properties.seriesid;
let markerID = properties.markerid;
let duplicate = false;

if(instance.data.mainMarkers.filter(kkk => kkk.markerId === markerID).length>0){
    duplicate =true;
}
instance.data.allPaneData.forEach( a=>{
    if(a.name === seriesID){
        if(a.markersArr.filter(aaa => aaa.markerId === markerID).length>0){
            duplicate = true;
        } 
    }
});
if(duplicate === false){
    function formateTime(timestemp){
        let date = new Date(timestemp);
        return{
            year: date.getFullYear(),
            month: date.getMonth()+1,
            day: date.getDate()
        }
    }
    let markerObj = {
        time: formateTime(properties.time),
        position: properties.position,
        color: properties.color,
        shape: properties.shape,
        text: properties.marker_text,
        size: properties.size,
        markerId : markerID,
        //marker_obj : null,
    }

    function setObject(obj,series){
        series.markerObject = obj;
    }

    if (seriesID !== null) {
        instance.data.allPaneData.filter(item => item.name === seriesID).forEach(item2 => {
            item2.markersArr.push(markerObj);
            let seriesmarker = LightweightCharts.createSeriesMarkers(item2.series,item2.markersArr);
            if(item2.markerObject == null){
                setObject(seriesmarker,item2);
            }
            //item2.markerObject.setMarkers(item2.markersArr);
        });

    } else {

        instance.data.mainMarkers.push(markerObj);
        let mainMarker=LightweightCharts.createSeriesMarkers(instance.data.allSeriesData[0].series,instance.data.mainMarkers);
        instance.data.markerObject = mainMarker
        //instance.data.markerObject.setMarkers(instance.data.mainMarkers);
    }
}

And below is my code to remove marker from the series

(function anonymous(instance, properties, context

) {

let seriesID = properties.seriesid; 
let markerID = properties.markerid;
let newarr=[];
if (seriesID == null) {
    instance.data.mainMarkers.forEach((val, index) => {
        if (val.markerId === markerID) {
            instance.data.mainMarkers.splice(index, 1); 
            
        }
    });
  instance.data.markerObject.setMarkers(instance.data.mainMarkers);  
}else {

    instance.data.allPaneData.forEach(chartObject => {
        if (chartObject.name === seriesID) {
            chartObject.markersArr.forEach((val, index) => {
                if (val.markerId === markerID) { 
                    chartObject.markersArr.splice(index, 1); 
                }
                chartObject.markerObject.setMarkers(chartObject.markersArr);
            })

        }

    });
}

})

now the problem is it only removes 1 marker from the array even if i pass an empty array it does nothing.

Scroll moves to the top on redraw of form builder in form.io library

Form.io Angular1.x library

I am using the library with Angular (1.x). I have some special situations where I will require your guidelines.

Case 1
I need to attached the element_id property in the component JSON before it gets render in the form. This element_id I get after I do the API call.

Currently, we are getting the addComponent event after the component gets add to the form due which I need to redraw the builder form in order to update the json of the form builder. I need to avoid this reload because due to this reload the scroll of the screen goes to the top.

Case 2
I have couple of component like Panel and Data Grid that I add to form without drag and drop. This components are added when user clicks on the button but in order to load them to the form I need to re-initialise the form again due to which the scroll of the screen goes to top which is not the good user friendly behaviour.

Case 3
For component sequence we are managing the order_no property so when user change the element position using drag and drop then we are calling the API with updated order_no but in order to update the same in form builder json we need to re-initialise the form builder and that move the scrolls to the top of the screen.

case 4
We have skipped the confirm box of form io open for the remove component and loads our modal with message. The problem is we can only load the model after the removeComponent event is triggered and till this moment the element is removed from the form builder json. We need to configure in such a way that the component should not be removed from the json until user gives the confirmation to the model.

Also when we re-initialise the form builder the side panel of component list is also re-initialise the scroll position as well as the search text are reset.

Looking forward to hear form you for the solution.

Refresh dynamic select box in JavaScript with Bootstrap 5

Using bootstrap 5, I have the following html:

<select class="form-select">
<option hidden="hidden">17 kW</option>
<option>18 kW</option>
<option>19 kW</option>
<option>20 kW</option>
<option>22 kW</option>
<option selected="selected">24 kW</option>
<option>26 kW</option>
<option>28 kW</option>
<option>30 kW</option>
<option>32 kW</option>
<option hidden="hidden">34 kW</option>
</select>

Note the two hidden options.

The first time I click the select box I get the image on the left. The next time I click the select box I get the image on the right. Using Chrome as the browser.

Bootstrap select dropdown

Is there a way in javascript or jquery to refresh the select box to ensure proper display, before the box is displayed for the first time?

Why JQuery AJAX POST sends null value?

I’m new at JQuery-AJAX. I’ve a form in index.php file. When clicking the first input(id=”d_code”) it opens a div(id=”d_codes”) which has been filled with some li tags which have text values from mysql database (table: d_code). I need to fill out next div(id=”d_names”) (display:none) without refreshing webpage with some li tags which have text values from mysql database (table: d_code) with AJAX post method under second input(id=”d_no”). Even if I get value of li in “d_names” I get an error (Undefined array key “d_no” in dno.php) in the browser. By the way, console.log(d_no); gives correct result. I search for a week but could not find a suitable answer for this problem. Tried several solutions but got nothing. What am I doing wrong? I’m not a native speaker that’s why I may have some issues with my English. I’ll try to give more details if you have any question(s).

index.php file form elements

<div class="d_code" id="d-e-m">
    <label for="d_code">D C:</label>
    <input type="text" id="d_code" name="d_code">
</div>
<?php dC($pdo); ?>

<div class="d_no" id="d-e-m">
   <label for="d_no">DNo:</label>
   <input type="text" id="d_no" name="d_no">
</div>
<?php dNo($pdo); ?>

script.js file

$("#d_codes li").click(function(){
$("#d_code").val($(this).attr("value"));

var d_no = $("#d_code").val();

console.log(d_no);

$.ajax({
  url: "includes/dno.php",
  type: "POST",
  data: {d_no:"d_no"},
  dataType: "text",
  success: function(options){
    $("#d_names").empty().append(options);
  },
  error: function(options) {
    console.log(options);
  }
});

$("#d_names").css("display","none");
});

dno.php file

<?php 

 declare (strict_types=1);

 require_once 'db.php';  

 function dNo(object $pdo){
  $d_code= $_POST["d_no"];

  $query = "SELECT d_no, d_name FROM d WHERE d_code=:d_code;";
  $stmt = $pdo->prepare($query);
  $stmt->bindParam(":d_code", $d_code);
  $stmt->execute();
  $dNA = $stmt->fetchAll(PDO::FETCH_ASSOC);

  echo '<div id="d_names">';
  echo '<ul>';
    foreach($dNA as $row){
      echo "<li value='" . htmlspecialchars($row["d_no"] . " - " . $row["d_name"]) 
    . "' name='d_no'>" . htmlspecialchars($row["d_no"] . " - " . $row["d_name"]) . " 
    </li>";       
    }
  echo '</ul>';
 echo '</div>';
 }
 ?>

Manage and consume npm packages in ASP.NET Core MVC application using Visual Studio

I installed couple of npm packages in an ASP.NET Core MVC app following instructions at one of the MS Learn’s how-to guide: Manage npm packages in Visual Studio

After setting up everything, my solution explorer and code files look as below:
Screenshot from Visual Studio

When I view the index.cshtml file in browser, the import statement in index.js (highlighted in the above screenshot) fails and the console shows below error:

Uncaught TypeError: The specifier “@azure/msal-browser” was a bare
specifier, but was not remapped to anything. Relative module
specifiers must start with “./”, “../” or “/”.

I also tried with relative paths and fully qualified .js file name with no luck (error messages are mentioned in the above screenshot, below each highlighted import statement).

Please help. What am I missing here?

Unable to set cookies in chrome in application tab

When I try to manually add cookies in google chrome in application tab I just can’t add more than one, I doubt if this one is even added. There is no extra empty row below for adding a new cookie.
What I’ve tried:

  1. When I googled, I read about chrome://flags/ and Partitioned cookies – but there is no such an option;
  2. I tried to enable all cookie related options in chrome://flags/ and it didn’t work;
  3. Thirt-party cookies are allowed in chrome settings;
  4. Tried to add cookies programmatically and got Uncaught SecurityError: Failed to set the 'cookie' property on 'Document': Access is denied for this document.;

The strange thing is that everything worked fine a few weeks ago and now I’m unable to auth on localhost and test or do smth.
Anyone has encountered this problem? Would be happy for help.

Google Docs API: Text from insertText appears all in the first cell of table — how to correctly insert text into each cell? Using React

I’m working with the Google Docs API to insert a table and then populate each cell with text. The table gets inserted correctly, but when I insert text into the cells, all the content appears squished into the first cell, like this:
my output

What I’m doing:

  1. I create the table using insertTable.
  2. Then I fetch the updated document to find the table and cell structure.
  3. I attempt to insert text into each cell using insertText.

Here’s the relevant code I’m using:

    const insertTableWithText = async () => {
  if (!docId) return;

  try {
    const doc = await gapi.client.docs.documents.get({ documentId: docId });
    const endIndex = doc.result.body.content.reduce((max, el) => {
      return el.endIndex > max ? el.endIndex : max;
    }, 1);

    const tableData = [
      ["Header 1", "Header 2"],
      ["Value 1", "Value 2"]
    ];

    await gapi.client.docs.documents.batchUpdate({
      documentId: docId,
      resource: {
        requests: [{
          insertTable: {
            rows: tableData.length,
            columns: tableData[0].length,
            location: { index: endIndex - 1 }
          }
        }]
      }
    });

    await new Promise(resolve => setTimeout(resolve, 1000));

    const updatedDoc = await gapi.client.docs.documents.get({ documentId: docId });

    let tableElement = null;
    for (let i = updatedDoc.result.body.content.length - 1; i >= 0; i--) {
      if (updatedDoc.result.body.content[i].table) {
        tableElement = updatedDoc.result.body.content[i];
        break;
      }
    }

    if (!tableElement) throw new Error("Table not found");

    const requests = [];

    tableElement.table.tableRows.forEach((row, rowIndex) => {
      row.tableCells.forEach((cell, colIndex) => {
        const paragraphIndex = cell.content[0].paragraph.elements[0].startIndex;

        requests.push({
          insertText: {
            text: tableData[rowIndex][colIndex],
            location: { index: paragraphIndex }
          }
        });
      });
    });

    if (requests.length > 0) {
      await gapi.client.docs.documents.batchUpdate({
        documentId: docId,
        resource: { requests }
      });
    }

  } catch (err) {
    console.error("Error inserting table with text:", err);
  }
};

Problem:
Instead of each value going into its respective cell, all the values are being inserted into the first cell, one after another (as if the insert index is reused or overlapping).

How do I properly determine the correct index to insert text into each individual cell?
Why is text appearing all in one cell even though I loop through different cells?