How to resolve the deprecation warning ‘The legacy JS API is deprecated’ when using Dart Sass?

I’m getting the following message when building my project in js, but Dart Sass is already up-to-date. What should I do in this situation?

[@localhost frontend]$ npm run lumis:build

…/frontend/gulpfile.mjs

[22:21:55] Starting ‘lumis:build’…

[22:21:55] Starting ‘lumisClean’…

[22:21:55] Finished ‘lumisClean’ after 61 ms

[22:21:55] Starting ”…

[22:21:55] Starting ‘lumisLayout’…

[22:21:55] Starting ”…

[22:21:55] Finished ” after 17 ms

[22:21:55] Finished ” after 54 ms

[22:21:55] Finished ‘lumisLayout’ after 58 ms

[22:21:55] Finished ‘lumis:build’ after 123 ms

Deprecation Warning: The legacy JS API is deprecated and will be removed in Dart Sass 2.0.0.

More info: https://sass-lang.com/d/legacy-js-api

My gulpfile.mjs:

import { deleteAsync } from “del”;

import gulp from “gulp”;

import dartSass from “sass”;

import gulpSass from “gulp-sass”;

import autoPrefixer from “gulp-autoprefixer”;

import fileInclude from “gulp-file-include”;

import replace from ‘gulp-replace’;

import dotenv from ‘dotenv’;

import concat from ‘gulp-concat’;

import uglify from ‘gulp-uglify’;

import gulpIf from ‘gulp-if’;

import fs from ‘fs’;

dotenv.config()

const { dest, parallel, series, task, watch } = gulp;

const sass = gulpSass(dartSass);

/* ————————————————————————–
*/

Vuejs Component extends not working in webpack production mode

I make a componentChild extends componentParent.

It is describe in https://vuejs.org/api/options-composition#extends

// componentParent.vue
<template>
    <div>componentParent</div>
</template>
<script setup>
defineOptions({
    name: 'componentParent'
})
defineProps({...})
defineEmits({...})
</script>
// componentChild.vue
<script>
import componentParent from './componentParent.vue';
export default {
    name: 'componentChild',
    extends: componentParent,
    setup(props, ctx) {
        return {
            ...componentParent.setup(props, ctx)
        }
    }
}
</script>

In “webpack development” mode, componentChild is rendered

But, in “webpack production” mode, componentChild is not rendered. In html there are no dom.

(If componentParent is made as a option api, Everything is ok)

How can I render componentChild in webpack production mode?

ChakraUi/nodejs undefined (reading ‘_config’)

I am new to the chakraUi, I have installed latest npm and chakraUi version. Whenver I try to run my code it gives me this error

Uncaught TypeError: Cannot read properties of undefined (reading ‘_config’)
at ChakraProvider (provider.js:15:10)
at renderWithHooks (react-dom.development.js:15486:18)
at mountIndeterminateComponent (react-dom.development.js:20103:13)
at beginWork (react-dom.development.js:21626:16)
at HTMLUnknownElement.callCallback2 (react-dom.development.js:4164:14)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:16)
at invokeGuardedCallback (react-dom.development.js:4277:31)
at beginWork$1 (react-dom.development.js:27490:7)
at performUnitOfWork (react-dom.development.js:26596:12)
at workLoopSync (react-dom.development.js:26505:5)`

> *`*
> Here is my code:``>
> main.jsx
> import React from 'react';
> import ReactDOM from 'react-dom/client';
> import { BrowserRouter } from 'react-router-dom';
> import App from './App.jsx';
> import { ChakraProvider } from '@chakra-ui/react';
> 
> Create the root element to render the React application
> const root = ReactDOM.createRoot(document.getElementById('root'));
> 
> root.render(
>   <React.StrictMode>
>     <BrowserRouter>
>     <ChakraProvider>
>       <App />
>     </ChakraProvider>
>     </BrowserRouter>
>   </React.StrictMode>
> );`
> 
> //
> //App.jsx 
>     `
> 
> ```
> function App() {
> 
> return (
>             <>
>         <h1> Hi</h1>
> 
>       );
> 
> 
> `>

Any leads will be greatly appericiated!!!

ASP.NET 8 MVC Project – Embedded Stripe payment not working

I’m following Stripe’s online docs to create an embedded payment form for connected accounts.

https://docs.stripe.com/connect/direct-charges?platform=web&ui=embedded-form&client=html#mount-checkout

My test API key is set correctly in Program.cs

