Why is Wasm error breaking out of try/catch

I’m running an app on AWS Lambda & calling a function which internally uses WASM. I’m wrapping this function call inside a try/catch block but when there’s a WASM error it’s not handled in the catch block & crashes the app.

Does WASM errors not respect Javascript’s try/catch blocks? Any way to not crash the app due to WASM errors?

        try {
            const signatures = await myFunction();
            return signatures?.signatures?.sig1?.signature || ''
        } catch (e: any) {
            logMessage('FAILURE', {
                error: e,
                jsParams: {
                    ...this.jsParams,
                    toSign: ethers.utils.arrayify(hash),
                    sigName: 'sig1'
                },
                ipfsId: this.ipfsId
            })
            return ''
        }

I have wrapped it in even deeper levels of try/catch to no avail, simply when we get this error when calling our function: invalid DER: unknown/unsupported ASN.1 DER tag: 0x0d our Lambda crashes with Unhandled Promise Rejection.

node – check filename to avoid pushing them into array

I have this code in my node script

const fs = require('fs-extra');

const backupPath = path.join( __dirname , 'wp-backup');
const excludedResources = ['.DS_Store', 'dep.js', 'node_modules'];
const wpFolders = [];
const wpFiles = [];

fs.readdir( __dirname, { withFileTypes: true }, (err, files) => {
    if( err ) {
        console.log(err);
    }
    files.forEach( (file, i) => {
      const srcPath = path.join( __dirname, file.name);
      const destPath = path.join( backupPath, file.name );
         //
         if( file.isDirectory() ) {
            console.log(file.name);
            if( !fs.existsSync( destPath ) ) {
              fs.mkdir( destPath, (err) => {
                wpFolders.push( srcPath );
              });
            }
          } else {
            console.log(file.name);
            wpFiles.push( srcPath );
          }
    });
});

After I’ve readed the folder contents where the script will be placed, I want to check for the file names to check and skip the files that are into the excludedResources array to be pushed into the designed array. What is the best javascript function I can use to achive this?

export Key or Undex out of JQuery .each loop

My .each loop does not return a variable which has to be accessible from outside the loop.

I’m coding an E-Gretting-Card web app. After selecting the Card a sender can add as many recipients as desired through a form containing dynamic row additions with a + sign button.

each row has:

  • Column 1 (Email_Address text field)
  • Column 2 (Recipient_Name text field)
  • Column 3 (Add New Row + button)

Everything works like magic, except for a small detail.
I need to add the var new_recipients_count in the text field placeholder
and other areas in the HTML outside the placeholder.

I am getting the proper updated var new_recipients_count only outside the placeholder
through document.getElementById("showCount").innerHTML

The var new_recipients_count only displays correctly outside the loop when I test it with a value
at a variable hard coded right before the row HTML.

But it fails to spawn an new row altogeter when I attempt to display the real value from the .Each loop
here’s the code:

if ($("##recipients .emailRemoveTo").length < 19) {
  var new_recipients_count = 0;

  $.each($("#recipients .address"), function(i, o) {
    document.getElementById("showCount").innerHTML = i; // ## DISPLAY THE INPUT             
    var new_recipients_count = (i + 1);
    document.getElementById("showNewCount").innerHTML = new_recipients_count;
    return new_recipients_count;
  });
  new_recipients_count = 12; //* ONLY A TEST  *//
  var newRow = '<div class="row recipient"><div class="col-xs-8"><input type="text" name="Email_Address" id="Ad_Email" class="form-control email_address" placeholder="  ' + new_recipients_count + ' "><font size="+1"><b><span id="showCount" style="background-color:#FFFF00; padding: 3px; border:1px solid #000000"></span></b></font></div><div class="col-xs-3"><input type="text" name="Recipient_Name" class="form-control placeholder="Enter Your Name" value=""></div><div class="col-xs-1"><a href="javascript:;" class="addEmailRow"><span class="glyphicon glyphicon-plus"></span></a></div>';
});

