Expression language supported both in java and javascript [closed]

I want to create custom calculated properties. User can write formula and define variables to insert. Like mixpanel. Mixpanel validates formula on-the-fly and, of course, on saving. I want to achieve same functionality, but it requires expression evaluator available both in java (backend) and js (frontend). Mixpanel, probably, uses it’s own solution. The question is are there any ready public solutions? With approximately the same functionality.

I checked JSONata, but it requires creation of common json for all variables and syntax is not user-friendly.
Checked CEL, but it has no official port to js.

nodemailer attachments path is not coming in [duplicate]

I have the following code for a image picker…

<div class="col-md-12" style="text-align: left">
  <label for="img_file" class="form-label">Add an Image</label><br />
  <label for="img_file"
    ><img
      src="https://static.vecteezy.com/system/resources/previews/049/358/098/non_2x/add-photos-icon-vector.jpg"
      id="customKCImg"
      alt="Image"
  /></label>
  <br />
  <input
    type="file"
    id="img_file"
    onChange="previewImg(this);"
    style="display: none"
    accept="image/*"
  />
  <div class="form-text text-danger" id="errorFile"></div>
</div>

My previewImg function is as follows:

function previewImg(input) {
  $('#customKCImg')[0].src = (window.URL ? URL : webkitURL).createObjectURL(
    input.files[0]
  );
}

When I click on the submit, I am added the file like this…

const fileInput = document.getElementById("img_file");
const file = fileInput.files[0];

in my node server (firebase) I have the following function

exports.sendEmail = functions.https.onRequest((req, res) => {
  cors(req, res, () => {
    const imgSrc = req.query.src;
    const mailOptions = {
      from: 'Your Name <[email protected]>',
      to: '[email protected]',
      subject: 'Test Email from Firebase',
      html: '<p>This is a test email sent from Firebase Cloud Functions.</p>',
      attachments: [
        {
          path: imgSrc,
        },
      ],
    };

    return transporter.sendMail(mailOptions, (error, info) => {
      if (error) {
        return res.status(500).send(error.toString());
      }
      return res.status(200).send('Email sent: ' + info.response);
    });
  });
});

inside of the firebase function, I am getting the imgSrc… I have tried to pass file, file.name, file.src, and nothing works. i always get Error: ENOENT: no such file or directory, open… i know im not getting the absolute path for this iamge, but i cant figure out how to get that…

any help ?

What are the best practices for managing state in React applications?

I’m building a React application that’s growing in complexity, and I’m struggling with proper state management. My component tree is getting deeper, and I find myself passing props through multiple levels, which feels inefficient and hard to maintain.

I’ve heard about various approaches to state management in React, like:

  • React’s built-in useState and useReducer hooks
  • Context API
  • External libraries like Redux, MobX, Zustand, or Recoil

What are the current best practices for managing state in React applications? When should I use each approach, and what are their pros and cons? I’d appreciate code examples showing implementation of these different methods.

Specifically, I’d like to understand:

  1. When to use local component state vs. global state
  2. How to avoid prop drilling
  3. Performance considerations
  4. Structuring state for maintainability

What are the best practices for managing state in React applications?

I’m building a React application that’s growing in complexity, and I’m struggling with proper state management. My component tree is getting deeper, and I find myself passing props through multiple levels, which feels inefficient and hard to maintain.

I’ve heard about various approaches to state management in React, like:

  • React’s built-in useState and useReducer hooks
  • Context API
  • External libraries like Redux, MobX, Zustand, or Recoil

What are the current best practices for managing state in React applications? When should I use each approach, and what are their pros and cons? I’d appreciate code examples showing implementation of these different methods.

Specifically, I’d like to understand:

  1. When to use local component state vs. global state
  2. How to avoid prop drilling
  3. Performance considerations
  4. Structuring state for maintainability

Getting error in the regular expressions in Express js

I’m trying to match /old-page and old-page.html

const express = require('express')
const app = express()
const path = require('path')
const PORT = process.env.PORT || 3000

app.get('/old-page(.html)?',(req,res)=>{
    res.send("hi");
})

