Using an array of promises, each with metadata and Promise.All() to resolve

In my application, I build an array of calls to a 3rd party API that each returns a promise and then use Promise.All to act on the results once they all resolve.

I find myself repeating a pattern where I use this approach but also need to store additional metadata for each entry. If it’s an array of file loader promises for example, I might want to store the file type, intended destination etc. for each.

Currently, I build another array with this information and since I know the results from Promise.All will appear in the same order they were added, I can get the find both the result of the API call and the metadata using an appropriate index.

I wondered if was possible instead to create an array of containing both the API calls that returns a promise and the data as a single JavaScript object so that both can easily be extracted after they resolve.

Despite lots of trying, I wasn’t able to find a syntax that worked for me but it feels like it’s possible.

Can anyone help?

Error creating Nx workspace: “Failed to create a workspace”

I’m encountering an issue when trying to create a new Nx workspace using the create-nx-workspace command. Here are the details:

  1. I run the command npx create-nx-workspace.

  2. I provide the required information in the prompts (stack, framework, etc.).

  3. The process begins, but then it fails with the following error message:

  4. I have checked the log file, but it doesn’t provide much insight into the problem.

I’m using Windows 10 and npm version X.X.X.

Things I’ve tried:

  • Running the command as administrator.
  • Clearing npm cache with npm cache clean --force.
  • Updating npm to the latest version.

However, none of these steps have resolved the issue. Any insights or suggestions on how to troubleshoot and fix this problem would be greatly appreciated. Thank you!

using showdown js with openAi streaming response

I tried using showdownjs to translate streamed markdown from OpenAi to HTML

I changed the code given at https://github.com/orhanerday/ChatGPT and just added the showdown part

The system prompt to OpenAi includes returning responses using markdown, which it does

After the showdownjs parsed , the results are weird. Each chunk is in a separate line and the markdown isn’t parsed!


                        let converter = new showdown.Converter({smoothLivePreview: true});
                        let parsedHtml = converter.makeHtml(txt);

                        div.innerHTML += parsedHtml;

The data does come back from the backend as a stream

Am totally flummoxed. What am i doing wrong here? I have the references all included and the data does come back from the php file in the backend.

enter image description here

Thanks in advance

cropping an image using canvas drawImage gives blurry image

I am learning chrome extension development and trying to create a tool to capture crosshair screenshot. I use chrome.tabs.captureVisibleTab API to get the screenshot of whole visible area.

Now, I want to crop that visible area to what user selected using crosshair cursor. To crop that, I use HTML5 Canvas’s drawImage method. But for some reason, drawImage gives me blurry output

enter image description here

This is my cropping function:

function cropImage(
  src: string,
  cropArea: { left: number; top: number; width: number; height: number }
): Promise<HTMLCanvasElement> {
  return new Promise((resolve, reject) => {
    const { left, top, width, height } = cropArea;

    const img = document.createElement('img');
    img.src = src;
    img.onload = function () {
      // TODO: remove this: just for testing
      document.body.appendChild(img);

      try {
        const canvas = document.createElement('canvas');

        canvas.width = width;
        canvas.height = height;

        const ctx = canvas.getContext('2d');

        const devicePixelRatio = window.devicePixelRatio || 1;

        ctx.drawImage(
          img,
          left * devicePixelRatio,
          top * devicePixelRatio,
          width * devicePixelRatio,
          height * devicePixelRatio,
          0,
          0,
          width,
          height
        );

        resolve(canvas);
      } catch (error) {
        reject(error);
      }
    };
    img.onerror = function (event, source, lineno, colno, error) {
      reject(error);
    };
  });
}

This code is responsible for rendering the cropped Image:

      const canvas = await cropImage(response.imgSrc, {
        left: left - window.scrollX,
        top: top - window.scrollY,
        width,
        height,
      });

      const croppedImg = new Image();
      const croppedSrc = canvas.toDataURL('image/jpeg', 1.0);
      croppedImg.src = croppedSrc;
      document.body.appendChild(croppedImg);

Checking other stackoverflow questions with similar issues, I tried some suggestions:

  ctx.imageSmoothingEnabled = false;

But it does not work.

