Prevent webpack/Laravel mix from transforming promises/async to _asyncToGenerator functions

I’m using Laravel-mix/webpack to generate my JS code, but it generates _asyncToGenerator, although my system/browsers support async functions out of the box.
What do I do to prevent the codding from being converted to a (very clumsy) function called _asyncToGenerator instead of just keep it as it is – a simple async function?

I’ve tried putting “target: es2017′” in webpack.mix.js file, but it throws an erro that “configuration object that does not match the API schema”.

I’ve searched a lot through the Internet and no success so far…

I’m using:

For example, this clear and fine code:

async saveFileToDisk(blob, fileName) {
      try {
        const fileHandle = await self.showSaveFilePicker({
          suggestedName: fileName,
          types: [
            {
              description: "File",
              // ...
            },
          ],
        });

        const writeFile = async (fileHandle, contents) => {
          // Create a FileSystemWritableFileStream to write to.
          const writable = await fileHandle.createWritable();
          // Write the contents of the file to the stream.
          await writable.write(contents);
          // Close the file and write the contents to disk.
          await writable.close();
        };
        // write file
        writeFile(fileHandle, blob).then(() => console.log("FILE DOWNLOADED!!!"));
      } catch (error) {
        console.log(error);
      }
    }

is being converted into this:

saveFileToDisk: function saveFileToDisk(blob, fileName) {
      return _asyncToGenerator( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {
        var fileHandle, writeFile;
        return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _context2.prev = 0;
                _context2.next = 3;
                return self.showSaveFilePicker({
                  suggestedName: fileName,
                  types: [{
                    description: "File" // ...

                  }]
                });

              case 3:
                fileHandle = _context2.sent;

                writeFile = /*#__PURE__*/function () {
                  var _ref3 = _asyncToGenerator( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(fileHandle, contents) {
                    var writable;
                    return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {
                      while (1) {
                        switch (_context.prev = _context.next) {
                          case 0:
                            _context.next = 2;
                            return fileHandle.createWritable();

                          case 2:
                            writable = _context.sent;
                            _context.next = 5;
                            return writable.write(contents);

                          case 5:
                            _context.next = 7;
                            return writable.close();

                          case 7:
                          case "end":
                            return _context.stop();
                        }
                      }
                    }, _callee);
                  }));

                  return function writeFile(_x, _x2) {
                    return _ref3.apply(this, arguments);
                  };
                }(); // write file


                writeFile(fileHandle, blob).then(function () {
                  return console.log("FILE DOWNLOADED!!!");
                });
                _context2.next = 11;
                break;

              case 8:
                _context2.prev = 8;
                _context2.t0 = _context2["catch"](0);
                console.log(_context2.t0);

              case 11:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, null, [[0, 8]]);
      }))();
    },

I just want it to keep the original code. No transformations!

SQLite WASM How to load existing DB from url

I have an API endpoint that serves an SQLite database. I want to load this DB in a web app and then query it. Persistence is not needed, as I’m not writing to it.

Creating a new DB works well:

new sqlite3.oo1.DB();

However, neither the constructor nor any other function before takes an existing DB as arguments. The constructor can take a filename as argument, but that doesn’t seem to work. It just fails without even triggering a HTTP request.

sql.js has a constructor like this:

new SQL.Database(new Uint8Array(buffer));

That works, but I can’t use sql.js, because it doesn’t have FTS5.

How do I load an existing DB? Shouldn’t that be easy?

Creating Wavy Red Underline for Detected Errors in Spell Checker Project

Certainly! Here’s a suggestion for your Stack Overflow question:

Title: Creating Wavy Red Underline for Detected Errors in Spell Checker Project

Details:

I’m working on a spell checker project using Flask for the backend and JavaScript (with jQuery) for the frontend. The backend successfully detects errors and sends them to the frontend. Now, I’m facing challenges in dynamically applying a wavy red underline to misspelled words within a contenteditable div.