I’m a novice regarding Jquery, 99 % of this code is from code examples copy/paste and I’m amazed that it almost works perfectly as I need it, but I dont know how to expórt a value from an .each loop which needs to be printed in a fields placeholder.

Saving the state of a HTML webpage after logging in [closed]

i am making a website where users can log in and use skill trees to learn calisthenics by starting at a starter skill and unlocking various skills by learning unlocked skills and get points and a score for doing so. I am using Flask, JavaScript, HTML and CSS to make this. Currently, users can register, log in and use the skill tree, gaining points and unlocking skills, however when they click off onto another page, and then return, muscleup.html restarts back to its initial state with all the skills as locked. I want it so even if a user clicks off or logs out, their progress in the html page saved.

I do not know what to do

Quiz creation JavaScript

I try to create one quiz page I’m passing data from the database I have attached the sample data also the key is similar in all the 3 databases the show element and hide elements are not working as expected but the start timer and displaying first question are doing correctly and I have basic CSS only. Kindly focus only on js to display only one question at a time

The sample data from data base

D={key1:[[questioned, question text1, option1, option2, option3, option4, option5, option6, option7,option8],
[questioned, question text2, option1, option2, option3, option4, option5, option6, option7,option8],
[questioned, question text3, option1, option2, option3, option4, option5, option6, option7,option8],
]
key2:[[questioned, question text4, option1, option2, option3, option4, option5, option6, option7,option8],
[questioned, question text5, option1, option2, option3, option4, option5, option6, option7,option8],
[questioned, question text6, option1, option2, option3, option4, option5, option6, option7,option8],
]
key3:[[questioned, question text7, option1, option2, option3, option4, option5, option6, option7,option8],
[questioned, question text8, option1, option2, option3, option4, option5, option6, option7,option8],
[questioned, question text9, option1, option2, option3, option4, option5, option6, option7,option8],
]
}
B={key3, key2, key1}
C={key1:[60]key2:[30], key3:[50]}

The code

<!DOCTYPE html>
<html lang="en">


<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    body {
      margin: 0;
      padding: 0;
      display: flex;
      transition: background-color 1s;
    }
    
    #div1,
    #div2,
    #div3,
    #div4,
    #questionDiv {
      border: 1px solid #000;
      margin: 10px;
      padding: 10px;
    }
    
    .numberBox {
      border: 1px solid #000;
      width: 30px;
      height: 30px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      margin: 5px;
      cursor: pointer;
    }
    
    #questionDiv button {
      margin: 5px;
    }
  </style>
</head>


