Home screen app of PWA do not show badge in Android system

We have a website which is capable of adding to (install) home screen in both Android and iOS systems. In the “app” Notification is requested and works well in both systems. Now we would like to add “Badge” feature to the app. We simply added to the app a short javascript code snippet as follows:

if(navigator.setAppBadge){
    alert("Badge Supported.");
    navigator.setAppBadge(3);
} else {
    alert("No Badges.");
}

The test results in both systems are:
iOS(iPhone 8 Plus, iOS 16.7.4):
alert shows “Badge Supported”, and return to the home screen we can see a badge showing “3” on the app icon. As shown in the picture below:

enter image description here

Android(Pixel 6 Pro with Android 14, and Samsung Galaxy Note 7 with Android 10):
alert shows “Badge Supported”, but the home screen app icon does NOT show the badge. Both devices do not show. As shown in the picture below:

enter image description here

We would like to ask if anyone know how to make both systems show badge normally? Thanks!

Best Possible way of getting the LOWEST https response times

I have tried everything. keep-alive, re-using connections, buffer responses but I’m unsure how I can get lower response times. 3 of my other friends are using the same proxy, same request URL and same server location. I get 70-80ms response times but they get 30-45ms. I even tried rust for proxy performance but the amount it reduced was 1-2ms less than JavaScript. How can I get the lowest response times? Would more cookies affect response times? Is it something to do with a different header? Or can it be the way you handle requests/different libraries? Just an fyi, I have 0.2ms ping proxies and my friends use the same thing but get much different results.

My friends use C++, Rust and Golang, but I tried 2 of them (Rust and Golang) but wasn’t able to achieve anything better than 68ms.

Here is my current code:

const https = require('https');
const tunnel = require('tunnel');
const dns = require('dns');

const proxy4 = "http://myproxy";
const remoteHostName = "myurl.com";

const proxyUrl = new URL(proxy4);
const proxyOptions = {
  host: proxyUrl.hostname,
  port: proxyUrl.port,
  proxyAuth: proxyUrl.username + ':' + proxyUrl.password,
};


const agent = tunnel.httpsOverHttp({ proxy: proxyOptions });

async function getting() {
  let date = Date.now();

  dns.lookup(remoteHostName, (err, remoteAddress) => {
    if (err) {
      console.error('DNS lookup error:', err);
      getting();
      return;
    }
    const options = {
      hostname: remoteHostName,
      path: '/mypath',
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'cookie': 'mycookie',
        'Connection': 'keep-alive',
        'Accept-Encoding': 'gzip',
      },
      agent,
    };

    const req = https.request(options, (res) => {
      const chunks = [];

      res.on('data', (chunk) => {
        chunks.push(chunk);
      });

      res.on('end', () => {
        const responseBuffer = Buffer.concat(chunks);

        try {
          const json = JSON.parse(responseBuffer.toString());
          console.log(Date.now() - date, json.price);
        } catch (error) {
          console.error('Error parsing JSON:', error);
        }

        getting();
      });
    });

    req.on('error', (err) => {
      console.error('Request error:', err);
      getting();
    });

    req.end();
  });
}

getting();

Why these two dont do th same thing?

In else statement if instead of input.value = “” i put text = “” it is not working the same.
Console.log shows the same thing but on the screen is not showing “” if i put text = “”.
Why is that? I expected that it will do the same thing but it is not.

const input = document.querySelector("#text-input");
const checkButton = document.querySelector("#check-btn");
const result = document.querySelector("#result");

function cleanInputString(str) {
const regex = /[\W_]/g;  
return str.replace(regex, '');
}

const palindromeCheck = () => {
let text = input.value;
const textNoSpacesUpperCase = cleanInputString(text).toUpperCase();
const textNoSpacesUpperCaseReverse = textNoSpacesUpperCase.split("").reverse().join("");

    if (text === "") {
        alert("Please input a value");
    } else if (textNoSpacesUpperCaseReverse === textNoSpacesUpperCase) {
        result.innerHTML = `<p class="checkResult">${text} is a palindrome</p>`;
    } else {
        result.innerHTML = `<p class="checkResult">${text} is not a palindrome</p>`;
    }
    input.value = "";         
    }

checkButton.addEventListener("click", palindromeCheck);

Using CoreNLP dictionary api with node js

I want to use the CoreNLP dictionary api to find words that that match a certain part of speech however the CoreNLP library that I’m using for node js doesn’t appear to have any references to the dictionary. Are there any ways I can access the dictionary api in node js?

I’ve looked on GitHub for additional CoreNLP dictionary libraries to add to my code but nothing appears.

