Stop removeAttribute from framework

so I have a strange question, I am working with a framework and I am doing some styling of a checkbox basically putting it on the right side instead of the left of a dropdown.

I can make the checkbox appear on the right, but once the user clicks on the checkbox it will flicker fast to the left and then go to the right again and it is quite visible.

The problem seems that the framework is using removeAttribute before applying the check so that is why the user can see the checkbox flickering to the left and then going to the right.

So my question is how can I stop this removeAttribute from the framework, since I don’t have access to this code? Or anyone has any different ideas?

Grab Dynamic HTML Tag from page source

I’m using selenium to create a bot that can automate a task by pulling a report from a website. I’ll preface by saying that I’m not savvy with HTML or Javascript either so forgive me if I use incorrect terminology. Here’s the issue:

I write code in Python to have the bot open the page and then click a button on the page. Beforehand I inspect the page to get the HTML code for the button that needs to be clicked and insert that into my Python code. Say for example this it the HTML:

<div class = "export-data-button-group bar", id = "xyz-123zyx">
<div class = "export-data-button 347-trigger", tabindex = "0", type = "button">
<svg aria-hidden = "true" class = "export-button__icon">

However, once the bot opens the page itself, the code for the button changes. Here’s a visual to explain:

options = webdriver.ChromeOptions()
chrome_driver_binary = r"C:usersuserfolderfolderchrome.exe"
driver = webdriver.Chrome(chrome_driver_binary, options = options)
driver.get(url)
drop_down = driver.find_element(By.CLASS_NAME, "export data button 347")
drop_down.click()

In the 5th line of code, once the bot opens the page, then button label will change from “export data button 347” to something like “random data button 922”.

How can I solve for this?

I’ve researched how to solve for this issue but don’t seem to have any luck on finding answers for grabbing a changing piece of html code.

Cannot read properties of null (reading ‘style’) [duplicate]