<body>


  <div id="div1">
    <!-- Append keys from B dynamically using JavaScript -->
  </div>
  <div id="div2">
    <!-- Content will be dynamically populated by JavaScript -->
    <button onclick="sectionend()">SECTIONSUBMIT</button>
  </div>
  <div id="div3">
    <!-- Timer will be displayed here -->
    <h1 id="timerDisplay">Time Remaining: 0 seconds</h1>
    <button onclick="sectionend()">SECTIONSUBMIT</button>
  </div>
  <div id="div4">
    <button id="markForReview" onclick="markForReview()">Mark for Review</button>
    <br>
    <button onclick="saveAndNext()">Save & Next</button>
    <br>
    <button onclick="clearResponse()">Clear Response</button>
    <br>
    <button onclick="submit()">Submit</button>
  </div>
  <div id="questionDiv1">
    <form method="POST" action="{% url 'submit_exam' %}">
      {% csrf_token %}
      <input type="hidden" name="examname" value="{{ exam }}">
      <div id="questionDiv"></div>
      <button>submit</button>
    </form>
    <!-- Question will be dynamically populated by JavaScript -->
  </div>


  <script>
    // Sample data
    const D = {
      {
        questions_with_sections | safe
      }
    };
    const B = {
      {
        ordered_sections | safe
      }
    };
    const C = {
      {
        timing_data_dict | safe
      }
    };


    let currentKeyIndex = 0;
    let timerSeconds = parseInt(C[B[currentKeyIndex]]);
    const selectedOptions = {};


    function populateDiv1() {
      const div1 = document.getElementById('div1');
      B.forEach(key => {
        const button = document.createElement('button');
        button.textContent = key;
        button.addEventListener('click', () => showKeyValues(key));
        div1.appendChild(button);
      });
    }


    function showKeyValues(key) {
      if (key === B[currentKeyIndex]) {
        const div2 = document.getElementById('div2');
        div2.innerHTML = '';
        const value = D[key];
        if (value) {
          for (let i = 0; i < value.length; i++) {
            const numberBox = document.createElement('div');
            numberBox.className = `numberBox ${key}-${i}`;
            numberBox.textContent = i + 1;
            numberBox.addEventListener('click', () => takeDivKey(key, i + 1));
            div2.appendChild(numberBox);
          }
        }
        startTimer();
      }
    }


    function startTimer() {
      const timerDisplay = document.getElementById('timerDisplay');


      const timer = setInterval(() => {
        timerSeconds--;


        if (timerSeconds <= 0) {
          clearInterval(timer);
          switchKey();
        } else {
          timerDisplay.textContent = `Time Remaining: ${timerSeconds} seconds`;
        }
      }, 1000);
    }



    function switchKey() {
      if (currentKeyIndex < B.length - 1) {
        currentKeyIndex++;
        timerSeconds = parseInt(C[B[currentKeyIndex]]);
        showKeyValues(B[currentKeyIndex]);
        takeDivKey(B[currentKeyIndex], 1);
        startTimer();
      } else {
        document.body.style.backgroundColor = "red";
      }
    }

    function takeDivKey(key, value) {
      const questionDiv = document.getElementById('questionDiv');
      const totalQuestionsForCurrentKey = D[key].length;
      hideElements(questionDiv);
      createFunction(key, value);
    }

    // Function to hide elements
    function hideElements(questionDiv) {
      //alert("hide called")
      const radioContainer = questionDiv.querySelector('.radio-container');
      const previousParagraph = questionDiv.querySelector('.question-text');
      //alert(radioContainer)
      //alert(previousParagraph)
      // Check if the elements exist before attempting to hide them
      if (radioContainer) {
        radioContainer.style.display = 'none';
        //alert("radio hidden")
      }
      if (previousParagraph) {
        previousParagraph.style.display = 'none';
        //alert("paragraph hidden")
      }
    }
    // Function to create new elements
    function createFunction(key, value) {
      const questionDiv = document.getElementById('questionDiv');
      const questionArray = D[key][value - 1];
      const questionText = questionArray[1];
      const options = questionArray.slice(2);
      // Show the current question
      const questionTextElement = document.createElement('text'); // Change from 'p' to 'div'
      questionTextElement.className = 'question-text';
      // Create a container for radio buttons
      const newRadioContainer = document.createElement('div');
      newRadioContainer.className = 'radio-container';
      options.forEach(option => {
        const label = document.createElement('label');
        const radio = document.createElement('input');
        radio.type = 'radio';
        radio.name = `question${questionArray[0]}`;
        radio.value = option;
        label.appendChild(radio);
        // Create a span for each option text
        const optionTextContainer = document.createElement('span');
        optionTextContainer.appendChild(document.createTextNode(option));
        label.appendChild(optionTextContainer);
        newRadioContainer.appendChild(label);
        // Check if the current option is the selected one
        if (selectedOptions[key] === option) {
          radio.checked = true;
        }
        radio.addEventListener('change', () => {
          selectedOptions[key] = option;
          handleRadioButtonChange();
        });
      });
      // Append the new container to the questionDiv
      questionDiv.appendChild(questionTextElement);
      questionTextElement.appendChild(newRadioContainer);
    }


    // Function to show elements
    function showElements(questionDiv) {
      const radioContainer = questionDiv.querySelector('.radio-container');
      const previousParagraph = questionDiv.querySelector('.question-text');

      // Check if the elements exist before attempting to display them
      if (radioContainer) {
        radioContainer.style.display = 'block';
      }
      if (previousParagraph) {
        previousParagraph.style.display = 'block';
      }
    }



    function markForReview() {
      const currentKey = B[currentKeyIndex];
      const questionDiv = document.getElementById('questionDiv');
      const selectedRadioButton = questionDiv.querySelector('input[name^="question"]:checked');
      const numberBoxes = document.getElementsByClassName('numberBox');


      if (selectedRadioButton) {
        const questionIndex = parseInt(selectedRadioButton.name.replace('question', ''), 10) - 1;
        const currentNumberBox = numberBoxes[questionIndex];
        currentNumberBox.style.backgroundColor = 'violet';
        currentNumberBox.innerHTML = '✔';
        switchToNextQuestion();
      } else {
        const currentNumberBox = numberBoxes[currentKeyIndex];
        currentNumberBox.style.backgroundColor = 'red';
        switchToNextQuestion();
      }
    }


    function saveAndNext() {
      switchToNextQuestion();
    }


    function clearMarkedForReview() {
      const currentKey = B[currentKeyIndex];
      const questionDiv = document.getElementById('questionDiv');
      const selectedRadioButton = questionDiv.querySelector('input[name^="question"]:checked');


      if (selectedRadioButton) {
        const questionIndex = parseInt(selectedRadioButton.name.replace('question', ''), 10) - 1;
        const numberBoxes = document.getElementsByClassName('numberBox');


        const currentNumberBox = numberBoxes[questionIndex];
        currentNumberBox.style.backgroundColor = '';
        currentNumberBox.innerHTML = '';
      }
    }


    function switchToNextQuestion() {
      const currentKey = B[currentKeyIndex];
      const questionDiv = document.getElementById('questionDiv');
      const selectedRadioButton = questionDiv.querySelector('input[name^="question"]');


      const questionIndex = parseInt(selectedRadioButton.name.replace('question', ''), 10);
      // const currentQuestionID = D[currentKey][questionIndex];
      alert(questionIndex)
      let nextQuestionIndex = -1;


      for (let i = 0; i < D[currentKey].length; i++) {
        if (D[currentKey][i][0] === questionIndex) {
          nextQuestionIndex = (i + 1);
          alert(nextQuestionIndex)
          alert(D[currentKey].length)
          break;
        }
      }


      if ((nextQuestionIndex !== -1) && (nextQuestionIndex < D[currentKey].length)) {
        takeDivKey(currentKey, (nextQuestionIndex + 1));
        handleRadioButtonChange();
      } else {
        handleRadioButtonChange(selectedRadioButton);
        alert("Wait for the timer to end or move to the next key");
        handleRadioButtonChange();
      }
    }


    function sectionend() {
      switchKey();
    }


    function clearResponse() {
      const questionDiv = document.getElementById('questionDiv');
      const selectedRadioButton = questionDiv.querySelector('input[name^="question"]:checked');


      if (selectedRadioButton) {
        selectedRadioButton.checked = false;
        clearMarkedForReview();
        handleRadioButtonChange(selectedRadioButton);
      }
    }


    function submit() {
      alert("Submitted");
    }


    function sectionSubmit() {
      switchKey();
    }


    function handleRadioButtonChange() {
      const currentKey = B[currentKeyIndex];
      const questionDiv = document.getElementById('questionDiv');
      const numberBoxes = document.getElementsByClassName('numberBox');


      const checkedRadioButton = document.querySelector('input[type="radio"]:checked');


      if (checkedRadioButton) {
        const questionIndex = parseInt(checkedRadioButton.name.replace('question', ''), 10);
        let nextQuestionIndex = -1;


        for (let i = 0; i < D[currentKey].length; i++) {
          if (D[currentKey][i][0] === questionIndex) {
            nextQuestionIndex = i;
            break;
          }
        }


        if (nextQuestionIndex !== -1) {
          const currentNumberBox = numberBoxes[nextQuestionIndex];


          if (currentNumberBox) {
            currentNumberBox.style.backgroundColor = 'green';


            const selectedOption = checkedRadioButton.value;
            //alert(selectedOption);
            selectedOptions[currentKey] = selectedOption;
          }
        }
      } else {
        const currentNumberBox = numberBoxes[currentKeyIndex];
        if (currentNumberBox) {
          currentNumberBox.style.backgroundColor = 'red';
        }
      }
    }


    populateDiv1();
    showKeyValues(B[0]);
    takeDivKey(B[0], 1);
  </script>