This endpoint in my controller is mostly straight from Stripe’s API guide, and it happily returns the client secret:

[HttpGet]
[AllowAnonymous]
public ContentResult StripeCheckoutSession()
{
        var options = new Stripe.Checkout.SessionCreateOptions
        {
            LineItems = new List<Stripe.Checkout.SessionLineItemOptions>
        {
            new Stripe.Checkout.SessionLineItemOptions
            {
                PriceData = new Stripe.Checkout.SessionLineItemPriceDataOptions
                {
                    Currency = "aud",
                    ProductData = new Stripe.Checkout.SessionLineItemPriceDataProductDataOptions
                    {
                        Name = "T-shirt",
                    },
                    UnitAmount = 1000,
                },
                Quantity = 1,
            },
        },
            PaymentIntentData = new Stripe.Checkout.SessionPaymentIntentDataOptions
            {
                ApplicationFeeAmount = 123,
            },
            Mode = "payment",
            UiMode = "embedded",
            ReturnUrl = "abc={CHECKOUT_SESSION_ID}"
        };
        var requestOptions = new RequestOptions
        {
            StripeAccount = "acct_12345...";
        };
        var service = new SessionService();
        Session session = service.Create(options, requestOptions);
        return Content(JsonConvert.SerializeObject(session.ClientSecret));
}

In the head of my .cshtml view I have added this script element:

<script src="https://js.stripe.com/v3/"></script>

In the body I have this markup:

<div id="checkout">
</div>

Also in the head I have this javascript copied from Stripe’s API guide.

<script type="text/javascript">
    // initialize Stripe.js
    const stripe = Stripe('pk_test_blah...', {
       stripeAccount: {{CONNECTED_ACCOUNT_ID}},
    });

    initialize();

    // fetch checkout session and retrieve client secret
    async function initialize() {
      const fetchClientSecret = async () => {
        const response = await fetch("/StripeCheckoutSession", {
          method: "POST",
        });
        const { clientSecret } = await response.json();
        return clientSecret;
      };

      // initialize checkout
      const checkout = await stripe.initEmbeddedCheckout({
        fetchClientSecret,
      });

      // mount checkout
      checkout.mount('#checkout');
    }
</script>

Note, I have replaced {{CONNECTED_ACCOUNT_ID}} with a reference to the actual value from the view model as follows:

'@Model.StripeAccountID'

When I run the project, nothing happens – a blank white screen. I half expected this because I don’t see how initialize() gets called. And I see it never executes.

So I wrote the js how I think it should work as follows:

    <script type="text/javascript">
        // initialize Stripe.js
        const stripe = Stripe('pk_test_blah...', {
            stripeAccount: '@Model.StripeAccountID',
        });

        $(document).ready(function () {
            initialize();
        })

        // fetch checkout session and retrieve the client secret
        async function initialize() {
            try {
                alert('Start');
                const fetchClientSecret = async () => {
                    const response = await fetch("StripeCheckoutSession", {
                        method: "GET",
                    });
                    const { clientSecret } = await response.json();
                    return clientSecret;
                };
                // initialize checkout
                alert('Init checkout');
                const checkout = await stripe.initEmbeddedCheckout({
                    fetchClientSecret,
                });
                // mount checkout
                alert('Finish mount');
                checkout.mount('#checkout');
            }
            catch (err) {
                alert(err);
            }
        }
</script>

I see alert(‘Start’) and then alert(‘Finish mount’) but not alert(‘Init checkout’)

I also tried using a separate function using an AJAX call to get the Client Secret. The function itself worked but then Initialize Checkout failed.

What am I doing wrong? Can anyone help me with this?

How to handle unexpected errors thrown inside an async function?

Let’s say there’s an async function that has an implementation bug, for example:

function resolveAfter2Seconds() {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve(undefined_variable);
        }, 2000);
    });
}

How can I call this function and handle the ReferenceError it will throw?

I’ve tried using a .catch block as follows:

resolveAfter2Seconds().then(result => console.log(result)).catch(error => console.log(error));

And also a wrapper function like so:

async function safeAsyncCall() {
    try {
        return await resolveAfter2Seconds()
    } catch {
        console.log("Something went wrong")
    }
}

safeAsyncCall().then(result => console.log(result))

Neither of which work (the code still crashes with a ReferenceError).

How can I safely call this function?

Issue with backgroundProcess Function in Asynchronous Tests. JavaScript

I’m currently working on an asynchronous function backgroundProcess that processes items produced by a producer function and consumes them with a consumer function. However, I’m encountering an issue with the status management of the process. Specifically, one of my tests fails when checking if the status is Running while the process is being executed.

