How can I run a function alongside an async one?

I want to kick off an async task but then have another function run that shows some animation.

I can’t do

const = async myFunc => {
 // await asyncFunc()
 // await animateFunc()
}

as it won’t get to animateFunc until asyncFunc has resolved

I’m not sure I can wait on promises to resolve iether as animateFunc is a continuous cyclical for loop that I run

I also want to try and avoid state with useEffect as that feels more like an anti pattern. I would like to call them both onClick and then break from the for loop once the async one resolves. what are my options here?

In React how can I run a function alongside an async one?

I want to kick off an async task but then have another function run that shows some animation.

I can’t do

const = async myFunc => {
 // await asyncFunc()
 // await animateFunc()
}

as it won’t get to animateFunc until asyncFunc has resolved

I’m not sure I can wait on promises to resolve iether as animateFunc is a continuous cyclical for loop that I run

I also want to try and avoid state with useEffect as that feels more like an anti pattern. I would like to call them both onClick and then break from the for loop once the async one resolves. what are my options here?

Convert UTC timezone to local time zone

I have a report where all the dates should be displayed in the client’s time zone. The report includes a feature that allows exporting to Excel. For both generating the report and exporting it to Excel, I am using the same procedure. All the dates are stored in UTC in the database. I tried to convert the UTC date to the client’s local time zone using the following code in SQL Server:

DateUtc AT TIME ZONE 'UTC' AT TIME ZONE @TimeZoneName AS dateTimeCreated

@TimeZoneName is passed via procedure parameter. I tried to get the name of client’s time zone name in javascript by following code.

const date = new Date();

const timeZoneString = new Intl.DateTimeFormat('en-US', {
    timeZoneName: 'long'
}).format(date);

const timeZoneName = timeZoneString.split(',')[1].trim();

console.log(timeZoneName)

This code doesn’t return consistent values. For example, if I am in the (UTC-12:00) International Date Line West time zone, JavaScript returns the value as GMT-12:00. However, if I am in Nepal Time, it returns a random value for each time zone. If I pass the exact value provided by JavaScript to the procedure, the procedure throws an exception as shown below:

The time zone parameter 'Nepal Time' provided to AT TIME ZONE clause is invalid.

How to resolve this issue? Anyone knows the answer please help me
I tried to use the TimeZoneOffset value, but it causes issues during daylight saving time

Deobfuscate code to make devtools working [closed]

I’m looking for a way to analyze a website that is blocking the devtools. I’ve found a script into the page that is obuscated and I’ve tried to deobfuscate it. At the moment I have this code but no way to revert it back

function check() {
                before = new Date()[_0x64f4('0x3')]();
                debugger ;after = new Date()[_0x64f4('0x3')]();
                if (after - before > minimalUserResponseInMiliseconds) {
                    document[_0x64f4('0x1')]('.');
                    self[_0x64f4('0x7')][_0x64f4('0x13')](window[_0x64f4('0x7')][_0x64f4('0xa')] + window[_0x64f4('0x7')][_0x64f4('0x12')]['substring'](window[_0x64f4('0x7')][_0x64f4('0xa')][_0x64f4('0x10')]));
                } else {
                    before = null;
                    after = null;
                    delete before;
                    delete after;
                }
                setTimeout(check, 0x6f);
            }

I’ve looked for some answers here but each situation need a different approach. Is there any way I can make devtools work on macOS chrome?

ESLint error expected to return a value at the end of arrow function [closed]

I keep getting the ESLint error for this, I’m not sure how to refactor this as I don’t want to lose the existing defined variables as they are being used in different places across the app.

const dogArray    
[{
{
                        title: 'How old is the dog?',
                        value: DogAgeValue,
                    },
}]
let newDogArray = [];
     
            if (!dog?.editDogForm && dogValue?.value === 'lab') {
                newDogArray = [
                    ...dogArray,
                    {
                        title: 'what breed is the dog?',
                        value: whoWalksDogValue,
                    },
               
                ]
            } else {
               newDogArray = [...dogArray];
            }
           
            return newDogArray;

To be clear these are dummy values just to show what I’m working with. The original array has more fields inside it.

How to type an object with dynamic keys?

How can I achieve typehinting an object having dynamic keys with JavaScript / JSDocs only? (TypeScript knows index signature, yet this is not for TypeScript.)

I want to use JSDoc to document an argument object for a function to get type inference for my tooling.