</body>


</html>

how to make the random number generated saved in an array in local storage and then after time generate another one without deleting the previous one

    function runAtSpecificTime(hour, minutes, func){

        let twentyFourHours = 10000;
        let now = new Date();
        let eta_ms = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hour, minutes, 0,      0).getTime() - now;

    if(eta_ms < 0){
        eta_ms += twentyFourHours;
    }
    setTimeout(() => {
        func();
        setInterval(func,twentyFourHours);
    }, eta_ms);
}
runAtSpecificTime(1,27,() =>{
    let min = 22;
    let max = 24;
    result = Math.random().toFixed(1) * (max - min) + min;
    localStorage.setItem("temp" , JSON.stringify(result))
});

in this code i already generate the random number but when i save it in localstorage the value change with time i need to save the first value in the array and add the other value to the array

Remove author link from recent comments widget

1st of all, I know how to add custom widget, BUT! I want to use default WP widget of recent comments. And by default the author’s name – is a link to his URL, or on his page on this site… like : site.com/author/author_name . I’m looking for hook to remove this. On front-end it looks like:
<a class="wp-block-latest-comments__comment-author" href="site/author/authorname/">authorname</a>
I found in /wp-includes/blocks/latest-comments.php some condition:

            $author_url         = get_comment_author_url( $comment );
            if ( empty( $author_url ) && ! empty( $comment->user_id ) ) {
                $author_url = get_author_posts_url( $comment->user_id );
            }