In my JavaScript code, after receiving detected errors from the server, I want to add a red wavy underline to each misspelled word in the user’s input. The user’s input is provided through a textarea in the HTML.
Here’s a simplified version of my JavaScript code:
` // app/static/scripts.js
function tokenizeText() {
var inputText = document.getElementById(“inputText”).value;

// Sending input text for tokenization and error detection
fetch("/tokenize", {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
    },
    body: JSON.stringify({
        text: inputText,
    }),
})
.then(response => response.json())
.then(data => {
    // Log the detected errors to the console
    console.log("Detected Errors:", data.errors);

    // TODO: Dynamically add red wavy underline for each detected error in the textarea
})
.catch(error => console.error("Error:", error));

}
`

I have implemented a spell checker project with Flask (backend) and JavaScript (frontend). The backend successfully detects errors, and I’ve set up communication between the frontend and backend using fetch requests. After receiving detected errors in the frontend, I attempted to dynamically add a red wavy underline to misspelled words within a contenteditable div.
I expected that, upon receiving detected errors, the JavaScript code would iterate through the errors and add a red wavy underline to each corresponding misspelled word within the contenteditable div. The visual indication would provide users with a clear indication of the errors in their input.

What is the difference between pages directory and routes in app directory in Next JS?

A page route can be defined either as /pages/my_page/index.js or /app/my_page/page.js. What is the difference between them? Which one is preferred?

This is confusing for me because I can’t use getServerSideProps in the app directory but I can in the pages directory. It does seem to me that both are by default sever side rendered components.

To be more specific, I want to do a fetch on a server component that takes the last slug from a path (ie capture c from /path/a/b/c) and returns to the client after the data has been captured. It seems I can only do this only if my page is under the pages directory. Making this change will cause a refactor in my code that I would rather avoid. The alternative is to make the page a client side component, which I believe is a way around the problem.

I tried to fetch an API from a server component that takes the last slug from a path, but I am not able to do this unless I move my page into the pages directory.

Sticky Column and Row Names in Rhandsontable

I am currently working on a Shiny application where I am using the rhandsontable package to display a table. Here is the code I am using:

library(shiny)
library(rhandsontable)

ui <- fluidPage(
  mainPanel(
    rHandsontableOutput("myTable")
  )
)

server <- function(input, output) {
  output$myTable <- renderRHandsontable({
    df <- data.frame(matrix(1:(50**2), ncol = 50))
    rhandsontable(df, height = 10000, width = 10000)
  })
}

shinyApp(ui = ui, server = server)

I would like to have sticky column and row names, but I am not sure how to achieve this without using a box (this is why I have set a very large height and width). I have tried several methods but none of them seem to work. Any input would be appriciated.

TypeError: fraction_js_1.default is not a constructor