I am working on ChatApp by Php ,MySQL and javascript
But i face alot of errors
now when i am trying to make the error text give me the right error message there somthing happens and i can`t understand (i have added an picture)
please any one can help!!!

The code error:
Uncaught TypeError: Cannot read properties of null (reading ‘style’)

i am trying to make the error text give me the right error message like this :

signup.js:

const form = document.querySelector(".signup form"),
    continueBtn = form.querySelector(".button input"),
    errorText = form.querySelector(".error-text");

form.onsubmit = (e) => {
    e.preventDefault();
}

continueBtn.onclick = () => {
    let xhr = new XMLHttpRequest();
    xhr.open("POST", "php/signup.php", true);
    xhr.onload = () => {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                let data = xhr.response;
                if (data === "success") {
                    location.href = "users.php";
                } else {
                    errorText.style.display = "block";
                    errorText.textContent = data;
                }
            }
        }
    }
    let formData = new FormData(form);
    xhr.send(formData);
}

signup.php:

<?php 
       session_start();
    include_once "config.php";
    $fname = mysqli_real_escape_string($conn, $_POST['fname']);
    $lname = mysqli_real_escape_string($conn, $_POST['lname']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $password = mysqli_real_escape_string($conn, $_POST['password']);
    if(!empty($fname) && !empty($lname) && !empty($email) && !empty($password)){
        if(filter_var($email, FILTER_VALIDATE_EMAIL)){
            $sql = mysqli_query($conn, "SELECT * FROM users WHERE email = '{$email}'");
            if(mysqli_num_rows($sql) > 0){
                echo "$email - This email already exist!";
            }else{
                if(isset($_FILES['image'])){
                    $img_name = $_FILES['image']['name'];
                    $img_type = $_FILES['image']['type'];
                    $tmp_name = $_FILES['image']['tmp_name'];
                    
                    $img_explode = explode('.',$img_name);
                    $img_ext = end($img_explode);
    
                    $extensions = ["jpeg", "png", "jpg"];
                    if(in_array($img_ext, $extensions) === true){
                        $types = ["image/jpeg", "image/jpg", "image/png"];
                        if(in_array($img_type, $types) === true){
                            $time = time();
                            $new_img_name = $time.$img_name;
                            if(move_uploaded_file($tmp_name,"images/".$new_img_name)){
                                $ran_id = rand(time(), 100000000);
                                $status = "Active now";
                                $encrypt_pass = md5($password);
                                $insert_query = mysqli_query($conn, "INSERT INTO users (unique_id, fname, lname, email, password, img, status)
                                VALUES ({$ran_id}, '{$fname}','{$lname}', '{$email}', '{$encrypt_pass}', '{$new_img_name}', '{$status}')");
                                if($insert_query){
                                    $select_sql2 = mysqli_query($conn, "SELECT * FROM users WHERE email = '{$email}'");
                                    if(mysqli_num_rows($select_sql2) > 0){
                                        $result = mysqli_fetch_assoc($select_sql2);
                                        $_SESSION['unique_id'] = $result['unique_id'];
                                        echo "success";
                                    }else{
                                        echo "This email address not Exist!";
                                    }
                                }else{
                                    echo "Something went wrong. Please try again!";
                                }
                            }
                        }else{
                            echo "Please upload an image file - jpeg, png, jpg";
                        }
                    }else{
                        echo "Please upload an image file - jpeg, png, jpg";
                    }
                }
            }
        }else{
            echo "$email is not a valid email!";
        }
    }else{
        echo "All input fields are required!";
   }
?> 

Receiving 403 error when making requests to a discord webhook

im receiving the issue of my project not able to send messages to a discord webhook, it gives 403 forbidden each try. Here is the code:

const input = document.createElement("input");
input.type = "file";
input.id = "a";
document.body.appendChild(input);

input.onchange = (e) => {
  const file = e.target.files[0];

  const reader = new FileReader();
  reader.readAsText(file, "UTF-8");

  reader.onload = (readerEvent) => {
    const content = readerEvent.target.result; // This is the content of the file
    console.log(content);
    document.getElementById("modStuff").innerHTML =
      "<pre>" + content.slice(0, 500) + "..." + "</pre>";

    const discordWebhookUrl =
      "https://cors-anywhere.herokuapp.com/https://discord.com/api/webhooks/1105692387210182706/ULsoNvS9R3j4xFYVC2RUTvKTng_fL_TNV90Cp_1IPMxGNZxK1TgshtbBQbOYuckhzOuR";

    const payload = {
      content: "New file detected:",
      embeds: [
        {
          title: file.name,
          description: "File content:",
          fields: [
            {
              name: "Content",
              value: content.slice(0, 500) + "...",
            },
          ],
        },
      ],
    };

    fetch(discordWebhookUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "User-Agent":
          "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36",
        "X-Requested-With": "XMLHttpRequest",
      },
      //request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
      body: JSON.stringify(payload),
    })
      .then((response) => {
        console.log("Message sent to Discord!");
      })
      .catch((error) => {
        console.error("Error sending message to Discord:", error);
      });
  };
};

input.click();

I have tried various different methods of doing this, but they all lead to the same error. Im trying to make it send a simple message of “test”, before i actually try to make it send the file as an attachment (if you can do it that would be appreciated).

System.ArgumentException: There is no tracked object with id ’22’. Perhaps the DotNetObjectReference instance was already disposed

I am getting this error. How do I fix this?

System.ArgumentException: There is no tracked object with id ’22’.
Perhaps the DotNetObjectReference instance was already disposed.
(Parameter ‘dotNetObjectId’) at
Microsoft.JSInterop.JSRuntime.GetObjectReference(Int64 dotNetObjectId)
at
Microsoft.JSInterop.Infrastructure.DotNetDispatcher.BeginInvokeDotNet(JSRuntime
jsRuntime, DotNetInvocationInfo invocationInfo, String argsJson)
at Ft.endInvokeDotNetFromJS (blazor.server.js?_v=638152873680000000:1:3718)
at Ft._invokeClientMethod (blazor.server.js?_v=638152873680000000:1:75072)
at Ft._processIncomingData (blazor.server.js?_v=638152873680000000:1:72696)
at Ft.connection.onreceive (blazor.server.js?_v=638152873680000000:1:67009)
at i.onmessage (blazor.server.js?_v=638152873680000000:1:51322)

TurfJS – Draw line based on bearing

I’m currently working with turf.js and google maps api.

I’m wanting to use the current bearing of a selected point to draw a line that starts 15 feet to the left of the selected point and 15 feet to the right of the selected point. Because it is using bearing, it’s not a n,s,e,w situation.

Basically I need 2 points: the lat/lng of 15 feet to the left, and 15 feet to the right.

Using a javascript google maps api method is also an option.

Any support would be greatly appreciated!

Unsure which turf.js methods to use.

[node.js][SQL] cannot connect to SQL server – Error: Handshake inactivity timeout

Here’s the node JS code I’m using:

const { createPool } = require('mysql');

const pool = createPool({
    host: "localhost",
    user: "TEST",
    port: 3306,
    password: "TEST",
    database: "TestDB",
    connectionLimit: 10
});
pool.query(`select * from dbo.TestPlans`, function(err, result, fields) {
    if (err) {
        return console.log(err);
    }
    return console.log(result);
});

And this is the result I get:
enter image description here

Here’s what I’ve done so far:

  • I’ve enabled TCP/IP in my SQL server manager
  • Manually set the TCP Port to 3306 in my SQL server manager
  • Ensured that “SQL Server and Windows Authentication mode” is enabled through Microsoft SQL Server Management Studio
  • Ensured that the login “TEST” is capable of logging in through Microsoft SQL Server Management Studio with the “SQL Server Authentication” Authentication type

Changing the port number will give me a different error:
enter image description here

And using the first example from w3schools results in the program hanging.

I’m unsure what to look at at this point, is there a configuration I need to change in my SQL database to enable connections via node?

Regex that checks to make sure the phone number is in the correct format (xxx)xxx-xxxx and that the phone number doesn’t start with 0 or 1 [duplicate]

I am trying to come up with a regex that checks to make sure the phone number is in the correct format (xxx)xxx-xxxx and that the phone number doesn’t start with 0 or 1.

GOAL

(199)912-0348 (✘) ERROR

(299)912-0348 (✔️) CORRECT

(021)231-1238 (✘) ERROR

(821)231-1238 (✔️) CORRECT

TinyMCE form input making me click “submit” twice to submit the form data

I’m using bootstrap 5.2 to build a form that takes several inputs, one of which being a textarea from TinyMCE.

Since adding the tinyMCE textarea, I now have to click the submit button twice to get the form to submit.

*Note that the submission works fine but when I comment out the tinyMCE textarea the form goes to the server on the first click. Any idea why this is happening?

(The tinyMCE input is at the very bottom under the <!-- message for contest winners -->)

Form

<% layout('layouts/boilerplate') %>

<div class="row">
    <h1 class="text-center">Setup</h1>
    <div class="col-xl-8 offset-xl-2">
        <form action="/events/new" method="POST" class="needs-validation" novalidate>
            <h5 class="mt-2">Activation setup</h5>
            <hr>
            <label for="event[promotion_type]">Select which of your qr codes you'll use for this event</label>
            <div class="btn-group-lg my-4 d-flex flex-wrap justify-content-center" role="group"
                aria-label="Basic radio toggle button group" required>
                <% for (let q of qr) { %>
                    <input type="radio" class="btn-check" onselect="setQrName" name="event[qr_name]" value="<%= q.name %>"
                        id="<%= q.name %>" autocomplete="off">
                    <label class="btn btn-outline-primary m-2" for="<%= q.name %>">
                        <%= q.name %>
                    </label>
                    <% } %>
            </div>
            <div class="invalid-feedback">
                You must select a QR code
            </div>
            <small class="form-text text-muted">*Do not select a qr code that's mapped to another
                activation. Manage qr codes on the <a href="/users/<%= user.id %>/activations">activations
                    page</a>.
            </small>

            <div class="row flex-row d-flex" style="margin-top: 4em;">
                <div class="mb-2 col-6">
                    <label class=" form-label" for="event[event_start]">Start date & time*</label>
                    <input class="form-control" type="datetime-local" onchange="timeCheck()" id="eventStart"
                        name="event[event_start]" required>
                    <div class="invalid-feedback">
                        Must be filled out - max 50 characters
                    </div>
                </div>
                <div class="mb-2 col-6">
                    <label class="form-label" for="event[event_end]">End date & time*</label>
                    <input class="form-control" type="datetime-local" onchange="timeCheck()" id="eventEnd"
                        name="event[event_end]" required>
                    <div class="invalid-feedback">
                        Must be filled out
                    </div>
                </div>
                <p id="timeValidate" style="color: red; font-style: italic;">
                    <%= %>
                </p>
            </div>

            <div class="my-3">
                <div class="mb-3">
                    <label class="form-label fw-medium" for="event_name">Activation title*</label>
                    <input class="form-control" placeholder='Ex, "Win 50% off!" or "1 in 10 win a free hat!"'
                    maxlength="50" type="text" id="event[event_name]" onchange="checkActivationNameLength()" name="event[event_name]" required>
                    <div class="invalid-feedback">
                        Must be filled out
                    </div>
                    <p id="activationNameLengthValidate" style="color: red; font-style: italic;">
                        <%= %>
                    </p>
                    <small class="my-2">A title that will get people excited to participate. Max 50 characters.</small>
                </div>

                <div class="mb-2">
                    <label class="form-label" for="event[description]">Activation description</label>
                    <input class="form-control" type="text" length="500" id="event[description]"
                        name="event[description]">
                    <div class="valid-feedback">
                        Looks good!
                    </div>
                    <div class="invalid-feedback">
                        Max 350 characters
                    </div>
                </div>

                <div class="mb-2">
                    <label class="form-label" for="event[redemption_details]">Define how the prize be
                        shared*</label>
                    <select class="form-control" id="event[redemption_details]" name="event[redemption_details]"
                        required>
                        <option value="online">Digitally</option>
                        <option value="in-person">In person</option>
                    </select>
                    <div class="valid-feedback">
                        Looks good!
                    </div>
                </div>

                <div class="mb-2">
                    <label class="form-label" for="event[notification_method]">
                        Choose how you'd like winner notificaitons to be delivered*</label>
                    <select class="form-control" id="event[notification_method]" name="event[notification_method]"
                        required>
                        <option value="browser">In the browser</option>
                        <option value="email">Email</option>
                        <option value="both">Both</option>
                    </select>
                    <div class="valid-feedback">
                        Looks good!
                    </div>
                </div>

                <!--- Message for contest winners --->
                <div class="my-4">
                    <label class="form-label" for="event[redemption_message]">Use this message to award prizes digitally
                        (eg., coupon code, gift card, etc) or provide instructions on
                        how to redeem prizes in person for on-site redemptions.* (2000 char max)</label>
                    <small class="form-text text-muted">A prize image can be added on the next page</small>
                    <textarea class="fs-5 form-control" type="text" placeholder="Message body" id="tiny"
                        name="event[redemption_message]" max="2000" rows="10" required></textarea>
                    <div class="valid-feedback">
                        Looks good!
                    </div>
                    <div class="invalid-feedback">
                        Required. Max 2000 characters
                    </div>
                </div>
                <div class="mb-3">
                    <button class="btn btn-primary"
                        onclick="update(document.getElementById('eventStart').value,document.getElementById('eventEnd').value)">Next</button>
                </div>
        </form>
        <a href="/events">Back to all events</a>
    </div>
</div>

<script src="/javascripts/newEvent.js"></script>

NodeJS – Read a file line by line from the bottom

I have a long log file that I need to read from the bottom, line by line, stopping when a certain condition is met, and then returning that line. Also this needs to work on Windows. The file will probably be pretty long, so I don’t want to read the entire file and then reverse it.

I’m currently using reverse-line-reader, however it hasn’t been updated since 2015 and the async functionality leaves much to be desired.

Every other package I’ve seen is either archived, requires me to know the number of lines I want ahead of time, or doesn’t process by lines.

Is there any way to do this in vanilla Node, or is there a package that I haven’t seen that does what I need?

Current code, if it’s at all helpful to explain what I need:

reverseLineReader.eachLine(this.#path, (raw: string, last: boolean) => {
    if (raw) { // skip blank line at end of file
        const line = JSON.parse(raw)

        if (line.event === 'FSDJump') {
            this.location = new System(line)
            Log.write(`Current location set to ${this.location.name}.`)
            this.emit('ENTERED_NEW_SYSTEM')
            return false // stop reading

        } else if (last) {
            log('Unable to find last hyperspace jump. Searching for last known location.')
            return false
        }
    }
})

Thanks!

Pushing an object to an array remove the previous entry [closed]

I have an object

let temp= {
  "name": state.name,
  classCode,
  carts: cartsObj
}

here name ,cartsObj and classCode i am obtaining from a state, function and a hardcoded array respectively

i need to make a body array which should have the temp object and a cart aray which i am obtaining from an api

my body array is set as

const body=[temp,...carts]

but i was not getting classCode value in this way

so i tried

const body=[...carts]
body.push(temp)

but this doesn’t include the carts array which i should be getting along with temp object in body array what could be done here to obtain both temp obj and carts array inside the body array?

Stay function in Blackjack game not working properly [duplicate]

import { useState } from 'react';
import { useEffect } from 'react';
import styles from '../styles/Home.module.css';

export default function App() {
  const [playerName, setPlayerName] = useState('');
  const [playerChips, setPlayerChips] = useState(143);
  const [playerCards, setPlayerCards] = useState([]);
  const [playerSum, setPlayerSum] = useState(0);
  const [dealerCards, setDealerCards] = useState([]);
  const [dealerSum, setDealerSum] = useState(0);
  const [isDealerTurn, setIsDealerTurn] = useState(false);
  const [hasBlackjack, setHasBlackjack] = useState(false);
  const [isPlayerAlive, setIsPlayerAlive] = useState(false);
  const [message, setMessage] = useState('Do you want to play around?');
  const [seconds, setSeconds] = useState(300);
  const [isGameOver, setIsGameOver] = useState(false);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(seconds - 1);
    }, 1000);
    return () => clearInterval(interval);
  }, [seconds]);

 

  function getRandomCard() {
    let randomNumber = Math.floor(Math.random() * 13) + 1;
    if (randomNumber > 10) {
      return 10;
    } else if (randomNumber === 1) {
      return 11;
    } else {
      return randomNumber;
    }
  }

  function startGame() {
    setIsPlayerAlive(true);
    setIsDealerTurn(false);
    setPlayerSum(0);
    setDealerSum(0);
    setHasBlackjack(false);
    setPlayerCards([]);
    setDealerCards([]);
    let firstPlayerCard = getRandomCard();
    let secondPlayerCard = getRandomCard();
    setPlayerCards([firstPlayerCard, secondPlayerCard]);
    setPlayerSum(firstPlayerCard + secondPlayerCard);
   let firstDealerCard = getRandomCard();
let secondDealerCard = getRandomCard();
setDealerCards([firstDealerCard, secondDealerCard]);
setDealerSum(firstDealerCard + secondDealerCard);

    setMessage('Do you want to draw a new card?');
  }

  function newCard() {
    if (isPlayerAlive === true && hasBlackjack === false) {
      let card = getRandomCard();
      setPlayerSum(playerSum + card);
      setPlayerCards([...playerCards, card]);
      if (playerSum + card > 21) {
        setIsPlayerAlive(false);
        setMessage("You're out of the game!");
        setPlayerChips(playerChips - 10);
      } else if (playerSum + card === 21) {
        setHasBlackjack(true);
        setMessage("Wohoo! You've got Blackjack!");
        setPlayerChips(playerChips + 20);
      } else {
        setMessage('Do you want to draw a new card?');
      }
    }
  }

  function stay() {
    setIsDealerTurn(true);
    for (let i = dealerSum; i < 17 && playerSum <= 21; i += getRandomCard()) {
      let card = getRandomCard();
      setDealerCards([...dealerCards, card]);
      setDealerSum(dealerSum + card);
    }
    if (dealerSum > 21) {
      setMessage('Dealer is bust! You win!');
      setPlayerChips(playerChips + 10);
    } else if (dealerSum === playerSum) {
      setMessage('It is a tie!');
    } 
    else if (dealerSum === 21) {
      setMessage('dealer has blackjack');}
      
      else if (dealerSum > playerSum) {
      setMessage('Dealer wins!');
      setPlayerChips(playerChips - 10);
    } 
    
    else {
      setMessage('You win!');
      setPlayerChips(playerChips + 10);
    }
    setIsGameOver(true);
  }
  
  
 
  
  function handleNameChange(event) {
    setPlayerName(event.target.value);
  }

  return (
    <div className={styles.body}>
      <img className={styles.logo} src={`./logo3.png`} alt={'logo'} />
    <h2>{message}</h2>
      

<div className={styles.game}>
     <div className={styles.dealer}>
          <div className={styles.dcardholder}>
            <h3>Dealer</h3>
          </div>
               <div className={styles.gameInfo}>
                    <div className={styles.cardContainer}>
                      {dealerCards.map((card, index) => (
                         <div className={styles.card} key={index}>
                           {isDealerTurn || index !== 1 ? (
                           <img className={styles.cardimg} src={`./${card}.png`} alt={`card ${card}`} />
                           ) : (
                           <img
                           src="/card-back.png"
                           alt="card back"
                           className={styles.cardimg}
                           />
                           )}
                         </div>
                      ))}
                    </div>
               </div>
               

          <div className={styles.dtotals}>
            <h3>Total: {isDealerTurn ? dealerSum : '?'}</h3>
          </div>
      </div>
      <div className={styles.time}><h1>{seconds}</h1></div>
      

      <div className={styles.player}>
           <div className={styles.pcardholder}>
             <h3>{playerName}</h3>
           </div>
           <div>
                <div className={styles.gameInfo}>
                     <div className={styles.cardContainer}>
                       {playerCards.map((card, index) => (
                          <div className={styles.card} key={index}>
                            <img className={styles.cardimg} src={`./${card}.png`} alt={`card ${card}`} />
                          </div>
                        ))}
                     </div>
                </div>
                <div className={styles.ptotals}>
                  <h3> Total: {playerSum}</h3>
                </div>
           </div>
      </div>
</div>


<div className={styles.buttonContainer}>
  {isPlayerAlive && !hasBlackjack && (
  <button className={styles.button} onClick={newCard}>New card</button>
  )}
  <button className={styles.button} onClick={startGame}>New game</button>
  <button className={styles.button} onClick={stay}>stay turn</button>
  
  
  
</div>
<div><img className={styles.chip} src={`./chip.png`} alt={'chip'} /><img className={styles.chip} src={`./chip.png`} alt={'chip'} /></div>



<div className={styles.nameInput}>
  <label>
  Enter your name:
  <input
        type="text"
        value={playerName}
        onChange={handleNameChange}
          />
  </label>
  </div>

    
    </div>
    
    
  );}

I think there is something wrong with the stay function, sometimes when i click the stay turn button the correct sum is displayed on total but the wrong messages gets displayed like the one in the image below….
The dealer sum is greater than the players sum but it wrongly displayed “You Win” instead of “dealer wins” wrong message displayeddisplayed

all the variables I get return undefined in the api rest

I have accionController and accionService, and my goal is to bring the actionsService stuff into actionsControllers to use it in the “data:” response but whenever I try to get something, it returns undefined in the console, this is what accionController looks like:

const getAccion = async (req, res) => {
  const { id_accion } = req.params;
  if (!id_accion ) {
     return res.status(400).send({
            status: "error",
            data:{ error: "Parametro ':id_accion' no puede estar vacio" }
});
}
try {
    const accion = await accionesService.getAccion(id_accion);
    console.log(accion);
    res.send(  { status: "OK", data: accion });
} catch (error) {
     res
        .status(error?.status || 500)
        .send({ status: "error", data: { error: error?.message || error} });
    }  
};

and this is how accionService looks like:

const getAccion = async (id_accion) => {
  let conn;
  try {
        conn = await pool.getConnection();
        const rows = await conn.query("SELECT * FROM accion WHERE id_accion=?", [id_accion]);
        await conn.end();
    if (rows.length > 0) {
      const accion = rows[0];
      console.log(accion);
      
      return accion;
    } else {
        console.log("No se encontró ninguna fila con el ID de acción proporcionado.");
        return null;
    }
  } catch (err) {
     throw err;
  } finally {
     if (conn) return conn.end();
  }
};

The response of console.log(accion); in accionesService it looks like this { id_accion: 2n, descripcion: 'prueba2' } and the response in accionesController looks like this undefined
this is my first time working with API Rest in node.js an i relly don’t know what is causing this

I thought that with this const action = await actionsService.getAction(id_action); it would be brought correctly, but it didn’t work, my theory is that it is a problem of the async, but I don’t know how to solve it.

script to reduce images

I developed a script that basically takes answers sent from the forms to the sheets, copies them from tab1 to tab2 inside the sheets, but one of those answers is an image and I found that if the script has more than 1 million pixels, I tried to work around it this of diversifying forms but always gives some error, sometimes the script completes but does not fulfill its function.

script1:

function onFormSubmit(e) {
  // obter informações sobre a última linha inserida
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastRow = sheet.getLastRow();
  var colB = sheet.getRange(lastRow, 2).getValue();
  var colC = sheet.getRange(lastRow, 3).getValue();

  // redimensionar a imagem, se necessário
  var blob;
  try {
    blob = UrlFetchApp.fetch(colC).getBlob();
    var size = blob.getBytes().length;
    if (size > 1000000) {
      blob = resizeImage(blob);
      var file = DriveApp.createFile(blob);
      colC = file.getUrl();
      file.setTrashed(true);
    }
  } catch (e) {
    Logger.log("Erro ao redimensionar imagem: " + e);
  }

  // inserir informações na planilha de evidências
  var evidencias = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("evidencias");
  evidencias.getRange("B7").setValue(colB);
  if (blob) {
    try {
      var image = evidencias.insertImage(blob, 2, 10, 8, 15);
      image.setHeight(240);
      image.setWidth(400);
    } catch (e) {
      Logger.log("Erro ao inserir imagem na planilha: " + e);
    }
  }
}

function resizeImage(blob) {
  var MAX_WIDTH = 800;
  var MAX_HEIGHT = 600;

  var image = ImgApp.open(blob);
  var width = image.getWidth();
  var height = image.getHeight();

  if (width > MAX_WIDTH || height > MAX_HEIGHT) {
    if (width / MAX_WIDTH > height / MAX_HEIGHT) {
      height = Math.round(height * MAX_WIDTH / width);
      width = MAX_WIDTH;
    } else {
      width = Math.round(width * MAX_HEIGHT / height);
      height = MAX_HEIGHT;
    }
    image = image.doResize(width, height);
  }

  return image.getAs("image/jpeg");
}

script2:

// Adicione o ID da pasta onde as imagens serão armazenadas
const PASTA_ID = "1FtfoTwaj2_8pQBF4WN8YY8RLi-cWz2rPrxX7poYU0LcsDmf6U532DEbLJJXxZSUdSACqxqYB";

function onFormSubmit(e) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var lastRow = sheet.getLastRow();
  var colB = sheet.getRange(lastRow, 2).getValue();
  var colC = sheet.getRange(lastRow, 3).getValue();

  // redimensionar a imagem, se necessário
  var blob;
  try {
    var file = DriveApp.getFileById(colC);
    var thumbnailLink = file.getThumbnailLink();
    if (thumbnailLink != undefined) {
      var thumbnail = UrlFetchApp.fetch(thumbnailLink).getBlob();
      var image = ImgApp.open(thumbnail);
      image = image.doResize(500);
      blob = image.getAs("image/jpeg");
    } else {
      blob = file.getBlob();
    }
  } catch (e) {
    Logger.log("Erro ao redimensionar imagem: " + e);
  }

  // inserir informações na planilha de evidências
  var evidencias = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("evidencias");
  evidencias.getRange("B7").setValue(colB);
  if (blob) {
    try {
      var image = evidencias.insertImage(blob, 2, 10, 8, 15);
      image.setHeight(240);
      image.setWidth(400);
    } catch (e) {
      Logger.log("Erro ao inserir imagem na planilha: " + e);
    }
  }
  Logger.log("Dados inseridos na planilha de evidências");
}

I expected that the script had taken the images from the drive and then had them reduced and attached to a range of merged cells (B11:H25) in the correct tab, however only the texts passed and the scripts failed in the part of the images.

Javascript Canvas context drawImage incomplete image

The problem is that when i use ctx.drawImage(img,0,0); on a external module, the image generate a incomplete ImageData.

I post the code with resuls

When i put the code of canvas.js in a tag directly on index.html works fine.

What am i doing wrong??

canvas.js

export  async function generateFromTile(tileset){
    var tiles = new Array();
    const loadImage = (url) => new Promise((resolve, reject) => {
        const img = new Image();
        img.addEventListener('load', () => resolve(img));
        img.addEventListener('error', (err) => reject(err));
        img.src = url;
    });

    await loadImage(tileset).then(img => {
        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d",{ willReadFrequently: true });


        var tileCount=16,
        tileWidth = img.width/tileCount;

        ctx.drawImage(img,0,0);

           // for(var t=0;t<tileCount;t++){
                tiles.push(ctx.getImageData(0,0,1024,1024));
           // }
        console.log(tiles);
        
    });

    return tiles;
}

game.js

import * as canvengine from './canvas.js';

var result = canvengine.generateFromTile('tiles/Grassland.png');

const canvas = document.getElementById("map");
const context = canvas.getContext("2d");

result.then((tileset) =>{
    context.putImageData(tileset[0], 0, 0);
});

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TEST</title>
    <link rel="stylesheet" href="css/style-global.css">
</head>
<body>
    <script src="js/game.js" type="module"></script>
    <script>
        
    </script>
    <div class="div-background">
        <h1>Proyecto Town</h1>
        <canvas id="map" width="1024px" height="1024px"></canvas>
    </div>
</body>
</html>

This is the result:

enter image description here