app.listen(PORT,(req,res)=>{
    console.log(`The server is running in the port ${PORT}`);
})

The Error I get:

C:Express JSnode_modulespath-to-regexpdistindex.js:123
        throw new TypeError(`Unexpected ${nextType} at ${index}, expected ${type}: ${DEBUG_URL}`);
        ^

TypeError: Unexpected ( at 9, expected END: https://git.new/pathToRegexpError

    at Iter.consume (C:Express JSnode_modulespath-to-regexpdistindex.js:123:15)
    at consume (C:Express JSnode_modulespath-to-regexpdistindex.js:179:16)
    at parse (C:Express JSnode_modulespath-to-regexpdistindex.js:183:20)
    at C:Express JSnode_modulespath-to-regexpdistindex.js:294:74
    at Array.map (<anonymous>)
    at pathToRegexp (C:Express JSnode_modulespath-to-regexpdistindex.js:294:25)
    at Object.match (C:Express JSnode_modulespath-to-regexpdistindex.js:264:30)
    at matcher (C:Express JSnode_modulesrouterliblayer.js:86:23)
    at new Layer (C:Express JSnode_modulesrouterliblayer.js:93:62)
    at Function.route (C:Express JSnode_modulesrouterindex.js:428:17)

Node.js v22.14.0

Leetcode Runtime Error: To Be Or Not To Be

I keep getting a run time error whenever I try this problem.
https://leetcode.com/problems/to-be-or-not-to-be/submissions/1627481169

/**
 * @param {string} val
 * @return {Object}
 */
var expect = function (val) {
    return {
        toBe: function (otherVal) {
            if (val === otherVal) return true;
            else throw new Error("Not Equal");
        },
        notToBe: function (otherVal) {
            if (val !== otherVal) return true;
            else throw new Error("Equal");
        }
    };
};

expect(5).toBe(5); // true
expect(5).notToBe(5); // throws "Equal"

ERROR:

Line 16 in solution.js
throw new Error("Equal");
^
Error: Equal
Line 16: Char 23 in solution.js (Object.notToBe)
Line 27: Char 12 in solution.js (Object.<anonymous>)
at Module._compile (node:internal/modules/cjs/loader:1554:14)
at Object..js (node:internal/modules/cjs/loader:1706:10)
at Module.load (node:internal/modules/cjs/loader:1289:32)
at Function._load (node:internal/modules/cjs/loader:1108:12)
at TracingChannel.traceSync (node:diagnostics_channel:322:14)
at wrapModuleLoad (node:internal/modules/cjs/loader:220:24)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:170:5)
at node:internal/main/run_main_module:36:49
Node.js v22.14.0

How to generate video preview thumbnail for a file server in flask?

I’m making a fileserver in flask and html/css. I want to display the saved contents in /gallery route. I wrote the script for displaying images but can’t figure out how to do it for videos. Can someone tell how to do it? Getting one frame from the video and then previewing it was my idea but I can’t figure out how to implement it. I’m open to other ideas too.

Thanks!

Having problems with Edge reseting the request stream

Having issues in the Edge browser reseting the request stream. I keep getting 413 errors back from the API and an IOException is being thrown all indications point to the client (Edge browser) reseting the request stream; and the first bit of the log says:

HTTP POST /v1/MyEndpoint responded 500 in 63.1555 ms
System.IO.IOException: The client reset the request stream.
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.ReadAsyncInternal…

I am sending a payload that is approximately 63MB.

I have tried mucking with the API… changing the MaxRequestBodySize and MaxRequestBufferSizes to a larger capacity.

Then I tried this:


group.MapPost("/MyEndpoint", async (HttpContext context, ILogger<ValueText> logger) =>
        {
            using var reader = new StreamReader(context.Request.Body, leaveOpen: true);
            var rawBody = await reader.ReadToEndAsync();

            Console.WriteLine($"Received payload size: {rawBody.Length} bytes");

            await context.Response.WriteAsync("Streaming request processed!");

            return ValidateResponse(logger, 1);

And then actually bothered to look at the logs. Does Edge have a payload limit for POST requests? I do have an OAuth2 server in play here…so it might be doing something too.

How to Solve CORS Error When Connecting React to Google Apps Script Web App?

I’m trying to connect a React form to a Google Apps Script web app, but I’m getting CORS errors:

Access to fetch at 'https://script.google.com/macros/s/SCRIPT_ID/exec' from origin 'http://localhost:5173' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

My Setup
Google Apps Script (backend):

function doPost(e) {
  try {
    const formData = JSON.parse(e.postData.contents);
    
    // Save to Google Sheets
    const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data');
    sheet.appendRow([new Date(), formData.name, formData.email]);
    
    return ContentService.createTextOutput(
      JSON.stringify({ success: true })
    ).setMimeType(ContentService.MimeType.JSON);
    
  } catch(error) {
    return ContentService.createTextOutput(
      JSON.stringify({ success: false, error: error.message })
    ).setMimeType(ContentService.MimeType.JSON);
  }
}

React (frontend):

const handleSubmit = async (formData) => {
  try {
    const response = await fetch('https://script.google.com/macros/s/SCRIPT_ID/exec', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(formData)
    });
    const result = await response.json();
    return result;
  } catch(error) {
    console.error('Submission failed:', error);
  }
}

What I’ve Tried:

1. Setting mode: ‘no-cors’
This makes the request go through but I can’t read the response.

2. Adding CORS headers in Apps Script
Tried using HtmlService with setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL) but still getting errors.

3. Creating a proxy API
Works but adds complexity – would prefer direct connection if possible.

Question:

How can I properly handle CORS when connecting React directly to a Google Apps Script web app?

  • Is there a way to configure Apps Script to accept cross-origin requests?
  • Are there any workarounds that still allow reading the response?
  • What’s the most reliable production solution?

Why This is Different From Other Questions:

Most solutions suggest using no-cors mode or a proxy server, but:

  • no-cors prevents reading responses
  • Proxy adds latency and another point of failure

I’m looking for a way to make direct requests work properly with CORS.

finding of parent of an html node in javascript using recursion?

Basically I need a less stupid way to do this:

var x = getElementById('not-important');
x.parentElement.parentElement.parentElement.parentElement....parentElement.style.display = 'none'; 

In my case I have to use the .parentElement eight times. (FYI it’s looking for the containing div for a link/advert that directs our users to another website, on pages that we ingest from a 3rd-party organization.)

The element I need to hide is a div and the only defining characteristic is it has a class name of “Enh”. Other divs within the page have the class name and they cannot be deleted, thankfully though there’s only one div with class ‘Enh’ within the structure I’m trying to delete.

So, the whole structure is something like this:

<div class='Enh'>
  <div>
    <div>
      ...
        <div id='not-important>
          <a href='http://another.domain'>delete me<a>
        </div>
      ...
    </div>
  </div>
</div>
<div class='Enh'>
  I must not be deleted
</div>

And like I said, the structure that needs to be deleted is coming from outside my control and could change at anytime, and if they change it from 8 nested divs to 7-or-less nested divs then my dumb code from above could accidently delete the whole page or section.

Anyone want to take a stab at this?

ReactJS input fields lag on large dynamic table with live calculations

I’m working on a ReactJS application where I have a table with an infinite number of rows (user can keep adding rows). Each row has 10 input fields (columns). There is one constant total row at the top that:

  1. Shows column-wise totals by summing values from each respective column.
  2. Shows row-wise total at the end of each row (sum of all columns in that row).

All totals are calculated live as the user types in the input fields.

The Problem

When I start adding many rows (say 50+), the input fields become very slow and laggy. Typing becomes almost impossible. I assume this is due to state updates and re-rendering, but I couldn’t figure out a clean and optimized way to handle it.

Current Implementation

import React, { useState } from "react";
 
const NUM_COLS = 10;