I’m using an external package called “fraction-js” ( https://npm.io/package/fraction.js )

The following error occurs in my jest test files only:

TypeError: Fraction is not a constructor

for the following function:

export const multiply = (num1: number, num2: number) => {
    return new Fraction(num1).mul(num2).valueOf();
}

In my tsconfig, I’ve specified:

  • esModuleInterop: true
  • allowSyntheticDefaultImports: true
  • module: “esnext”

How can I resolve this issue?

Can you autoplay videos sound-on in Safari?

I’m working on a landing page and need to make a element autoplay sound-on when the video is scrolled into view.

Browsers are pretty strict towards this (and understandably so, given it can ruin UX). Some workarounds that I came across are:

  • Including video controls;
  • Checking for user interaction (click, keypress etc.);
  • Checking whether the user has been redirected from another page of the same domain.

The first is not an option, for visual considerations. The other two apparently work in Chrome/Firefox, but not on Safari, which blocks the video.

Is there any way to autoplay a video with sound in Safari?

How can i optimize this code in of mysql2 and nodeJs

Here is function of . if a user want to register i have to to first find the user for these two.

  1. Check if the email is not already registered.
  2. Check if the mobile number for same country is not already registed.

if any of the condition is matched i have to retrun the user. if not found i have to register the user and his address and after that i have to retrun the user . here is the code i have done.

async function register(params) {
    return new Promise(async (resolve, reject) => {
        findUserByEmailOrMobileNumberAndCountryId(params)
            .then((data) => {
                if (data.status) {
                    resolve(data);
                } else {
                    return createNewUserAndReturn(params)
                        .then((data) => {
                            resolve(data);
                        })
                        .catch((err) => {
                            reject(err);
                        });
                }
            })
            .catch((err) => {
                reject(err);
            });
    });
}

async function addAddressOrUpdate({ userId, state, city, zip, country_id }) {
    return new Promise((resolve, reject) => {
        return pool
            .getConnection()
            .then(async (connection) => {
                let query = `INSERT IGNORE INTO address (userId, state, city, zip, country_id) VALUES ('${userId}', '${state}', '${city}', '${zip}', '${country_id}')  ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id), userId = VALUES(userId), state = VALUES(state), city = VALUES(city), zip = VALUES(zip), country_id = VALUES(country_id)`;

                try {
                    let [results, metadata] = await connection.query(query);
                    connection.release();
                    resolve(results);
                } catch (error) {
                    connection.release();
                    resolve(err);
                }
            })
            .catch((err) => {
                resolve(err);
            });
    });
}

async function findUserByEmailOrMobileNumberAndCountryId(params) {
    return new Promise(async (resolve, reject) => {
        getByIso2(params.countryiso2)
            .then((country) => {
                pool.getConnection()
                    .then(async (connection) => {
                        let query = `SELECT u.id,u.first_name,u.date_of_birth,u.gender,u.type,u.device_token,  u.last_name,u.mobile_number,u.email,u.profile_url, countries.name,countries.iso2, a.state, a.zip, a.city FROM users u LEFT JOIN address a ON u.id = a.userId LEFT JOIN countries ON u.country_id = countries.id WHERE (u.mobile_number = '${params.mobile_number}' && u.country_id = '${country.id}') || u.email = '${params.email}'`;
                        try {
                            let [results, metadata] = await connection.query(query);
                            connection.release();
                            if (results.length > 0) {
                                resolve({
                                    status: true,
                                    user: results[0],
                                    message: "User found successfully",
                                });
                            } else {
                                resolve({
                                    status: false,
                                    user: null,
                                    message: "User Not Exist",
                                });
                            }
                        } catch (error) {
                            connection.release();
                            reject({
                                status: false,
                                user: null,
                                message: "There is some unknow issue with server.Please try again later",
                            });
                        }
                    })
                    .catch((err) => {
                        reject({
                            status: false,
                            user: null,
                            message: "Due to high volume of active users Server is bussy please try again later",
                        });
                    });
            })
            .catch((err) => {
                reject({
                    status: false,
                    user: null,
                    message: "user with the given country code not found",
                });
            });
    });
}

async function findUserById(id) {
    return new Promise(async (resolve, reject) => {
        return pool
            .getConnection()
            .then(async (connection) => {
                let query = `SELECT u.id,u.first_name,u.date_of_birth,u.gender,u.type,u.device_token,  u.last_name,u.mobile_number,u.email,u.profile_url, countries.name,countries.iso2, a.state, a.zip, a.city FROM users u LEFT JOIN address a ON u.id = a.userId LEFT JOIN countries ON u.country_id = countries.id WHERE u.id = '${id}'`;
                try {
                    let [results, metadata] = await connection.query(query);
                    if (results) {
                        connection.release();
                        resolve(results[0]);
                    } else {
                        reject(null);
                    }
                } catch (error) {
                    connection.release();
                    reject(null);
                }
            })
            .catch((err) => {
                reject(null);
            });
    });
}


async function createNewUserAndReturn(params) {
    const { first_name, last_name, mobile_number, email, profile_url, date_of_birth, gender, type, device_token, countryiso2 } = params;
    return new Promise(async (resolve, reject) => {
        return getByIso2(countryiso2)
            .then((country) => {
                return pool
                    .getConnection()
                    .then(async (connection) => {
                        try {
                            let query = `INSERT INTO users (id, first_name, last_name, mobile_number, email, profile_url, date_of_birth, gender, type, device_token, country_id, createdAt, updatedAt) VALUES (NULL, '${first_name}', '${last_name}', '${mobile_number}', '${email}', '${[
                                profile_url,
                            ]}', '${date_of_birth}', '${gender}', '${type}', '${device_token}', '${country.id}', current_timestamp(), current_timestamp());`;
                            let [results, metadata] = await connection.query(query);
                            connection.release();
                            if (results) {
                                return addAddressOrUpdate({
                                    userId: results.insertId,
                                    city: params.city,
                                    zip: params.zip,
                                    state: params.state,
                                    country_id: country.id,
                                })
                                    .then((data) => {
                                        return findUserById(results.insertId)
                                            .then((data) => {
                                                resolve({
                                                    status:false,
                                                    user:data,
                                                    message:"User Created successfully  "
                                                });
                                            })
                                            .catch((err) => {
                                                reject({
                                                    status:false,
                                                    user:null,
                                                    message:"There went some thing wrong"
                                                });
                                            });
                                    })
                                    .catch((err) => {
                                        reject({
                                            status:false,
                                            user:null,
                                            message:"There went some thing wrong white adding address"
                                        })
                                    });
                            } else {
                                reject({
                                    status:false,
                                    user:null,
                                    message:"There went some thing wrong white creating users"
                                })
                            }
                        } catch (error) {
                            connection.release();
                            reject({
                                status:false,
                                user:null,
                                message:"There went some thing wrong white creating users"
                            })
                        }
                    })
                    .catch((err) => {
                        reject({
                            status:false,
                            user:null,
                            message:"Server is overloaded, max number of users reached. please try after some time"
                        })
                    });
            })
            .catch((err) => {
                reject({
                    status:false,
                    user:null,
                    message:"There went some thing wrong white creating users"
                })
            });
    });
}

it working fine but i need to optimize the code to reduces errors. i want if an error occcured the the whole queries musr reverse back. for example if the add address query failed then the registered query must be rolled back.

another issue that i want that each this operation have to utilize one connection from pool. and then retrun it. i my code i am using multile connection and closing that would be time consuming and must hva overload.

Format Date based on timezone/UTC offeset

It will be very helpful to know if there is a way to format Date based on Timezone.

Ex:we give America/Los_Angeles as timezone,the output date should be formatted as MM-DD-YYYY.If we give timezone as India/Calcutta, It should be changed to DD-MM-YYYY.
I wanted to know if any library have any OOB method to auto format Date based on selected Timezone.

I have already tried using Locale support.Using Locale (en-US,en-GB,ja) we can format the date but none of the libraries stores which timezone uses which locale. We can use the browser locale(navigator.language) But This will not give desired output on locale and timezone mismatch.

Ex: 
    new Date(value).toLocaleString('en-US',{timeZone: "India/kolkata"}) // gives o/p in MM-DD-YYYY format. 
    ideally this should give O/P in DD-MM-YYYY format.

most of the libraries gives an OOB method to format the date but it expects an input string.

Ex: DateTime.fromFormat('May 25, 1982', 'MMMM dd, yyyy')

   formatInTimeZone(date, 'America/New_York', 'yyyy-MM-dd HH:mm:ssXXX') 

   dayjs('2019-01-25').format('[YYYYescape] YYYY-MM-DDTHH:mm:ssZ[Z]') 

i have checked below libraries:

https://www.npmjs.com/package/luxon

https://www.npmjs.com/package/dayjs

https://www.npmjs.com/package/date-fns-tz

I am looking for any help would be greatly appreciated. Thanks!!

Preventing Column Looping in (R)handsontable

I’m currently working with Rhandsontable and I’m facing an issue with user cell selection. When a user selects a cell from the last column (say column C) and then presses the right keyboard arrow, the selection loops back to the first column (column A). I would like to prevent this behavior and make it similar to Excel, where you cannot go further once you reach the final column.

Here’s a simple example of my current Rhandsontable

library(rhandsontable)
df <- data.frame(A = 1:5, B = 6:10, C = 11:15)
rhandsontable(df)

In this example, if a user selects a cell from column C and presses the right arrow key, the selection jumps back to column A. I want to prevent this looping behavior.

How to add lucide-angular to the standalone Angular app?

I want to add lucide-icon package to my standalone Angular app. Accroding to it’s document it’s availabe for the Angular module but I’m using standalone mode, so how to add this package to the component?

I tried this way but it gives me error.

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { NgClass, NgOptimizedImage } from '@angular/common';
import { cx } from 'class-variance-authority';
import { LucideAngularModule, Home } from 'lucide-angular';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, NgOptimizedImage, NgClass, LucideAngularModule.pick({Home})],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css',
})
export class AppComponent {
  title = 'tasko';
  protected readonly cx = cx;
}