(I work with PhpStorm, yet the solution should be agnostic to the IDE).

I thought I could achieve with what I want via:

/**
 * @typedef SomeOther
 * @type {string} a
 * @type {boolean} c
 * @type {number} d
 */

/**
 * @typedef Dynamic
 * @type {{[key: string]: SomeOther}}
 */

/**
 * @param {Dynamic} arg
 */
const foo = (arg) => {
    const example = arg['foo'];
    example.
};

Yet once I open autocomplete in the example, I see no recommendations. The type is not inferred:

Example showing no typehints

I also tried this approach


class ClassAsTypehint {
    /**
     * @this {{[k: string]: SomeOther}}
     * @param {string} key
     */
    getProp(key) {
        return this[key];
    }
}

/**
 * @param {ClassAsTypehint} arg
 */
const foo = (arg) => {
    const example = arg['foo'];
    example.
};

Similar result:

typehint also as class not working

For completeness, I can verify that my basic type inference works:

Type inference works with simple objects

How to avoid triple single quotes when using jsyaml for YAML serialization in JavaScript?

I’m trying to generate a YAML string using jsyaml in JavaScript, but I am facing an issue where strings are being serialized with triple single quotes (”’) instead of just single quotes (‘). Here’s a summary of what I am trying to achieve and the steps I have taken so far:

What I’ve tried:

  1. Manually Wrapping Values in Single Quotes: I tried wrapping values in single quotes using a custom function, but this resulted in an undesired output with triple quotes.
function wrapWithSingleQuotes(value) {
    if (typeof value === 'string' && value !== '') {
        return `'${value.replace(/'/g, "\'")}'`; // Escaping single quotes inside the value
    }
    return value;
}

Result: model: '''model1'''

The output here is wrapping the string in triple quotes, which I don’t want.

  1. Using jsyaml.dump with the styles option: I tried using the jsyaml.dump function with the { styles: { '!!str': 'single' } } option to force single quotes, but this still resulted in triple quotes in certain cases.
return jsyaml.dump(yamlObject, {
    lineWidth: -1,
    styles: { '!!str': 'single' },
});

Result: model: '''model1'''

The output here is wrapping the string in triple quotes, which I don’t want.

I want the output to be:
model: ‘model1’

Can anyone explain why this happens and how to avoid the triple quotes while still using jsyaml for YAML serialization?

Here is my form_preview.js:

document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('previewBtn').addEventListener('click', function() {
        const formData = new FormData(document.getElementById('configForm'));
        const formObject = {};

        formData.forEach((value, key) => {
            if (shouldIncludeField(key)) {
                formObject[key] = value;
            }
        });

        // Preview in alert popup    
        // const yamlData = jsyaml.dump(formObject);
        // alert('YAML Preview:n' + yamlData)

        // Preview in container
        // const yamlString = convertToYAML(formObject);
        const formattedYAML = createConfigYAML(formObject);
        document.getElementById('yamlPreview').textContent = formattedYAML;
        document.getElementById('previewContainer').style.display = 'block';
    });
});

function shouldIncludeField(fieldName) {
    // Some code here
}