And anyway in that @name@ – link…. how to remove this? Make some like: <b>Authorname</b>

I tried a bunch of methods and no effect…

add_filter( 'get_comment_author_link', 'remove_comment_author_link', 10, 3 );

function remove_comment_author_link( $author_link, $author, $comment ) {
    return esc_html( $author );
}

no effect

Delete cookie set by root domain in subdomain

Root domain
Sets a cookie that has the domain set to .example.com

Subdomain: sub.example.com
I can read the cookie from the root domain.

I have an express app, which should clear the cookie after an action. I am using res.clearCookie('cookie-name') function.

Am I missing something really obvious? Or we cannot delete cookies that aren’t set by the subdomain.

Can I block third-party ads on the WordPress Website?

I have created a movie website using API from different websites. The problem I am facing is that this third-party content carries many ads displayed on my website. I want to bypass these ads from my website.

Someone told me you can block these ads from displaying on your website with JavaScript.

Here is the page with ads: https://pbctimes.com/123/movies/the-swimmers/

You can check the ads that automatically take you to some websites as you click to play movies. Not to mention that the movie gets played after 4 or 5 times a user gets redirected to ads.

Input range slider with specific number

I contain a slider which uses an input range the current numbers are

12, 24, 36, 48, 60

I need to add the ability to contain

24, 36, 48, 60, 120

<input type="range" data-id='slider1RangePicker' name="range"
       class="form-range slider range" min="24" max="120" step="12"
       id="slider1">

<ul class="range-labels">
 <li class="active selected">24</li>
 <li>36</li>
 <li>48</li>
 <li>60</li>
 <li>120</li>
</ul>

previously I would set the min as 12 max as 60 and then a step of 12 which allows it to range correctly.

However with adding 120 and removing 24 and setting the min max accordingly the step number no longer works because of the 60-120 jump.

How would I solve this?

Bootstrap-datepicker not triggering ‘show’ event on when I change year for half-yearly calendar

I am using bootstrap-datepickertext for rendering half yearly calendar by manipulating monthly calendar as shown in the code-