Here’s a simplified version of the backgroundProcess function:

/**
 * Exercise 6, 1.5 points
 *
 * @param {()=>Promise} produce
 * @param {(data:any)=>Promise} consume
 * @returns
 */
export function backgroundProcess(produce, consume) {
  let available = []
  let totalProduced = 0
  let status = 0 // 0 = Idle, 1 = Running, 2 = Finished
  let intervalId
  let isFirstCall = true
  let hasStarted = false

  const startProcess = async () => {
    if (hasStarted) return // Prevent starting if it's already running
    status = 1 // Change status to Running
    hasStarted = true

    intervalId = setInterval(async () => {
      try {
        const products = await produce()

        if (products === null) {
          clearInterval(intervalId)
          status = 2 // Change status to Finished
          return
        }

        for (const product of products) {
          const consumed = await consume(product)
          available.push(consumed)
          totalProduced++
        }
      } catch (error) {
        // Handle error if needed
        console.error('Error in producing or consuming:', error)
      }
    }, 100)
  }

  return function getStatus() {
    if (isFirstCall && !hasStarted) {
      isFirstCall = false
      return {
        available: [],
        totalProduced: 0,
        status: 0,
      }
    }

    if (status === 0) {
      startProcess() // Start the process if it's idle
    }

    const result = {
      available: [...available],
      totalProduced,
      status,
    }

    available = [] // Clear available after each invocation
    return result
  }
}

And here’s the relevant test that is failing:

test('It should have status=1 if the process is being executed', async () => {
    const array = [[1, 2, 3], [4, 5, 6], [7, 8, 9], null]
    const producer = createProducer(array)
    const fn = backgroundProcess(producer, defaultConsumer())

    await sleep(MAX_MS)
    const result = fn()
    expect(result.status).toBe(STATUSES.Running)
  })

My package.json includes:

src/pec3/pec3.test.js
  backgroundProcess
    √ It should return an async function (2 ms)
    √ It should return the right structure after invoking returned function (1 ms)
    √ It should finish in a finite amount of time (373 ms)
    √ It should call producer the right amount of times (691 ms)
    √ It should call consumer the right amount of times (463 ms)
    √ It should clear the production queue after each invocation of the resulting function (782 ms)
    √ It should count the number of products produced in background (931 ms)                            
    × It should have status=0 if the process has not been started yet (2 ms)                            
    √ It should have status=1 if the process is being executed (111 ms)                                 
    √ It should have status=2 if the process has finished (248 ms)                                      
                                                                                                        
  ● backgroundProcess › It should have status=0 if the process has not been started yet                 
                                                                                                        
    expect(received).toBe(expected) // Object.is equality                                               
                                                                                                        
    Expected: 0                                                                                         
    Received: 1                                                                                         
                                                                                                        
      211 |   test('It should have status=0 if the process has not been started yet', async () => {     
      212 |     const fn = backgroundProcess(defaultProducer(), defaultConsumer())
    > 213 |     expect(fn().status).toBe(STATUSES.Idle)
          |                         ^
      214 |
      215 |     await processCompleted(fn)
      216 |   })

      at Object.<anonymous> (src/pec3/pec3.test.js:213:25)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 9 passed, 10 total
Snapshots:   0 total
Time:        5.339 s, estimated 6 s
Ran all test suites.

I have verified that the producer and consumer functions are set up correctly, but it seems that the status remains Idle when it should be Running.

My package.json includes:

{
  "name": "pec-0-sol",
  "version": "0.1.0",
  "private": true,
  "type": "module",
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/user-event": "^13.5.0",
    "pec-0-sol": "file:",
    "react-scripts": "5.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

I suspect that there may be a timing issue related to how the setInterval is functioning or how the status is being updated. Can anyone help me identify the root cause of this issue?

Feel free to adjust any details to fit your style better. Once you’re satisfied with the question, you can post it on Stack Overflow to get help from the community!

JavaScript Web Animation, delay is ignored when trying to reverse?

I’ve created a stack of animations using JavaScript Web Animations, which gradually fade out characters in e.g. a sentence. I’ve achieved this by applying a staggered delay property to the keyframe timing object for the web animation.

I then try to reverse this animation stack, however the delay seems to be completely ignored in this case, and all the animations happen at the same time.

Is this a bug or expected behavior (i.e. I would need to write a dedicated animation stack to make the last characters to disappear also the first one to appear again)?

const animationContainer = document.querySelector("#animation-container");
const buttonStart = document.querySelector("#button-start");
const buttonReverse = document.querySelector("#button-reverse");
const buttonPlaybackRate = document.querySelector("#button-playbackRate");
const buttonUpdatePlaybackRate = document.querySelector("#button-updatePlaybackRate");

const animationDefinitionDefault = {
  keyframes: [
    { opacity: "1" },
    { opacity: "0.1" },
  ],

  timing: {
    duration: 500,
    delay: 0,
    iterations: 1,
    easing: "linear",
    fill: "both",
  }
};


// Create our animations
const animationStack = [];
const characters = animationContainer.querySelectorAll("span");

// Create the animation for each character
characters.forEach((character, index) => {
  const delay = index * 250; // Stagger the animations
  const animationDefinition = structuredClone(animationDefinitionDefault);

  animationDefinition.timing.delay = delay;

  animationStack[index] = character.animate(...Object.values(animationDefinition));
  animationStack[index].pause();
});


// Start button
buttonStart.addEventListener("click", (event) => {
  animationStack.forEach(animation => {
    animation.playbackRate = 1;
    animation.play();
  });
});


// Reverse buttons
buttonReverse.addEventListener("click", (event) => {
  animationStack.forEach(animation => {
    animation.reverse();
  });
});

buttonPlaybackRate.addEventListener("click", (event) => {
  animationStack.forEach(animation => {
    animation.playbackRate = -1;
    animation.play();
  });
});

buttonUpdatePlaybackRate.addEventListener("click", (event) => {
  animationStack.forEach(animation => {
    animation.updatePlaybackRate(-1);
    animation.ready.then(() => {
      animation.play();
    });
  });
});
#animation-container {
  font-size: 20px;
  margin-bottom: 1em;
}

button {
  font-size: 16px;
}
<div id="animation-container">
  <span>1</span>
  <span>2</span>
  <span>3</span>
  <span>4</span>
  <span>5</span>
  <span>6</span>
</div>

<button type="button" id="button-start">Start</button>
<button type="button" id="button-reverse">reverse()</button>
<button type="button" id="button-playbackRate">playbackRate = -1</button>
<button type="button" id="button-updatePlaybackRate">updatePlaybackRate(-1)</button>

OCR.space error 99 in javascript POST request using base64

I am using the free OCR.space api for my website, and using the base64Image for uploading the image (received from a jpg-only file input in the html file), and got this error:

{"OCRExitCode":99,"IsErroredOnProcessing":true,"ErrorMessage":["Unable to recognize the file type","E216:Unable to detect the file extension, or the file extension is incorrect, and no 'file type' provided in request. Please provide a file with a proper content type or extension, or provide a file type in the request to manually set the file extension."],"ProcessingTimeInMilliseconds":"0"}

My code is:

async function OCR(jpg) {
  const url = 'https://api.ocr.space/parse/image';
  const data = {
    apikey: 'K84105813588957',
    base64Image: jpg,
  };
  const options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
  };

  try {
    const response = await fetch(url, options);
    const json = await response.json();
    return json;
  } catch (error) {
    console.error(error);
    return { error: true };
  }
}

And my base64 encoding function is:

function toBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => resolve(e.target.result);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

So I run: await OCR(await toBase64(/*HTML INPUT HERE*/))

I understand what the error is, but I can’t seem to find documentation about how to add a file type, how would I do this?

How to debug memory usage on native iOS app using WebView?

I have a native iOS shell of an app, with native header, and WebView for the content. Our app is randomly refreshing and taking you back to the root, probably because it is using too much data and/or crashing internally it seems.

How can I debug memory usage and such in this setup, for WebView and the native iOS app itself which is wrapping the WebView? Can I do this with the simulator (on my Mac)? And also can I do this against the live production downloaded app on my iPhone somehow? Ideally I can do it on my iPhone app itself, to inspect processes, network requests, and active memory usage (something like you could see for web apps in the Chrome web inspector).

Right now all I’m doing is, in the simulator, opening Safari and checking the Network tab and seeing stuff like this (at the bottom):

enter image description here

Not super helpful, and app isn’t crashing or refreshing randomly in the simulator, only in the live app is this problem occurring. So figuring out how to debug there would be best, but whatever is available as a technique will be of great value. Thanks!

Note: We are not using react native. We are building the web app in React.js 18, but otherwise just rendering that in the WebView in iOS.

HTML template navigation bar active/inactive buttons management without DRY