Issue with javascript animation api and transforms in firefox

I am trying to animate a 3d card using the javascript animation API. I want the card to move up and either rotate to the left or right slightly. I managed to get it working in Chrome but in Firefox one of the animations glitches out and seems to reset to the centre at the beginning of the animation.

Here is a codepen I created of the issue: https://codepen.io/andy013/pen/MWxmdQp

I can fix this small example by removing the commitStyles() call and not applying any transform styles to the element (although it still seems to glitch out the first time the animation plays). In my real application I can’t do this since I am not applying any styles, but the bug is still present.

I think Firefox is somehow inferring a different starting keyframe. I tried giving a starting keyframe for each animation but that won’t work for my use case as I need to be able to dynamically interrupt the animation at any point and play the reverse animation. I also tried commitStyles() once the animation is interrupted but that didn’t work either.

I am trying to figure out exactly why this issue is happening so I can avoid it in future. It’s strange that the left rotation animation is working fine. If anyone can help point me in the right direction I would be grateful.

Thank you.

Code:

HTML

  <div class="card">
    <div class="front">
      <br><br>
      front
    </div>
    <div class="back">
      back
    </div>
  </div>
</div>

<button onclick="moveup()">Animate up right</button>
<button onclick="reverse()">Animate down right</button>

<button onclick="moveup_left()">Animate up left</button>
<button onclick="reverse_left()">Animate down left</button>

<p>Up right and down right are glitching in firefox</p> 

CSS

.card-container {
  border: 1px solid red;
  width: 95px;
  height: 140px;
  position: absolute;
  top: 80px;
  left: 50px;
  align-items: center;
  justify-content: center;
  display: flex;
  cursor: pointer;
  user-select: none;
}

.card {
  border: 1px solid blue;
  position: relative;
  width: 70px;
  height: 96px;
  transform-style: preserve-3d;
  top: 10px;
  left: 10px;
  transition: 1s all;
  //transform: rotateY(180deg);
  backface-visibility: hidden;
}

.back {
  position: absolute;
  width: 70px;
  height: 96px;
  backface-visibility: hidden;
  background-color: green;
}

.front {
  position: absolute;
  width: 70px;
  height: 96px;
  backface-visibility: hidden;
  background-color: red;
  transform: rotateY(180deg);
}

JS

const anim = document.getElementsByClassName("card")[0].animate(
  [
    {
      transform: `rotateY(180deg) rotateZ(-6deg)`
    }
  ],
  {
    duration: 0,
    fill: `forwards`,
    easing: `ease`
  }
);

anim.finished.then(() => {
  anim.commitStyles();
});

function moveup() {
  document.getElementsByClassName("card")[0].animate(
    [
      {
        transform: `translateX(-5px) translateY(-20px) rotateY(180deg) rotateZ(-6deg)`
      }
    ],
    {
      duration: 400,
      fill: `forwards`,
      easing: `ease`
    }
  );
}

function moveup_left() {
  document.getElementsByClassName("card")[0].animate(
    [
      {
        transform: `translateX(-5px) translateY(-20px) rotateY(180deg) rotateZ(6deg)`
      }
    ],
    {
      duration: 400,
      fill: `forwards`,
      easing: `ease`
    }
  );
}

function reverse() {
  document.getElementsByClassName("card")[0].animate(
    [
      {
        transform: `translateX(0px) translateY(0px) rotateY(180deg) rotateZ(-6deg)`
      }
    ],
    {
      duration: 400,
      fill: `forwards`,
      easing: `ease`
    }
  );
}

function reverse_left() {
  document.getElementsByClassName("card")[0].animate(
    [
      {
        transform: `translateX(0px) translateY(0px) rotateY(180deg) rotateZ(6deg)`
      }
    ],
    {
      duration: 400,
      fill: `forwards`,
      easing: `ease`
    }
  );
}

How does the window.__shellInternal work in chrome scripting?

I’m trying to understand some code on GitHub so that I can fork the repo and do something similar for another website, but I’m having a really hard time finding any documentation or questions online about how this code works. I’ll share a link to the GitHub file and share the lines that are pertinent here.

What I understand:

The code is getting the current tab from Chrome on the first 4 lines so that the tab id can be used later.
If the specific tab is not found, it returns early.
Chrome scripting is invoked (documentation on that here), and I learned about the MAIN world here. It invokes the function declared by the key/value of func, which is getMintApiKey in this case.
And I understand the code below that

What I don’t understand:

How is the getMintApiKey getting the API key from the tab? I’ve never seen window.__shellInternal and I’m having a hard time finding any documentation on it anywhere. Could someone please explain how this works?