`$.fn.datepicker.dates[‘halfyears’] = {
days: [“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”],
daysShort: [“Sun”, “Moon”, “Tue”, “Wed”, “Thu”, “Fri”, “Sat”],
daysMin: [“Su”, “Mo”, “Tu”, “We”, “Th”, “Fr”, “Sa”],
months: [“H1”, “H2″],
monthsShort: [”                 H1            ” , ”                 H2            “],
today: “Today”,
clear: “Clear”,
format: “mm/dd/yyyy”,
titleFormat: “MM yyyy”,
weekStart: 0
};

let that=this;
$('#date-picker-input').datepicker({
    format: "MM yyyy",
    minViewMode: 1,
    autoclose: true,
    language: "halfyears",
    forceParse: false,
}).on("show", function(event) {
 $(".month").css({"width" : "100%"}).each(function(index, element) {
   if (index > 1) $(element).hide();
 });

})`

enter image description here
the issue is when I click on left arrow of calendar to change the year ‘show’ event is not triggered.

Ideally it should be triggered.
can you tell what am I missing?

“Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client” when trying to detect duplicates in my database

I have a backend written using express.js which does the standart CRUD ops. I am using sequalizer as my ORM. Here’s the code:

import { Sequelize} from 'sequelize';
import User from '../Models/User.js';
import bcrypt from 'bcrypt';
async function getUserByUsername(username) {

try {
    // Find a user record with the specified username
    const foundUser = await User.findOne({
        where: {
            username: username
        }
    });

    // Check if the user was found
    if (foundUser) {
        return true;
    } else {
        false;
    }
} catch (error) {
    console.error('Error finding user:', error);
}
   }

 const sequelizer = new Sequelize.Sequelize({
    dialect: 'sqlite',
    storage: 'DergiKullanicilar.db'
  });



const createUser = async (req,res)=>{
const data = req.body ?? {};


const user = {username : data.username, email:data.email, password:data.password,role:data.role ?? 'user'};
if(!user.username || !user.password)
{res.status(400).json({'message': 'username and password are required'})
return;
}
//check for duplicates
if(await getUserByUsername(user.username)){
    res.sendStatus(409).json({"message":"user already exists"});
    return;
}

const salt = await bcrypt.genSalt(10);

user.password = await bcrypt.hash(user.password,salt);
try {
    // Create a new user record with the provided data
    const newUser = await User.create(user);

    // Return the newly created user record
    res.sendStatus(201);
    return
  } catch (error) {
    res.sendStatus(500);
    // Handle any errors that occur during the insert operation
    console.error('Error creating user:', error);
    throw error; // Rethrow the error to be handled by the caller
  }


       }
         export default {createUser};

The issue arises at the getUserByUsername function call and causes the entire thing to shutdown. The other cases are fine, bad request, server errors etc.

Best way to check if an array of objects contains duplicates

What is the best way to return information about duplicates in typescript from a large array of objects (I want it to return true or false).

let testArray: { id: number, name: string }[] = [
    { "id": 0, "name": "name1" },
    { "id": 1, "name": "name2" },
    { "id": 2, "name": "name3" },
    { "id": 3, "name": "name4" },
    { "id": 2, "name": "name3" },
    { "id": 2, "name": "name3" }
];

What is the actual, correct way of defining forms in HTML? [duplicate]

The standard way to define a web form, according to MDN, is to use an “action” attribute and send a GET request to some URL handling the request. But, depending on “target” attribute, this will either redirect the user to another page or open another tab, which is almost always not the behavior that you want.

Given the above: what is the correct way to define a modern form in HTML/JS – one that sends an HTTP request to a given URL in a background and doesn’t redirect the user anywhere?

How to make React Flow’s floating edges solution to display default edge labels?

So I’m trying to make an editable flowchart with React Flow. Floating edges are a must have, because otherwise the layout looks like a mess. But in their provided example the edge labels are missing and they don’t show up with the default way with just adding a ‘label’ prop. It works with default edges, but not the custom floating edges.

I have been trying to make it work with labels, but I just can’t.

I tried adding the label prop in different ways, even trying to use EdgeLabelRenderer but to no awail.