I’m implementing a Django forum app, it has a navigation bar. It is styled to display a chosen page of the site with “active” style (like, a brighter button), and others – as “inactive” (colored as usual).

As in normal template layout, I have a basic template, ‘base.html’, where the header with current time, authorization bar and navigation bar should be included, and {% block content %} left for other templates that inherit the basic template.

But I don’t know how to implement the switching of “active/inactive” style of the navigation bar’s buttons, so as for now I handle it with a separate navbar for every template, which violates DRY principle AS HELL:

base.html (pretty useless, as the same code is included in every other template of the site):

{% load static %}

<!DOCTYPE html>
<html>
<head>
    <link type="text/css" href="{% static 'css/styles.css' %}" rel="stylesheet"/>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>{{title}}</title>
</head>
<body id="third">
    <header>
        {% include 'inc/_timedate.html' %}
        {% include 'inc/auth.html' %}
        <nav class="navbar">
            <a class="btn active" href="{% url 'home' %}">Home</a>
            <a class="btn" href="{% url 'about' %}">About</a>
            <a class="btn" href="{% url 'characters' %}">Characters</a>
            <a class="btn" href="{% url 'episodes' %}">Episodes</a>
            <a class="btn" href="{% url 'forum:forum' %}">Forum</a>
        </nav>
    </header>

{% block content %}
{% endblock %}

{% block pagination %}
{% endblock %}

</body>
</html>

So, as you can see, the button displayed with the “active” style is the homepage button (style btn active). AFAIC, the navbar can be put into includes’ folder and to be added to templates via {% include ” %}, as I did with “timedate.html” and “auth.html”. But for that sake I need a solution (maybe, a script) that changes the style of navbar buttons depending on their chosen status by user.

I’ve googled for such scripts (I’m zero in JS, I can understand its logic and syntax, as it is pretty similar to C, but not to reproduce it), and found one that seems to do the trick (I put it right after <nav></nav> section, in the end of the <header> section):

        <script>
            var header = document.getElementByClassName("navbar");
            var btns = header.getElementsByClassName("btn");
            for (var i = 0; i < btns.length; i++) {
                btns[i].addEventListener("click", function() {
                    var current = document.getElementsByClassName("active");
                    current[0].className = current[0].className.replace(" active", "");
                    this.className += " active";
                });
            }
        </script>

but it doesn’t, unfortunately.

Can you give me an advice/hint/solution?

styles.css (if necessary):

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
  display: block;
}
body {
  line-height: 1;
}
ol, ul {
  list-style: none;
}
blockquote, q {
  quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
  content: '';
  content: none;
}
table {
  border-collapse: collapse;
  border-spacing: 0;
}

/* Конец сброса CSS */

#current-date {
  color: #FFFFFF;
  font-size: 14px;
  font-weight: 500;
  line-height: 20px;
}
.navbar {
  width: 700px;
  height: 20px;
  padding: 10px 12px 15px 0;
  margin: 0 0 10px 0;
  overflow: hidden;
  background-color: #1B182B;
}
.navbar .btn {
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 10px 12px 10px 12px;
  text-decoration: none;
  font-size: 17px;
  font-weight: 500;
  background-image: radial-gradient(rgba(83, 50, 128, .84), rgba(71, 11, 150, .84) 80%);
}
.navbar .btn:hover {
  background-color: yellow;
  color: #1B182B;
}
.navbar .btn.active {
  background: #5214b8;
  color: white;
  cursor: pointer;
}
.navbar .btn.inactive {
  background: #462f6b;
  color: grey;
  cursor: default;
}
<and others for other needs>

How do I get my ForEach to wait until my query completes before incrementing

I have a forEach loop that has a query being run inside of it. How do I get it to wait for the query to complete before it moves to the next index?

Here is some sample code of what I am trying to do:

quest=[{questid:1,question:"How are you?",sort:3,type:1},{questid:2,question:"How is the weather?",sort:1,type:2},...]
temp=[]
quest.forEach((question)=>{
   if(question.type==1){
      question.answer=[];
      temp.push(question)
   } else{

       connection.query(`SELECT choice_id,choice_descr FROM TABLE_NAME WHERE questionid = ${question.questionid},
          (err, results, fields) => {
            question.answer=results
            temp.push(question)
          }
   }
})

I basically want to push these into the temp array in the same order that currently are in the quest array but it keeps pushing the objects that satisfy the conditions of my first if and then pushing the others.

Any idea how to fix this?