Why is a `canvas` element not an `instanceof HTMLCanvasElement`?

I am trying to override the toDataURL method on HTMLCanvasElement, however at runtime, the element that I am trying to affect does not report itself as an instanceof HTMLCanvasElement. Why would this be?

enter image description here

If I call document.createElement('canvas').toDataURL(), I do successfully invoke the overridden method.

// Tried both methods of overriding, but obviously the real question is about the `instanceof` values in the image above.

HTMLCanvasElement.prototype.toDataURL = new Proxy(HTMLCanvasElement.prototype.toDataURL, {
  apply(target, self, args) {
    return Reflect.apply(target, self, args);
  },
});

// and...

HTMLCanvasElement.prototype.toDataURL = () => {
  // do stuff here
};

Line break using .join method

I am new to reactjs, I am trying to join which works, but I want to put a break after each Hello continent. The <br /> and n do not work. The br tag works in regular js but not react.
What I am looking for is

Hello Africa

Hello America

etc

What I am getting is Hello Africa Hello America ect

const continents = ['Africa','America','Asia','Australia','Europe'];
const helloContinents = Array.from(continents, c => `Hello ${c}!`);
const message = helloContinents.join("<br />");
const element = (
 <div title="Outer div">
  <h1>{message}</h1>
</div>
);

Receiving `undefined` while accessing properties of large JavaScript object

I’m developing a web app which has to handle very large (plain old) objects.

At some point when the object is too big and/or the memory consumption is too high, while deep-cloning such a big object, accessing its first value returns undefined (and no, the value is actually not undefined). See a capture of dev tools below:

enter image description here

the whole memory consumption of the app at this moment is about 2Go, and the object in question has 955,022 entries, which is big, but not that big.

Another weird fact, if I iterate the keys of the oject using for (const name in input) instead of the for (const name in Object.keys(input)), the loop is just skipped, as if the object was empty.

Is this a known V8 bug (I did not find it on V8 bug report list)?
Is there a way to work around this issue? I can reproduce the bug in my app, but I did not manage to have a minimal reproducible case to share with you.

[EDIT]
The tyepscript code goes like that (simple recursive deep cloning)

const output: Record<string, any> = {}
for (const name in input) {    
  output[name] = jsonDeepCloneUncheck((input as any)[name])
}
return output as T

MathJax not rendering with custom delimiters or script configs

I am trying to get alternative math delimiters and other configurations to work in MathJax version 3. I am following the guide here to use the script config, i.e.

<script>
    MathJax = {
        tex: {
            inlineMath: [['$', '$'], ['\(', '\)']]
        },
        svg: {
          fontCache: 'global'
       }
    };
</script>
<script type="text/javascript" id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-svg.js"></script>

Despite this, I cannot get the MathJax code to render properly using dollar signs inline, although I can get the \( and \) to render fine. When I use inspection on the web browser, I can see that the HTML class is noted as span class="math math-inline" when using the dollar signs but class="MathJax CtxtMenu_Attached_0" when I use \( and \).

So, it looks like it’s detecting the dollar signs as math, but not using the correct classes?

For background, the website has a Rust backend, using Tera for HTML templating, and pulldown_cmark for Markdown to HTML conversion.

I’ve looked through the latest documentation, and followed the latest advice. I am expecting the configuration above to allow using dollar signs for inline math.

Why my env variable load 2 times, 1st time with proper values 2nd time with empty values

During Playwright api test i’am not able to read API_URL value for specified env in test.

my global-setup:

import * as dotenv from 'dotenv';
import fs from 'fs/promises';
import path from 'path';

interface User {
  username: string;
  password: string;
  cis: string;
  debitCard: string;
}

interface BankAccount {
  accountNumber: string;
  title: string;
}

interface TransferTitles {
  [key: string]: string;
}

export let CONFIG: {
  BASE_URL: string;
  API_URL: string;
  ENV: string;
  USERS: User[];
  BANK_ACCOUNTS: BankAccount[];
  COMMON_TRANSFER_TITLES: TransferTitles;
} = {
  BASE_URL: '',
  API_URL: '',
  ENV: '',

};