Authentication with passport.js shows different behavior depending on browser

I have this very strange bug where passport.js and passport-local-mongoose only work with Firefox. I have tried with Chrome, Internet Explorer and Edge, but I can’t seem to login.

Here’s the main code for login.

Routes

const passport = require('passport')
const express = require('express');
const router = express.Router({ mergeParams: true });

router.post('/login', passport.authenticate('local', {
  failureRedirect: '/login/fail',
  successRedirect: '/login/success'
});

router.get('/login/success', (req, res) => {
  req.session.userID = req.user._id;
  res.status(200).json(req.user);
});

UserProfile Schema

const mongoose = require('mongoose');
const passportLocalMongoose = require('passport-local-mongoose');

const userProfileSchema = new mongoose.Schema({
  email: { type: String, required: true, unique: true },
  // other fields
});

userProfileSchema.plugin(passportLocalMongoose, {
  usernameField: 'email',
  usernameLowerCase: true
});

const UserProfile = mongoose.model('UserProfile', userProfileSchema);
module.exports = UserProfile;

app.js

const express = require('express');
const cookieParser = require('cookie-parser');

// Setup authentication
const passport = require('passport');
const UserProfile = require('@userProfile/model/userProfile');
passport.use(UserProfile.createStrategy());
passport.serializeUser(UserProfile.serializeUser());
passport.deserializeUser(UserProfile.deserializeUser());

// Setup session handling
const oneWeek = 1000 * 60 * 60 * 24 * 7;
const expressSession = require('express-session')({
  secret: keys.session.secret,
  resave: false,
  saveUninitialized: false,
  cookie: { maxAge: oneWeek }
});

var app = express();
app.use(expressSession)
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session());