GitHub link:

https://github.com/monarchmoney/mint-export-extension/blob/ef1d75874bb4e3669f15942cd0be3fd8f8b6fed3/src/pages/background/index.ts#L95-L126

Code:

const handleMintAuthentication = async (sendResponse: (args: unknown) => void) => {
  const [activeMintTab] = await chrome.tabs.query({
    active: true,
    url: 'https://mint.intuit.com/*',
  });

  // No active Mint tab, return early
  if (!activeMintTab) {
    sendResponse({ success: false, error: ErrorCode.MintTabNotFound });
    return;
  }

  // Get the API key from the page
  const response = await chrome.scripting.executeScript({
    target: { tabId: activeMintTab.id },
    world: 'MAIN',
    func: getMintApiKey,
  });

  const [{ result: apiKey }] = response;

  if (apiKey) {
    await apiKeyStorage.set(apiKey);
    sendResponse({ success: true, key: apiKey });
  } else {
    sendResponse({ success: false, error: ErrorCode.MintApiKeyNotFound });
  }
};

function getMintApiKey() {
  return window.__shellInternal?.appExperience?.appApiKey;
}

I tried searching for documentation of the mysterious window.__shellInternal attribute. I was expecting if it were a common attribute, it would have been listed in the MDN documentation, or possibly the chrome documentation, but I couldn’t find it anywhere.

Bring a frontmatter astro field into the script

Good afternoon! At first I tell you that I don’t know JavaScript. I understand that it must be a simple question.

My goal is bring a field (Ventana) from above and insert it in the script outside the Astro Fontmatter. This field has content. And this content goes in the part of the script ‘SomeThingThatsWork’. Till now the script work if i use quotes and a plain text. So, I understand that my only problem is get the field content inside the script.

  ---

  import type { StrapiPost } from '@interfaces/article';

  type Props = StrapiPost;
  const { attributes: {
    title, copete, image, updatedAt, content, slug, fecha, autor, AutorManual, volanta, Ventana
  } } = Astro.props;

  ---
  <script>
  const el = document.querySelector('.current p:nth-child(3)');
  const p = document.createElement('p');
  p.textContent = SomeThingThatsWork;
  p.classList.add('ventana', 'font-helve');

  // Insert before the after element
  el.after(p);
  </script>

  Next come the html code.

Thank you for your help and sorry my english.

I tried to copy code but i dont know the semantics so nothing work. The goal is get the content and insert this between the paragraph of an article (this part works!!).

Playwright Error: Error: locator.fill: Unknown engine “data-qa” while parsing selector data-qa=login-input-email Call log:

I am new to playwright. I am getting an error below:

Error: locator.fill: Unknown engine “data-qa” while parsing selector data-qa=login-input-email

This is my Page file where my locator and method is written

export class LoginPage {
    /**
     * @param {import('@playwright/test').Page} page
     */
    constructor(page) {
      this.page = page;
      this.userName = this.page.locator('data-qa=login-input-email');
      this.password = this.page.locator('data-qa=login-input-password');
      this.loginButton = this.page.locator('data-qa=login-button');
    }
  
    async goto() {
      await this.page.goto('https://www.baseurl.com/login');
    }
  
    /**
     * @param {string} text
     */
    async enterUsername(text) {
      await this.userName.fill(text);
    }

    /**
     * @param {string} text
     */
    async enterPassword(text) {
        await this.password.fill(text);
      }

    async clickLoginBtn() {
        await this.loginButton.click();
    }

  }

This is my spec file

// @ts-check
const { test, expect } = require('@playwright/test');

import { LoginPage } from '../../pages/login-page'

// const { LoginPage } = require('../../pages/login-page');

const username = '[email protected]';
const password = 'test123_mcx6bca8CHK.tup';


test.describe('Login', () => {
  
  test('Validates the login', async ({ page }) => {
    
    const loginPage = new LoginPage(page);

    loginPage.goto();
    loginPage.enterUsername(username);
    loginPage.enterPassword(password);
    loginPage.clickLoginBtn();

  })
})

Here’s the locator. Please take note that we are require to use data-qa

enter image description here

How to read line by line a file and keep track of previous line in NodeJs?

I’m currently working on a Node.js project where I need to read a file line by line and, at the same time, keep track of the previous line for some processing. I’ve looked into various methods, but I’m unsure about the most efficient and clean way to achieve this in Node.js.

Could someone provide a code example or guide me on the best practices for reading a file line by line and maintaining a reference to the previous line in Node.js? I want to ensure that the solution is both performant and follows best practices for asynchronous file operations in Node.js.