I hereby agree that I have researched thoroughly before asking this question, so I don’t think this is a duplicate of some other question. Please feel free to reach out incase if you think that this question is 100% duplicate of some other question.

Note: I think it will be helpful to mention that I am using Macbook Pro on which I get window.devicePixelRatio = 2.

Angular application not updating different image types correctly despite correct implementation of onFileSelect method

I’m encountering an issue in my Angular application where I’m trying to upload and preview images. I have implemented an onFileSelect method which is called when a file is selected, and depending on the image type, it should update the corresponding property in the data service.

The problem I’m facing is that regardless of which image is uploaded, only the main image seems to be updated, even though I’m confident that the correct image types are being passed.

Here’s a simplified version of my code:

// bilder-hochladen-dialog.component.ts

import { Component } from '@angular/core';
import { DataserviceService } from '../dataservice.service';

@Component({
  selector: 'app-bilder-hochladen-dialog',
  templateUrl: './bilder-hochladen-dialog.component.html',
  styleUrls: ['./bilder-hochladen-dialog.component.scss']
})
export class BilderHochladenDialogComponent {

  constructor(public _dataservice: DataserviceService) {}

  onFileSelect(event: Event, imageType: string) {
    const inputElement = event.target as HTMLInputElement;
    const file = inputElement.files?.[0];
    const allowedFileTypes = ["image/png", "image/jpeg", "image/jpg"];
    
    if (file && allowedFileTypes.includes(file.type)) {
      const reader = new FileReader();
      reader.onload = () => {
        switch (imageType) {
          case 'main':
            this._dataservice.MainimgData = reader.result as string;
            break;
          case 'detail1':
            this._dataservice.DetailimgData1 = reader.result as string;
            break;
          // other cases for different detail images
        }
      };
      reader.readAsDataURL(file);
    } else {
      console.log("Image could not be converted to data string or file type not allowed");
    }
  }
}

And here’s the HTML code:

<!-- bilder-hochladen-dialog.component.html -->

<div class="DialogBody">
  <div class="container-fluid">

    <!-- Main Image Upload Section -->
    <div class="Row">
      <div class="col-md">
        <div class="ImageAdderFlex">
          <input class="DefaultInput" id="uploadImg" (change)="onFileSelect($event,'main')" type="file" #fileinput1 name="FileInput">
          <label for="uploadImg" class="UploadButton"> <span>Main Image Upload</span> <img src=".assetsIconsUploadfoto.png"> </label>
          <div class="ImagesFlex">
            <img class="ProductImageVorschauDefault" src=".assetsIconst-shirt.svg">
            <img class="ProductImageVorschau realeImage" [src]="_dataservice.MainimgData">
          </div>
        </div>
      </div>
    </div>

    <!-- Detail Image Upload Sections (Repeat for multiple images) -->
    <!-- Adjust the change event and imageType accordingly for each detail image -->
    <!-- Example for detail1 -->
    <div class="Row">
      <div class="col-md">
        <div class="ImageAdderFlex">
          <input class="DefaultInput" id="uploadImg" (change)="onFileSelect($event,'detail1')" type="file" #fileinput1 name="FileInput">
          <label for="uploadImg" class="UploadButton"> <span>Detail Image 1 Upload</span> <img src=".assetsIconsUploadfoto.png"> </label>
          <div class="ImagesFlex">
            <img class="ProductImageVorschauDefault" src=".assetsIconst-shirt.svg">
            <img class="ProductImageVorschau realeImage" [src]="_dataservice.DetailimgData1">
          </div>
        </div>
      </div>
    </div>

    <!-- Repeat the above section for other detail images (detail2, detail3, etc.) -->

    <!-- Button to Confirm and Submit Images -->
    <div class="Row">
      <div class="col-md">
        <div class="ImageAdderFlex">
          <div  class="BestaetigenButton"> <span>Confirm</span> </div>
        </div>
      </div>
    </div>

  </div>
</div>

I’ve double-checked my implementation of the onFileSelect method to ensure the switch block is functioning correctly and that the correct image type is being passed. I’ve also verified the data service to ensure that the properties for detail images (DetailimgData1, DetailimgData2, etc.) are correctly initialized and updated.