const TableWithTotals = () => {
  const [rows, setRows] = useState([[...Array(NUM_COLS).fill("")]]);

  const handleInputChange = (rowIndex, colIndex, value) => {
    const updatedRows = [...rows];
    updatedRows[rowIndex][colIndex] = value;
    setRows(updatedRows);
  };

  const addRow = () => {
    setRows([...rows, [...Array(NUM_COLS).fill("")]]);
  };

  const getColumnTotal = (colIndex) =>
    rows.reduce((sum, row) => sum + Number(row[colIndex] || 0), 0);

  const getRowTotal = (row) =>
    row.reduce((sum, val) => sum + Number(val || 0), 0);

  return (
    <div>
      <button onClick={addRow}>Add Row</button>

      {/* Totals Row */}
      <div style={{ display: "flex", fontWeight: "bold", marginTop: "10px" }}>
        {Array.from({ length: NUM_COLS }).map((_, colIndex) => (
          <input
            key={`total-${colIndex}`}
            value={getColumnTotal(colIndex)}
            readOnly
            style={{ width: "80px", margin: "2px" }}
          />
        ))}
        <input value="-" readOnly style={{ width: "80px", margin: "2px" }} />
      </div>

      {/* Data Rows */}
      {rows.map((row, rowIndex) => (
        <div key={rowIndex} style={{ display: "flex" }}>
          {row.map((val, colIndex) => (
            <input
              key={colIndex}
              value={val}
              onChange={(e) =>
                handleInputChange(rowIndex, colIndex, e.target.value)
              }
              style={{ width: "80px", margin: "2px" }}
            />
          ))}
          <input
            value={getRowTotal(row)}
            readOnly
            style={{ width: "80px", margin: "2px", fontWeight: "bold" }}
          />
        </div>
      ))}
    </div>
  );
};

export default TableWithTotals;

What I’ve Tried

  1. I’ve experimented with debouncing the input changes, but still the issue persists
  2. I tried using useReducer instead of useState but didn’t see significant improvements.
  3. I’ve tried virtualization but still the viewport rows calculations feels laggy

What I’m Looking For

  • How can I optimize this setup so the inputs don’t lag when there are many rows?
  • Is there a recommended React pattern for handling large datasets with real-time calculations?

Any help or suggestions would be greatly appreciated! I’m open to completely rethinking the approach if necessary.

Javascript Fetch API – How to save output to variable [duplicate]

This is a follow-up on answer https://stackoverflow.com/a/45018619 to question Javascript Fetch API – How to save output to variable as an Object (not the Promise)

I’ve taken the code snippet in that answer and added a console.log() invocation after the complete fetch() chain.

<html lang='en'>
  <body>
    <script>
      var obj;

      fetch('https://jsonplaceholder.typicode.com/posts/1')
        .then(res => res.json())
        .then(data => {
           obj = data;
        })
        .then(() => {
          console.log('Inside then()', obj);
        });

      console.log('Outside fetch()', obj);
    </script> 
  </body>
</html>

The original console.log() (which I have labelled 'Inside then()') correctly shows the value of obj.

My question is: How do I get the console.log() labelled 'Outside fetch()' to show the expected value of obj instead of undefined?

This behavior has been observed in both Chromium and Firefox.

Can’t implement yt-dlp-exec in my Node.js/Express backend for YouTube transcript fetching

I’m building a web app to fetch YouTube transcripts and I’m having trouble implementing yt-dlp-exec in my Node.js/Express backend. I’m relatively new to JavaScript and have built most of this with AI assistance, but now I’m stuck.

The Problem
When I try to fetch transcripts, I get various errors depending on the implementation. The frontend works fine, but the backend API using yt-dlp-exec fails to properly retrieve transcripts.

My Setup
Frontend: Vanilla JavaScript

Backend: Node.js + Express

Using yt-dlp-exec v1.0.2

Errors I’m Getting
Sometimes the process just hangs with no response

Other times I get “No subtitles found” even when I know captions exist

For playlists, I often get timeouts

What I’ve Tried
Verified yt-dlp is installed on my system

Tried different YouTube videos (some with official captions, some with auto-captions)

Added various flags like –write-subs and –sub-lang en

Tested with both yt-dlp-exec and the original youtube-dl-exec

Questions:

Is there a better way to implement YouTube transcript fetching in Node.js?

Are there specific options I should be passing to yt-dlp-exec for reliable transcript fetching?

How can I handle playlists more efficiently?

Should I be using a different approach entirely?