async function globalSetup(): Promise<void> {
  const environment = process.env.ENV || 'uat';
  console.log(`Loading environment: ${environment}`);
  const envPath = path.resolve(__dirname, `../../.env.${environment}`);
  console.log(`Loading .env file from: ${envPath}`);
  dotenv.config({ path: envPath, override: true });
  console.log(`Loaded BASE_URL from .env: ${process.env.BASE_URL}`);
  console.log(`Loaded API_URL from .env: ${process.env.API_URL}`);

  CONFIG = {
    BASE_URL: process.env.BASE_URL ?? '[NOT SET]',,
    API_URL: process.env.API_URL ?? '[NOT SET]',
    ENV: environment,
    COMMON_TRANSFER_TITLES: {},
    USERS: [],
    BANK_ACCOUNTS: [],
  };

  try {
    const commonDataPath = path.resolve(__dirname, './COMMON/commonData.json');
    const commonData = await fs.readFile(commonDataPath, 'utf8');
    const parsedCommonData = JSON.parse(commonData);
    CONFIG.COMMON_TRANSFER_TITLES = parsedCommonData.transferTitles;
    console.log('Common data loaded successfully.');
  } catch (error) {
    console.error('Error loading common data:', error);
    throw new Error('Failed to load common data');
  }

  try {
    const testDataPath = path.resolve(__dirname, `./${environment}/testData-${environment}.json`);
    const testData = await fs.readFile(testDataPath, 'utf8');
    const parsedTestData = JSON.parse(testData);
    CONFIG.USERS = parsedTestData.users;
    CONFIG.BANK_ACCOUNTS = parsedTestData.bankAccounts;
    console.log(`${environment} data loaded successfully.`);
  } catch (error) {
    console.error(`Error loading ${environment} data:`, error);
    throw new Error(`Failed to load ${environment} data`);
  }

  console.log('Global setup completed. Configuration and test data loaded.');
  console.log(`Final BASE_URL in CONFIG: ${CONFIG.BASE_URL}`);
  console.log(`Final API_URL in CONFIG: ${CONFIG.API_URL}`);

  global.CONFIG = CONFIG;
}

export default globalSetup;

my api_requests file in utils

import { CONFIG } from './global-setup';
import { APIRequestContext } from '@playwright/test';

const headersUnblock = {
  'sim-state': 'UNKNOWN',
  'device-flag-vpn': 'true',
  'os-type': 'iOS',
};

console.log('CONFIG.API_URL at top level:', CONFIG.API_URL);

export const putUnblockRequest = async (request: APIRequestContext): Promise<any> => {
  console.log('CONFIG.API_URL inside function:', CONFIG.API_URL);
  const baseApiUrl = CONFIG.API_URL;
  const path = '/my/path';
  const url = `${baseApiUrl}${path}`;
  console.log('Full URL:', url);
  const response = await request.fetch(url, {
    method: 'PUT',
    headers: headersUnblock,
  });
  console.log('Response:', response);
  return response;
};

My api.spec.ts file:


import { putUnblockRequest } from '../../src/utils/api_requests';
import { expect, request as pwRequest, test } from '@playwright/test';
import { CONFIG } from '../../src/utils/global-setup';
console.log('CONFIG after import:', CONFIG);

test.describe('API Tests', () => {
  let request: any;

  test.beforeAll(async ({ playwright }) => {
    request = await pwRequest.newContext({
      extraHTTPHeaders: {},
    });
  });

  test.afterAll(async () => {
    await request.dispose();
  });

  

  test.only('PUT request to unblock all channels', async () => {
    console.log('CONFIG.API_URL BEFORE calling putUnblockRequest:', CONFIG.API_URL);
    const response = await putUnblockRequest(request);
    expect(response.status()).toBe(204);
  });
});

Why i’am not able to perform API test? – my url from api_requests
I tried everything atm I lost my CONFIG.API_URL when i’am entering into function it is avaliable when try to console.log(‘CONFIG.API_URL at top level:’, CONFIG.API_URL);

 const baseApiUrl = CONFIG.API_URL;
  const path = '/my/path';
  const url = `${baseApiUrl}${path}`;

is always just /my/path

New data not showing up in frontend