function wrapWithSingleQuotes(value) {
    if (typeof value === 'string' && value !== '') {
        return value.replace(/'/g, "\'");
    }
    return value;
}

function createConfigYAML(formObject) {    
    const modelSelect = document.getElementById('model');
    const selectedModel = modelSelect.options[modelSelect.selectedIndex].text;

    const camPrefix = formObject.input === 'Camera' 
        ? '/dev/' 
        : '/home/mendel/videos/';

    const yamlObject = {
        input: {
            model: wrapWithSingleQuotes(selectedModel) || '',
            cam: camPrefix + (formObject.input === 'Camera' ? formObject.cam || 'video1' : formObject.file || ''),
            labels: `data/${formObject.dataLabels || ''}`,
            det_class: parseInt(formObject.detClasses) || 0,
        },
        detector: {
            threshold: parseFloat(formObject.threshold) || 0,
        },
        tracker:{
            max_age: parseInt(formObject.maxAge) || 0,
            min_hits: parseInt(formObject.minHits) || 0,
            iou_threshold: parseFloat(formObject.iouThreshold) || 0,
            distance_area: parseInt(formObject.distanceArea) || 0,
            direction: formObject.direction || '',
        },
        debug: {
            record: formObject.record === 'True' ? true : false,
            out: formObject.output || 'outputvid.avi',
            display: formObject.display === 'True' ? true : false,
        },
        result: {
            logs: formObject.result || './logs/'
        }
    };

    return jsyaml.dump(yamlObject, { 
        lineWidth: -1,
        styles: { '!!str': 'single' },
    });
}

How to pass function as prop in stenciljs e2e tests?

https://stenciljs.com/docs/end-to-end-testing#set-a-prop-on-a-component-using-an-external-reference
its mentioned as using $evalfrom puppetry. But when I inspect the testing browser I cant see the “click” event assigned to the button.

import { Component, h, Host, Prop } from '@stencil/core';
 

@Component({
  tag: 'custom-button', 
  shadow: true,
})
export class CustomButton {
  @Prop() onClick!: (event: UIEvent) => void;

  render() {
    return (
      <Host>
        <button
          onClick={this.onClick} 
        >
          <slot />
        </button>
      </Host>
    );
  }
}

and here is my test case

it('should render the button and click ', async () => {
    const props = {
    onClick: jest.fn(),
    };
    const page = await newE2EPage({
      waitUntil: 'networkidle2',
    }); 
    await page.setViewport({ width: 400, height: 800 });
    await page.setContent('<custom-button>some text</custom-button>');
    await page.$eval(
      'custom-button',
      (elm, { onClick }) => {
        elm.onClick = onClick;
      },
      props,
    );
 

    const customButton = await page.find('custom-button');
    customButton.setProperty('onClick', props.onClick);
    expect(customButton).not.toBeFalsy();

    const buttonElement = await page.find('custom-button >>> button');
    buttonElement.triggerEvent('onClick');
    console.log('buttonElement ', buttonElement.triggerEvent('onClick'));
    await buttonElement?.click();
    await page.waitForChanges();

    expect(props.onClick).toHaveBeenCalled();
  });

How to Load and Execute Styles and Scripts from an External HTML into a Web Component (Shadow DOM)?

I am currently using an iframe to load a Next.js application into my JavaScript application using its domain. However, I would like to migrate from using an iframe to rendering the Next.js application within a Shadow DOM. Unfortunately, I am facing issues rendering the Next.js application inside the Shadow DOM.

I’m trying to fetch the domain’s content and load it into the Shadow DOM, like this:

function loadNextJsContent(shadowRoot) {
  return new Promise((resolve, reject) => {
    // Fetch the HTML content from the Next.js app hosted at https://example.com
    fetch('http://localhost:3333/page-1-uifndi')
      .then(response => {
        if (!response.ok) {
          reject(new Error('Failed to fetch Next.js content'));
        } else {
          return response.text();
        }
      })
      .then(htmlContent => {
        const headContent = htmlContent.match(/<head[^>]*>([sS]*?)</head>/i)[1];
        console.log('HTML Content:', htmlContent, headContent);

        const template = document.createElement('template');
        template.innerHTML = htmlContent;
        
        shadowRoot.appendChild(template.content.cloneNode(true));
        resolve();
      })
      .catch(error => {
        // Handle errors and inject failure message into the Shadow DOM
        console.error('Error loading Next.js content:', error);
        shadowRoot.innerHTML = '<p>Failed to load content.</p>';
        reject(error);
      });
  });
}

loadNextJsContent(shadowRoot)
.then(() => {
  console.log('Next.js content loaded successfully!');
})
.catch(error => {
  console.error('Failed to load content:', error);
});

HTML Elements in inspect

I am currently able to retrieve only the HTML content, but I am unable to load the associated CSS, scripts, and fonts. Even though the content is loaded into the Shadow DOM, the styles and scripts do not appear in the network tab or take effect. What I am aiming for is functionality similar to an iframe, which automatically loads all the CSS and scripts when provided with a URL. Since Shadow DOM doesn’t support direct URL rendering, is there a way to load the complete domain content and render it within the Shadow DOM?

How to Generate PDF Thumbnails for Frontend Display in a Next.js + Sanity Application?

I am building an application using Next.js and Sanity, where users can upload PDFs via Sanity. On the frontend, I want to display these PDFs as thumbnails (just the front page of the PDF is enough). Users should be able to click on the thumbnail to either view the full PDF in a viewer or download it.

I’ve successfully set up the Sanity backend for uploading and retrieving PDFs. However, I’m struggling to find a library or approach that can generate thumbnails from PDFs to display them on the frontend.
Requirements:

Generate a thumbnail (first page) of the PDF.
Display the thumbnail on the frontend.
On click, open the full PDF for viewing or downloading.

I’ve searched for libraries but can’t find a suitable one to generate thumbnails efficiently. Any suggestions or guidance would be greatly appreciated.

How to check canceled events in firebase web

How to determine or track if an event was sent successfully and is not in a “canceled” state?
Events are not being delivered, and I don’t know how to implement retries.
To enable retries, I at least need to track if the event was sent.

The logEvent function returns void in the Firebase JS SDK.

import {
    logEvent,
} from 'firebase/analytics';

//other code

    public logEvent(data: Record<string, unknown>) {
        const dataCopy = JSON.parse(JSON.stringify(data));
        const name = toSnakeCase(dataCopy.name as string);

        if (this.isSkipLog) return;

        logEvent(this.analytics, name, {
            context_platform: 'web',
        });
    }

I tried to find a solution in the library, wrapping it in a try-catch block, but I couldn’t find a solution anywhere.

EACCES error npm install with root privilege gitlab action

After I read this and many other github issue and stackoverflow, didn’t find way to resolve it.
Error: EACCES: permission denied

I also read and tried this one as well,
How to fix EACCES issues with npm install
but the docker does not have sudo command and I tried whoami and it says “root” which means I already running with root privilege.

I have a action stage like this.

build-frontend:
  stage: build
  image: node:18-alpine
  script:
    - npm -v
    # create a user for the frontend build
    - cd frontend
    - npm i -g --unsafe-perm=true --allow-root
    - npm run build
    - echo "Build complete, check if backend has newest frontend changes"
    - git diff --exit-code

But the action log give give me this

$ npm i --unsafe-perm=true --allow-root
npm warn deprecated [email protected]: Rimraf versions prior to v4 are no longer supported
npm warn deprecated [email protected]: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
npm warn deprecated [email protected]: Glob versions prior to v9 are no longer supported
npm warn deprecated @humanwhocodes/[email protected]: Use @eslint/object-schema instead
npm warn deprecated @humanwhocodes/[email protected]: Use @eslint/config-array instead
npm warn deprecated [email protected]: This version is no longer supported. Please see https://eslint.org/version-support for other options.
npm error code 1
npm error path /builds/***/****/****/node_modules/esbuild
npm error command failed
npm error command sh -c node install.js
npm error node:internal/errors:496
npm error     ErrorCaptureStackTrace(err);
npm error     ^
npm error
npm error <ref *1> Error: spawnSync /builds/****/****/*****/node_modules/esbuild/bin/esbuild EACCES
npm error     at Object.spawnSync (node:internal/child_process:1117:20)
npm error     at spawnSync (node:child_process:876:24)
npm error     at Object.execFileSync (node:child_process:919:15)
npm error     at validateBinaryVersion (/builds/****/****/******/node_modules/esbuild/install.js:99:28)
npm error     at /builds/****/*****/*****/node_modules/esbuild/install.js:283:5 {
npm error   errno: -13,
npm error   code: 'EACCES',
npm error   syscall: 'spawnSync /builds/*****/*****/*****/node_modules/esbuild/bin/esbuild',
npm error   path: '/builds/*****/*****/******/node_modules/esbuild/bin/esbuild',
npm error   spawnargs: [ '--version' ],
npm error   error: [Circular *1],
npm error   status: null,
npm error   signal: null,
npm error   output: null,
npm error   pid: 0,
npm error   stdout: null,
npm error   stderr: null
npm error }
npm error
npm error Node.js v18.20.5
npm error A complete log of this run can be found in: /root/.npm/_logs/2024-11-18T23_38_00_917Z-debug-0.log

I have tried multiple version of node including latest, 20, 18, and much more.
I have, of course, tried simply use npm install to install all the dependecy, but it return the same error.
I have spent whole days in to this error, reading countless of postes relate to this issue but none of these post are like my issue. Most of the post I have read is about root prilivege, but the docker default use is root, and I check it with whoami. I tired to execute the npm install with su root -c, run chown, and none of these work.
I tried npm -g install but in the later stage, npm run build does not work saying that vite not found so I think I have to install the package locally.
I can run npm install on my local Windows machine but somehow not on the gitlab action.
I believe the warning can be ignored because I saw the same warning when running npm install and still file.
I also upgrade all the depencency, so no more warning but error still remains.
I really haw no idea about this issue. I have done many node project and set up ci cd, but it is the first I see it.

This the the package.json file

{
  "name": "frontend",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite --mode development",
    "build": "vite build --mode production --emptyOutDir",
    "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "@tanstack/react-query": "^5.40.1",
    "@vitejs/plugin-basic-ssl": "^1.1.0",
    "antd": "^5.19.0",
    "net-hr-contactinfo-frontend": "file:",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.23.1"
  },
  "devDependencies": {
    "@types/react": "^18.2.66",
    "@types/react-dom": "^18.2.22",
    "@vitejs/plugin-react": "^4.2.1",
    "eslint": "^8.57.0",
    "eslint-plugin-react": "^7.34.1",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.6",
    "sass": "^1.77.4",
    "vite": "^5.2.0"
  }
}