Any help or suggestions would be greatly appreciated! Thanks in advance.

I’ve attempted to translate a piece of code from Golang to Node.js, but I’ve encountered challenges in finding an equivalent solution. The original Golang code, while functional, lacks optimization, and I’m aware of its inefficiencies.

In the Node.js context, I was expecting to find a more streamlined and performant way to read a file line by line while simultaneously keeping track of the previous line. Despite my efforts, I haven’t been able to identify a suitable approach. If anyone has experience or insights into achieving this efficiently in Node.js, I’d greatly appreciate your guidance and any code examples you can provide.

Material UI Table- Change font colour based on price

I’m trying to create a table where when the numbers are negative the font colour must be red and if it is positive, it must be green.
I have a similar table that works fine but I am having trouble with this one.
If anybody could help me I would appreciate it a lot.

import * as React from 'react';
import { styled } from '@mui/material/styles';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell, { tableCellClasses } from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';

export default function MiniTable(data) {
  if (data.data && Object.keys(data.data).length === 0) return <div />;
  data.data.reverse();

  return (
    <TableContainer component={Paper}>
      <Table sx={{ minWidth: 700 }} size="small">
        <TableHead>
          <TableRow>
            <StyledTableCell>Date</StyledTableCell>
            <StyledTableCell align="right">Budget</StyledTableCell>
            <StyledTableCell align="right">Total Margin</StyledTableCell>
            <StyledTableCell align="right">CPC</StyledTableCell>
            <StyledTableCell align="right">Bid Target</StyledTableCell>
            <StyledTableCell align="right">Spend</StyledTableCell>
            <StyledTableCell align="right">Total Profit</StyledTableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {data.data.map((row) => (
            <StyledTableRow key={row.name}>
              <StyledTableCell component="th" scope="row">
                {row.date.split('T')[0]}
              </StyledTableCell>
              <StyledTableCell align="right">${row.budget.toFixed(2)}</StyledTableCell>
              <StyledTableCell align="right">${row.totalMargin}</StyledTableCell>
              <StyledTableCell align="right">${row.cpc.toFixed(2)}</StyledTableCell>
              <StyledTableCell align="right">${row.bidTarget.toFixed(2)}</StyledTableCell>
              <StyledTableCell align="right">${row.spend.toFixed(2)}</StyledTableCell>
              <StyledTableCell align="right">${row.totalProfit.toFixed(2)}</StyledTableCell>
            </StyledTableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
}

Change the font colour based on information

How to fix 401 unauthorized error, when using signInWithPassword, in a next js project with Supabase?

Description:
I’m currently working on a Next JS v.14 project with supabase for authentication and database storage. I’ve never worked with supabase in the past so all of this is new to me. I followed a tutorial on youtube for the email and password authentication. While, it works sometimes, in most cases it doesn’t allow me to sign in on the website although on the supabase dashboard it says I’ve signed in. By looking in the console I found an error. From what I understood from the video the process im following has to do with creating a session and then using cookies to store that session and then whenever I need to connect to supabase it uses that session. Would the issue stem from the session, cookies or is this a supabase issue? If i’m getting anything wrong please feel free to correct me. If you have any ideas on the issue or the error or just need more information please let me know. Thank you!

Error:

GET https://dswgtkzjdoyjmrhbzveo.supabase.co/auth/v1/user 401 (Unauthorized)

Code for login/route.js:

'use client'

import { createClientComponentClient } from "@supabase/auth-helpers-nextjs"
import { useRouter } from "next/navigation"
import { useEffect, useState } from "react"

export default function Login(){
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const router = useRouter()
  const [user, setUser] = useState(null)
  const [loading, setLoading] = useState(true)
  
  const supabase = createClientComponentClient();

  useEffect(() => {
    async function getUser(){
      const {data: {user}} = await supabase.auth.getUser();
      setUser(user);
      setLoading(false);
    }

    getUser();
  }, [])

  const handleSignUp = async () => {
    const res =await supabase.auth.signUp({
      email, 
      password,
      options: {
        emailRedirectTo: `$(location.origin)/auth/callback`
      }
    });
    setUser(res.data.user);
    router.refresh();
    setEmail('');
    setPassword('');
  }

  const handleSignIn = async () => {
    const res = await supabase.auth.signInWithPassword({
      email,
      password
    });
    setUser(res.data.user);
    router.refresh();
    setEmail('');
    setPassword('');
  }

  const handleLogout = async () => {
    await supabase.auth.signOut();
    router.refresh();
    setUser(null)
  }

  console.log(loading, user);
  if (loading){
    return <h1>Loading...</h1>
  }

  if (user){
    return (
      <div className="h-screen flex flex-col justify-center items-center bg-gray-100">
        <div className="bg-white dark:bg-gray-900 p-8 rounded-lg shadow-md w-96 text-center">
          <h1 className="mb-4 text-xl font-bold text-gray-700 dark:text-gray-300">You're already logged in</h1>
            <button onClick={handleLogout} className="w-full p-3 rounded-md bg-red-500 text-white hover:bg-red-600 focus:outline-none">Logout</button>
        </div>
      </div>
    )
  }

  return (
    <main className="hero min-h-screen bg-primary">
      <div className="hero-content flex-col lg:flex-row-reverse">
        <div className="text-center lg:text-left">
          <h1 className="text-5xl font-bold">Login now!</h1>
          <p className="py-6">Provident cupiditate voluptatem et in. Quaerat fugiat ut assumenda excepturi exercitationem quasi. In deleniti eaque aut repudiandae et a id nisi.</p>
        </div>
        <div className="card shrink-0 w-full max-w-sm shadow-2xl bg-base-100">
          <form className="card-body">
            <div className="form-control">
              <label className="label">
                <span className="label-text">Email</span>
              </label>
              <input type="email" name="email" value={email} onChange={(e) => setEmail(e.target.value)} className="mb-4 w-full input input-bordered" />
            </div>
            <div className="form-control">
              <label className="label">
                <span className="label-text">Password</span>
              </label>
              <input type="password" name="password" value={password} onChange={(e) => setPassword(e.target.value)} className="mb-4 w-full input input-bordered" />
              <label className="label">
                <a href="#" className="label-text-alt link link-hover">Forgot password?</a>
              </label>
            </div>
            <div className="form-control mt-6">
              <button className="w-full mb-2 btn btn-primary" onClick={handleSignUp}>Sign Up</button>
              <button className="w-full btn btn-default" onClick={handleSignIn}>Sign In</button>
            </div>
          </form>
        </div>
      </div>
    </main>
  )
}

Code for auth/callback/route.js

import {createRouteHandlerClient} from 'supabase/auth-helpers-nextjs'
import {cookies} from 'next/headers'
import {NextResponse} from 'next/server'

export async function GET(request){
  const requestUrl = new URL(request.url);
  const code = requestUrl.searchParams.get('code');
  if (code){
    const cookieStore = cookies();
    const supabase = createRouteHandlerClient({cookies: () => cookieStore});
    await supabase.auth.exchangeCodeForSession(code);
  }
  return NextResponse.redirect(requestUrl.origin);
}

What is the exact return value of Intl.NumberFormat with the ar locale

I’m currently writing some unit test and I just get the test to work with the arab locale.

const value = new Intl.NumberFormat('fa', {minimumIntegerDigits: 4, minimumFractionDigits: 2, style:'percent'}).format(1.2);
expect(value).toEqual('۰٬۱۲۰٫۰۰‎٪‎');

Which fails with the best kind of errors :

Expected '٠٬١٢٠٫٠٠٪؜' to equal '۰٬۱۲۰٫۰۰‎٪‎'.

Can someone help get the correct string for the expectation ?
This very likely related with use of the Left-to-Right Mark character (U+200E)

Changing background image with javascript (webpack)

Any one know how to set the background image with javascript when using webpack? (I think it is a webpack issue) I have tried setting the css directly with .style.backgroundImage and have also tried by using css variable but neither is working. The css variable works with the default value set in the css but when I try to change the var with javascript it is not working. here is the code i have been trying to use

import waldo2 from './images/waldo2resize.jpg'

const addPic = (picture) => {

    const picContainer = document.createElement('div');
    picContainer.id = 'picContainer'
    picContainer.classList.add('svgContainer');
    const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    svg.id = 'container';
    //const image = new Image();
    //image.src = waldo2;
   //svg.style.backgroundImage = "url(waldo2)"
   document.documentElement.style.setProperty('--myVariable', 'url(./images/waldo3.jpg)');
    picContainer.appendChild(svg)

    document.body.appendChild(picContainer);
}



export default addPic;

here is the css

:root{ --myVariable : url(./images/waldo2.jpg) }

body {
    
}


.svgContainer {}

#container {

    height: 1926px;
    width: 2500px;
    background-image: var(--myVariable);
    background-size: 100%;
}

i get this error when trying to change the variable GET file:///home/vboxuser/repos/waldovjs/dist/images/waldo3.jpg net::ERR_FILE_NOT_FOUND

If i set the variable with the same value (that is in the javascript) to the default in css it works fine