I am using django for the backend and next.js for my frontend

I have a table called Person in my database, which I recently modified and added two new values: `government_id and fiscal_address.

my django model looks like this:

class Person(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    email = models.EmailField()
    country_code = models.CharField(max_length=5)
    area_code = models.CharField(max_length=5)
    phone_number = models.CharField(max_length=20)
    fiscal_address = models.TextField(null=True)
    government_id = models.CharField(max_length=100, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_by = models.CharField(max_length=100)
    updated_by = models.CharField(max_length=100, null=True)

I also have defined the model in my frontend like this:

import User from "../User/User";

export default interface Person {
  id: string;
  user?: User;
  firstName: string;
  lastName: string;
  email: string;
  countryCode: string;
  areaCode: string;
  phoneNumber: string;
  fiscal_address: string;
  government_id: string;
  createdAt: string;
  updatedAt: string;
  createdBy: string;
  updatedBy: string;
}

Now, the issue comes when I try to access the two new values I just mentioned. By example, I call an endpoint to obtain a person and want to print its values. If I return this:

(...)
<div className="flex items-center justify-between text-m">
  <p className="text-gray-500">Name</p>
  <p className="text-right">{person.firstName} {person.lastName}</p>
</div>

<hr className="border-gray-200 mt-2 mb-1" />

<div className="flex items-center justify-between text-m">
  <p className="text-gray-500">Fiscal address</p>
  <p className="text-right">{person.fiscal_address}</p>
</div>

person.firstName and person.lastName will print the correct values, but person.fiscal_address will be empty, even if the values do exist in the database and when I check the return value from my endpoint in postman fiscal_address is there.

Border at the end of each Page in print

I want to add border at the end of each page below is my code.

I have tried page-break-inside: auto; but due to this page starts from 2nd page below is my html structure.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Care Plan Printing Sample</title>
  <style>
    @media print {
      @page {
        size: A4 landscape;
        margin: 10mm;
      }
    }
  </style>
</head>
<body>
  <h1>Care Plan Report</h1>
  <div class="content">
    <table class="table table2">
      <tr>
        <td class="left-align"><h6>Resident Name: Test</h6></td>
        <td class="right-align"><h6>Care Plan Issue Date: 11-12-2024</h6></td>
      </tr>
      <tr>
        <td class="left-align"><h6>Bed No / Room No: A10/104</h6></td>
        <td class="right-align"><h6>Responded By: hvcbbjdhdgbvc</h6></td>
      </tr>
      <tr>
        <td class="left-align"><h6>Register Date: 11-12-2024</h6></td>
        <td></td> <!-- Empty right cell for alignment -->
      </tr>
    </table>
    <table class="table mt-4 table3">
      <thead>
        <tr>
          <th style="width:10%!important">Category</th>
          <th style="width:20%!important">Goal</th>
          <th style="width:35%!important">Plan</th>
          <th style="width:20%!important">Schedule</th>
          <th style="width:15%!important">Evaluation</th>
        </tr>
      </thead>
      <tbody>
         <tr>
            <td>G1</td>
            <td>G1</td>
            <td>G1</td>
            <td>G1</td>
            <td>G1</td>
         </tr>
      </tbody>
    </table>
  </div>
</body>
</html>

Currently it looks like thisenter image description here if I add page-break-inside: auto; then it look like this enter image description here.

Thanks in advance.

Is there a thing like Client-Side Multi Page app?

I know that Client Side app is the one where majority of the processing happens on the browser whereas in Server-side majority of the processing happens on the server.

Although whenever I am searching for Single Page application (SPA) I am seeing it being associated with Client-side app and Server-side app being associated with Multi Page App (MPA).

I am having a application which shows the documentation in a website. This application is having multiple mkdocs files present in S3 and hosted via Cloudfront.

Should this application be considered as a Client-side Multi page application?

I want to implement authentication on top of this website using msal.js library having Entra ID as the Identity provider.

The first step for which is to know what kind of application will it be classified.Types of Application

Could you please suggest which amongst the above classifications would my app lie under.

Leaflet.Draw rising TypeError: L.Control.Draw is not a constructor

I’m trying to initialize a simple Leaflet instance with Leaflet.Draw plugin enabled. I followed all the tutorials i was able to find anywhere on the internet but the error persists: TypeError: L.Control.Draw is not a constructor on L.map line.

My code looks as follows:

import L from 'leaflet19';
import 'leaflet-draw';

const map = L.map(this.containerTarget, {
  drawControl: true,
}).setView([51.505, -0.09], 13);

L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png", {
  maxZoom: 19,
  attribution:
    '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
}).addTo(map);

I’m on leaflet 1.9.4 ("leaflet19": "npm:[email protected]") and leaflet-draw 1.0.4

Pushing an array into another array [closed]

why does it throw an error if i simply do result.push([nums]) and works well with result.push([...nums])

var permute = function(nums) {
    let result = [];
    let length = nums.length;
    function helper(i){
        if(i===length-1){
            result.push([...nums]);
            return;
        }
        for(let j=i; j<length; j++){
            [nums[i], nums[j]] = [nums[j], nums[i]]; //swap numbers
            helper(i+1);
            [nums[i], nums[j]] = [nums[j], nums[i]]; //backtrack
        }
    }
    helper(0);
    return result;
};

edit:- apparently I didn’t know about the spread operator in JS (thanks @Austin Duling for the help)…

I saw a solution to the permutation problem but the person did not explain about that particular line of code….
tried searching on youtube and google but didn’t find anything

Convert current date to an Uint8 array of bytes in little endian format

I’m trying to convert the current date to an Uint8 array of bytes in little endian format.

What I tried is this :

const epochSeconds = new Date().valueOf();

This works and returns the current date in epoch timestamp format.

I then create an array buffer of 8 bytes and a dataview and try to add the bytes to it, but it seems incorrect

const byteArray = this.longToByteArray(epochSeconds);
const buffer = new ArrayBuffer(8);
const dataView = new DataView(buffer);
for (let i = 0; i < 8; i++) {
    dataView.setUint8(i, byteArray[i]);
}

I tried to verify that value with a python program

import datetime

uint8_array = [25, 15, 142, 103, 0, 0, 0, 0]
#uint8_array = [72, 224, 87, 131, 148, 1, 0, 0]

timestamp_little_endian = int.from_bytes(uint8_array, byteorder='little')

human_readable_date_little_endian = datetime.datetime.utcfromtimestamp(timestamp_little_endian)

print(timestamp_little_endian, human_readable_date_little_endian)

With the first uint8_array i get 1737363225 2025-01-20 08:53:45 and with the second

File "a.py", line 8, in <module>
    human_readable_date_little_endian = datetime.datetime.utcfromtimestamp(timestamp_little_endian)
OSError: [Errno 22] Invalid argument

What am I doing wrong ?

What are the advantages of first downloading a file in JavaScript’s memory, before exporting the file to the Dowloads folder?

Today, I tried downloading the Tresorit software from this link: https://tresorit.com/download

I was fascinated to see a progress bar displayed within the page, slowing increasing from 0% to 100%. Only once the progress bar reached 100% did the browser open its usual download interface and create a file in my computer’s filesystem. It’s almost like the file got downloaded twice: once within JavaScript’s memory (or local storage), without creating a file in the filesystem, over minutes, and another time in the Downloads folder on the filesystem, instantaneously. I presume the instantaneous download was achived using the new JavaScript APIs that browsers offer nowadays.

I have never seen this design before, and I wondered what the advantages of such a implementation are. Why implement a website to offer in-memory downloads?

Why is a textbox rendered instead of a dropdown in my editable table?

I am developing a jQuery plugin for editable HTML tables. The table should allow inline editing, and certain columns (e.g., column 1 for “Position”) should render a dropdown for editing. However, instead of a dropdown, a textbox is being rendered.

What I Have Done:
I have implemented logic to check if a column is configured for a dropdown. If yes, it should render a element with predefined options.
If the column is not configured for a dropdown, it renders a textbox for editing.
I have also verified the column configuration and added console.log() statements to debug the issue.
Expected Behavior:
When I double-click a cell in column 1, I expect a dropdown with the following options to appear:

Developer
Designer
Manager
Analyst
Actual Behavior:
When I double-click the cell in column 1, a textbox is rendered instead of a dropdown. For other columns, the correct behavior (textbox) works fine.

    if (settings.enableEditing) {
  $table.on('dblclick', 'td', function () {
    const $cell = $(this);
    const colIndex = $cell.index(); // Get column index

    // 4.1 Skip if the column is not editable
    if (settings.editableColumns.length > 0 && !settings.editableColumns.includes(colIndex)) {
      return; // Skip if column is not editable
    }

    // 4.2 Prevent multiple edit fields
    if ($cell.find('input, select').length > 0) return;

    // 4.3 Save original value
    const originalValue = $cell.text().trim();

    // Debugging: Check what colIndex is and what dropdownColumns[colIndex] contains
    console.log("Selected column index: " + colIndex);
    console.log("Dropdown columns value: ", settings.dropdownColumns[colIndex]);

    // 4.4 Check if the column has a dropdown
    if (settings.dropdownColumns && settings.dropdownColumns[colIndex] && settings.dropdownColumns[colIndex].length > 0) {
      // 4.4.1 Create dropdown
      const $dropdown = $('<select>').addClass('editable-dropdown');
      settings.dropdownColumns[colIndex].forEach((option) => {
        const $option = $('<option>')
          .val(option)
          .text(option)
          .prop('selected', option === originalValue); // Set original value as selected
        $dropdown.append($option);
      });

      // 4.4.2 Add Save and Cancel icons
      const $saveIcon = $('<span>')
        .addClass('editable-save-icon')
        .html('&#10004;') // Checkmark icon (✔)
        .on('click', function () {
          const newValue = $dropdown.val();
          $cell.empty().text(newValue); // Update cell value
          if (settings.onEditComplete) {
            settings.onEditComplete($cell, originalValue, newValue); // Trigger callback
          }
        });

      const $cancelIcon = $('<span>')
        .addClass('editable-cancel-icon')
        .html('&#10006;') // Cross icon (✖)
        .on('click', function () {
          $cell.empty().text(originalValue); // Revert to original value
        });

      // 4.4.3 Append dropdown and icons to the cell
      $cell.empty().append($dropdown).append($saveIcon).append($cancelIcon);
    } else {
      // 4.5 Default text input for non-dropdown columns
      const $input = $('<input>')
        .attr('type', 'text')
        .val(originalValue)
        .addClass('editable-input');

      // 4.5.1 Add Save and Cancel icons
      const $saveIcon = $('<span>')
        .addClass('editable-save-icon')
        .html('&#10004;') // Checkmark icon (✔)
        .on('click', function () {
          const newValue = $input.val().trim();
          $cell.empty().text(newValue);
          if (settings.onEditComplete) {
            settings.onEditComplete($cell, originalValue, newValue);
          }
        });

      const $cancelIcon = $('<span>')
        .addClass('editable-cancel-icon')
        .html('&#10006;') // Cross icon (✖)
        .on('click', function () {
          $cell.empty().text(originalValue);
        });

      // 4.5.2 Append input and icons to the cell
      $cell.empty().append($input).append($saveIcon).append($cancelIcon);

      // 4.5.3 Focus input field
      $input.focus();
    }
  });
}

    $(document).ready(function () {
  $('#smartDataTable').SmartDataTablePro({
    enableEditing: true,
    editableColumns: [1, 2], // Make Position and Age editable
    dropdownColumns: {
      1: ['Developer', 'Designer', 'Manager', 'Analyst'], // Dropdown for column 1 (Position)
    },
    nonEditableColumns: [0], // Column 0 (Name) is non-editable
    onEditComplete: function ($cell, originalValue, newValue) {
      console.log(`Cell updated from "${originalValue}" to "${newValue}"`);
    },
  });
});

I’ll be very thankful if someone solves this issue
Regards

am5 amcharts Tooltip HTML and Link

i am trying to add a tooltip to an am5 map. The tooltip shall have a tag in it, but I do not get it to work. The attached code, creates the map, added the data and tooltip, so that they can be clicked and do not disappear. The formatting in the tooltip is ok, but the links (a-tags) do not work anymore.

Problem: The link in the tooltip is not clickable. Any idea? Thanks lot!

var test="<table><tr><td><a href='/test/people/327/11619'>John York | Blue</a></td></tr><tr><td>Mike Blank | Green</td></tr><tr><td>Mike Blank | Green</td></tr><tr><td>Mike Blank | Green</td></tr></table>";
var test2="<div class='row'><a href='/test/people/327/11619'>John York | Blue</a></div>Mike Blank | Green</div><div class='row'>Mike Blank | Green</div><div class='row'>Mike Blank | Green</div>";
var cities = {
    "type": "FeatureCollection",
    "features": [{
        "type": "Feature",
        "properties": {
        "name": "New York City",
        "contacts": test
        },
        "geometry": {
        "type": "Point",
        "coordinates": [-73.778137, 40.641312]
        }
    }, {
        "type": "Feature",
        "properties": {
        "name": "London",
        "contacts": test2
        },
        "geometry": {
        "type": "Point",
        "coordinates": [-0.454296, 51.470020]
        }
    }, {
        "type": "Feature",
        "properties": {
        "name": "Beijing",
        "contacts": "<table><tr><td>John China</td><td>Green</td></tr><tr><td>Mike Blank</td><td>Green</td></tr><tr><td>Mike Blank</td><td>Green</td></tr><tr><td>Mike Blank</td><td>Green</td></tr></table>"
        },
        "geometry": {
        "type": "Point",
        "coordinates": [116.597504, 40.072498]
        }
    }]
};

    
var root = am5.Root.new("mapdiv5");

var chart = root.container.children.push(
    am5map.MapChart.new(root, {
        projection: am5map.geoEquirectangular()
    })
);

var polygonSeries = chart.series.push(
    am5map.MapPolygonSeries.new(root, {
        geoJSON: am5geodata_worldCustomHigh,
        fill: am5.color(0x001146),
        stroke: am5.color(0xffffff),
        strokeWidth: 5,
    })
);

var pointSeries = chart.series.push(
    am5map.MapPointSeries.new(root, {
        geoJSON: cities
    })
);


pointSeries.bullets.push(function() {

    var circle = am5.Circle.new(root, {
        radius: 5,
        fill: am5.color(0xffba00),
        tooltipHTML: "{contacts}",
        //showTooltipOn: "always",
        cursorOverStyle: "pointer",   
        keepTargetHover: true,
        interactive: true,
        paddingBottom: 10,
        paddingLeft: 10,
        paddingRight: 10,
        paddingTop: 10,
        toggleKey: "active",

});

circle.on("active", function(active, target) {
    if (active) {
    target.setAll({
        showTooltipOn: "always",
    });
    } else {
    target.setAll({
        showTooltipOn: "hover",
    });
    }
    target.showTooltip();
});

circle.events.on("click", function(ev) {
    console.log(ev.target.dataItem);
});

Is there any way to send pdf-blob received from api to another api endpoint in rect-native,but as a File object,not base64 encoded string?

const convertDocument=async()=>{
    const formData=new FormData()
        if(selectedPhotos){
        selectedPhotos.forEach((photo)=>{
        formData.append('files',photo)
      })
      try{
      const response=await convertDocument(formData)
      const pdfBlob=await response.blob()
      console.log("Successfuly converted document:"+pdfBlob)
      const base64Data = await blobToBase64(pdfBlob);
      console.log('Base64 data:'+base64Data)
      // Save the PDF file to the device
      const outputFilePath = RNFS.DocumentDirectoryPath + '/converted.pdf';
      await RNFS.writeFile(outputFilePath, base64Data, 'base64');
      console.log('PDF saved to:', outputFilePath);
  
      return outputFilePath;
      }catch(error){
        console.log('Error converting document:'+error)
        return
      }
    }else{
      console.log('No photos selected...')
      return
    }
   }

Here i get blob response like {"_data":{"size":56238,"offset":0,"blobId":"1a848f38-e1eb-4224-bcdd-5c018b051828","__collector":{}}},but later trying to make new File object from here or trying to access .arrayBuffer() of this blob isnt working for some reason.Also writing with RNFS.writeFile() gives a corrupted,wrong format .pdf that can’t be opened