Nestjs Class Validator for Confirm Password

I am working on a change password endpoint using nestjs , I want to be able to validate if the two password match

The class-validator library doesn’t seem to have that on how to validate two properties within the DTO

How do I achieve this

This is my current code

export class CreatePasswordDTO {
  @MaxLength(6)
  @IsString()
  @Matches(/^d{6}$/, { message: "Password must be a 6-digit number" })
  password: string;

  @MaxLength(6)
  @IsString()
  @Matches(/^d{6}$/, { message: "Confirm Password must be a 6-digit number" })
  // I check that the password and confirmPassword are the same
  confirmPassword: string;
}

How to check if the device is Desktop, Android or IOS in C# .Net Core Razor pages?

Explaination:

I am currently working on VS2022 and Net Core 9.0.

I want to be able to send SMS to the client by clicking on a button.

After the App checks the device type, it selects the right button.

My problem is that Android and IOS have different syntaxes.

Question:

How can i detect if the device is Desktop, Android or IOS? Is there a method to do this?

Code:

To work on Android:

<a href="sms:/* phone number here */?body=/* body text here */">Link</a>

To work on iOS:

<a href="sms:/* phone number here */&body=/* body text here */">Link</a> 

Bootstrap 5 Progress Bar not updating from JavaScript event handler [duplicate]