The passport docs say:

By default, when authentication succeeds, the req.user property is set to the authenticated user, a login session is established, and the next function in the stack is called.

When logging in with Firefox, this works. The req.user is correctly set and I can use it for further processing.

When logging in with any other Browser, it doesn’t work. The authentication is successful, but req.user is not set and an error occurs in subsequent handling. Interestingly, I have just found out that this only happens on localhost. When using the IP address to access the frontend, everything works as expected.

Frontend Axios setup

import axios from 'axios';

const api = axios.create({
  withCredentials: true,
  baseURL: 'http://123.456.789.10:3000',
  timeout: 5000,
  validateStatus: () => true // to suppress axios errors
});

Backend CORS settings

app.use(cors({
  origin: [
    'http://localhost:9000',
    'http://123.456.789.10:9000'
  ],
  methods: ['GET', 'PATCH', 'POST', 'DELETE'],
  credentials: true
}));

When I change baseUrl to http://localhost:3000, the behavior is exactly reversed. I can still successfully login with Firefox on both localhost and the IP, while I can only login with the other browsers via localhost now.

I don’t understand it. How can using the frontend with localhost or IP both work with either baseURL on Firefox, but only one works on all the other browsers, even though nothing else has changed?

Angular – secondary router outlet stays in URL when navigating to new tab/window

I have a problem with angulars secondary router outlets (named outlets – https://angular.io/guide/router-tutorial-toh#displaying-multiple-routes-in-named-outlets).

The issue I am facing is that whenever a named outlet is active Ex.:http://myRoute1(popup:myRoute2) and then I try to navigate to another route trought routerLink with ctrl/shift modifiers (new tab/window)… the named outlet just stays in the URL.

Ex.: [routerLink]=”[‘myOtherRoute’]” produces an URL of http://myOtherRoute(popup:myRoute2) in new window/tab.

Is there any way to omit this behaviour whitout writing custom URL serializer and then navigating trough window?