Despite these checks, the issue persists. Are there additional steps I can take to diagnose and resolve this problem? Are there any known limitations or common pitfalls in Angular that

Uploading videos/Js/html/css

I am new to programming and creating a small social media app, anybody know like a script to upload videos, (its a small app, ik i dont have any cloud storage.) Anyway, thank you for taking your time to help. Have a good day

How do i set X-CSRFToken header with Axios instance in Next.js App?

I want to pass the CSRF token (which currently is a cookie) as a default header in my Axios instance, like this:

export const BASE_URL = "http://127.0.0.1:8000";

const api = axios.create({
    headers: {
        'X-CSRFToken': getCookie('csrftoken')
    },
    baseURL: BASE_URL,
    timeout: 3000,
    withCredentials: true
});

With a getCookie function i found here on StackOverflow:

function getCookie(name) {
  if (!document.cookie) {
    return null;
  }

    const xsrfCookies = document.cookie.split(';')
        .map(c => c.trim())
        .filter(c => c.startsWith(name + '='));

    if (xsrfCookies.length === 0) {
        return null;
    }
    return decodeURIComponent(xsrfCookies[0].split('=')[1]);
}

But this just results in

ReferenceError: document is not defined

How can i make sure document is defined? Or is there a better way to do this?

I tried 'use client' at the top of the file, but it did nothing.
I also tried:

xsrfCookieName: 'csrftoken',
xsrfHeaderName: 'X-CSRFToken',

TypeError: page.waitForXPath is not a function (Puppeteer/Puppeteer-extra)

Since i changed the cpu, ram, motherboard, and psu of my pc (and also reset my windows), the waitForXPath function stopped working for no reason. (and i really need it, since its like one of the most important things)


I tried: Reinstalling nodejs, visual studio code, asking chagpt and github copilot ofcourse, researching on the internet, reinstalling node modules and updating everything to the latest version.
I Expected: The code simply waiting and clicking a button.
The code:

await page.waitForXPath('//*[@id="loginContainer"]/div/div/div[3]'); 
const FClick = await page.$x('//*[@id="loginContainer"]/div/div/div[3]');
await FClick[0].click('//*[@id="loginContainer"]/div/div/div[3]')

Full Error:

await page.waitForXPath('//*[@id="loginContainer"]/div/div/div[3]');
                   ^

TypeError: page.waitForXPath is not a function
    at C:UsersuserDesktopShortifyindex.js:172:20
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Node.js v20.11.1

Not able to redirect using router in nextJs app

I am new to nextjs and was learning about routing, I have created following component in that is supposed to redirect to another page once we get a response from another API

"use client"

import Button from '@mui/material/Button';
import Box from '@mui/material/Box';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import Router from 'next/router';
//import {useRouter} from 'next/router'
import axios from 'axios';
import { useState, useEffect } from 'react';

const theme = createTheme();

export default function TestComponent() {
  //const router = useRouter();
  const [postRes, setPostRes] = useState({});

  const handleSubmit = async (event) => {
    event.preventDefault();
    const postData = {
        firstName: 'firstName',
        lastName: 'lastName',
        userName: 'userName',
        email: 'email',
        password: 'password',

    }
    try {
        const response = await axios.post('/apis/auth/createUser',postData);
          if (response.data) {
            console.log("here");
            setPostRes(response.data)
          }
    } catch (error) {
        alert(error?.response?.data);
    }
  };

  useEffect(() => {
    if (postRes) {
        Router.push('/login'); 
    }
}, [postRes]);

  return (
    <Button onClick={()=> {handleSubmit()}}>
        click
        </Button>
  );
}

in above code I am getting the following error at line 46
Error: No router instance found.
You should only use “next/router” on the client side of your app.

even though I am using ‘use client’ in my component why is this still considered to be server side component? would be great if anyone can help

ASP – Passed parameter hyperlink to Javascript function always NULL

I have in my ASP code:

<a style="cursor:pointer" id="btnRedirect" onclick="redirect()"><u>Click here</u></a>

And in my script:

function redirect() {
      var location = document.getElementById('Locations').value;
      window.open('/../Direct/NewPage.aspx?Location=' + location, 'List', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=no, width=990,height=600,left=530,top=200');
}

As you can see, I’m attempting to get the selected value of a Dropdown and pass it into a new window. The dropdown itself is definitely not null, as it is populated and a value pre-selected when the page itself loads. I’ve also confirmed that the URL itself is correct. When I attempt to click, nothing happens. I checked my console for any logs, and got the following error:

Uncaught TypeError: Cannot read properties of null (reading 'value')
    at redirect (OldPage.aspx:16:67)
    at HTMLAnchorElement.onclick

I’m just not sure if this is due to a syntax issue, or something else. My values are certainly not null as they’re being used elsewhere on the page. I made sure to have IDs, and my dropdown itself has one:

<asp:DropDownList runat="server" ID="Locations" Width="40%" Autopostback="true"></asp:DropDownList>

What could be causing this?

Regex negative look behind does not work as intended, how do I make it work

I am not trying to accomplish anything except understand why this specific regex does not work as intended:

/bty(?!t)b/i

Intended match:

  • any string starting with ‘ty’ and not ending with ‘t’

From what I understood about negative lookbehind, it should match something not followed by something, and here i want to match tyX (X can be any character) as long as X is not ‘t’.

Should match:

tya

Should not match:

tyt

Using a negated set solves this easily, but I don’t understand why a negative lookahead doesn’t work.

react save window width before resizing

i want to make able to get old window width after resizing with this code:

"use client";

import React, { useEffect, useRef, useState } from "react";
import Title from "./title/title";
import Note from "./note/note";
import Menu from "./menu/menu";
import { App, Main, Resizer } from "./style";

const Home = () => {
  const [width, setWidth] = useState(160);
  const [mouseDown, setMouseDown] = useState(false);
  const [appSize, setAppSize] = useState(0);

  const handleMouseDown = (event: React.MouseEvent<HTMLDivElement>) => {
    setMouseDown(true);
    event.preventDefault();
  };

  const handleMouseUp = (event: React.MouseEvent<HTMLDivElement>) => {
    setMouseDown(false);
  };

  const handleMouseMove = (event: React.MouseEvent<HTMLDivElement>) => {
    if (mouseDown) {
      const containerWidth = event.currentTarget.getBoundingClientRect().width;

      const newWidth = Math.min(event.pageX, containerWidth * 0.25);
      if (newWidth > 100) {
        setWidth(newWidth);
      }
    }
  };

  useEffect(() => {
    const handleResize = () => {
      const curSize = window.innerWidth;
      console.log(curSize, width, appSize, curSize * (width / appSize));
      setWidth(curSize * (width / appSize));
      setAppSize(curSize);
    };

    window.addEventListener("resize", handleResize);

    setAppSize(window.innerWidth);

    handleResize();

    return () => window.removeEventListener("resize", handleResize);
  }, []);

  return (
    <App>
      <Title />
      <Main onMouseUp={handleMouseUp} onMouseMove={handleMouseMove}>
        <Menu width={width} />
        <Resizer onMouseDown={handleMouseDown} />
        <Note menuWidth={width} />
      </Main>
    </App>
  );
};

export default Home;

but suddenly everytime when handleResize is called, appsize is always 0, so here console.log(curSize, width, appSize, curSize * (width / appSize)); i get infinity, but should get proportions of old size
how to fix it?

Angular routing using buttons

I have app.routes.ts:

import { Routes } from '@angular/router';
import { HomePageComponent } from '../layout/home/home-page/home-page.component';
import { LoginPageComponent } from '../layout/login/login-page/login-page.component';

export const routes: Routes = [
  {
    path: '',
    component: HomePageComponent,
    title: 'HomePage',
  },
  {
    path: 'login',
    component: LoginPageComponent,
    title: 'LoginPage',
  },
  {
    path: 'singup',
    component: LoginPageComponent,
    title: 'Signup',
  },
];

and

 <app-base-button-light
        title="Log in"
        routerLink="/login"
      ></app-base-button-light>
      <app-base-button-dark
        title="Sign in"
        routerLink="/login"
      ></app-base-button-dark>

if i type url/login this works, but if a click the button it doesnt work despite not having any error in console.
How to fix it?