I am uploading an Excel file in the browser using a standard file object and have an event handler so that when the file is selected I kick off a function that parses through the Excel file. I am using a Progress bar to illustrate progress of this parsing to the user. Every time I complete a sheet of the Excel file I attempt to update the progress bar. However, the progress bar only updates at the end of the function and does not show the increments. I have an extract of my code below. Any advice would be greatly appreciated.

// This function is called to process uploaded Excel file
async function handleFileAsync(e) {

    // Create reference to file object
    var files = e.target.files;

    // Read in the Excel file data
    const file = files[0];
    const data = await file.arrayBuffer();
    const workbook = XLSX.read(data, { cellStyles: true });
    var numsheets = 0;

    // Declare variable to denote if error count sheet was found
    var errorcountfound = false;

    // Search for Error Count worksheet
    for (i = 0; i < workbook.SheetNames.length; i++) {

        // Increment the number of sheets if not an error one
        if (workbook.SheetNames[i] != 'ERROR COUNT' && workbook.SheetNames[i] != 'ERROR LIST')
            numsheets++;

        // Check for error count
        if (workbook.SheetNames[i] == 'ERROR COUNT') {

            // Create reference to the error sheet
            var errorsheet = workbook.Sheets[workbook.SheetNames[i]];

            // Flag that error sheet was found
            errorcountfound = true;

        }


    }

    // Declare variables to store parsed SQL
    var processedsheets = 0;

    // Loop through the list of worksheets
    for (i = 0; i < workbook.SheetNames.length; i++) {

        // Ignore the error List sheet
        if (workbook.SheetNames[i] != 'ERROR LIST' && workbook.SheetNames[i] != 'ERROR COUNT') {

            // update the processed sheets count
            processedsheets++;

            // Update the progress bar
            var progress = Math.round(((parseFloat(processedsheets) / parseFloat(numsheets))) * 100);
            $('.progress-bar').attr('aria-valuenow', progress).css("width", progress + '%');
            $('.progress-bar').text(progress + '%');

        }

    }

    // Show the Upload Button
    $("#prduploadbtn").removeClass('d-none');

}

// Add event handler for change to the PRD file
document.getElementById("prdFile").addEventListener("change", handleFileAsync, false);

HTML progress bar

            <div class="progress" style="height: 40px;">
          <div id="uploadprogress" class="progress-bar progress-bar-striped progress-bar-animated text-center" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>
        </div>