Eslint does not see the import error, how can I fix it?

I’m sorry for the broken English.
I use quasar using typescript code inside the file .vue (vue 3). I created the interface and imported it import { ICut, ICutMasterItem } from '@/models/cut/cut';, after which if I delete the interface ICut from the file, the project will still assemble and only the IDE will give an error, how to make the project not assemble.
enter image description here
enter image description here

I tried to find the necessary eslint rules and connected different plugins, but I didn’t work out any of them

Session is using/detected another tab opened

I met the issue of routing to wrong page and hit the error message of “Session is using/detected another tab opened”, if UUID is not found. My desired solution is it should routing to self-defined session.js and prompt self-defined message, if UUID is not found.

I used window.sessionStorage to keep the value of UUID, where UUID as a parameter to set and get the session generated by backend.
Every UI pages (cshtml) will use the UUID as the parameter in javascript and check if UUID is matched with session generated from backend. The codes are shown as below.

<script>
checkSession(window.sessionStorage.getItem("UUID"));
</script>

The function checkSession will uses ajax to access to the API and get back response.
If the response is 0, it should prompt us for the button choices of “Continue(Go back Home page)” or “Cancel”. But somehow, instead of showing the self-defined prompt, it redirect back to home page and prompt “Session is using/detected another tab opened”. The redirect code are shown as below.

window.open(parentHomeUrl, '_top')

Is there any way that do prompt correctly before going back to home page, and stop prompt the error message “Session is using/detected another tab opened”?

Could not run phased build action

ths is the error code from flutter/dart/vscode
enter image description here

im using jdk 1.8

Could not run phased build action using connection to Gradle distribution ‘https://services.gradle.org/distributions/gradle-7.6.3-all.zip’.
Unable to start the daemon process.
This problem might be caused by incorrect configuration of the daemon.
For example, an unrecognized jvm option is used.
Please refer to the User Manual chapter on the daemon at https://docs.gradle.org/7.6.3/userguide/gradle_daemon.html
Process command line: C:Program FilesJavajava-se-8u43-ribinjava.exe -Xmx4G -Dfile.encoding=utf8 -Duser.country=MY -Duser.language=en -Duser.variant -cp C:Usersblack.gradlewrapperdistsgradle-7.6.3-allaocdy2d2z8kodnny3rsumj8i8gradle-7.6.3libgradle-launcher-7.6.3.jar org.gradle.launcher.daemon.bootstrap.GradleDaemon 7.6.3
Please read the following process output to find out more:

Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
Invalid maximum heap size: -Xmx4G
The specified size exceeds the maximum representable size.

idk idk idk idkidkidkidkidkidk

How to write a custom JSON.stringify() function for preserving .0 float values from Ajax responses

I need to write a custom JSON.stringify function that ensures numbers that end with .0 retain their decimal values, like when passed through .toFixed(). I understand that this is not how javascript numbers work, the requirement comes from my users. If a value an integer and does not include a .0, it should remain an integer without a decimal place. If a value is a float, it should remain a float. And if a value is a float with any .0000… type empty value in the decimal place, it should remain a float with the same number of zeroes in the decimal place.

I have written the following function:

function monacoStringify(json: any, spacing: number) {
    return JSON.stringify(json, (key: string, value: any) => {
        if(typeof value === 'number') {
            const numString = `${value}`;
            const dotIdx = numString.indexOf('.');
            if(dotIdx !== -1) {
                const dotSplit = numString.split('.');
                const numsAfterDecimal = dotSplit[1].length;
                return value.toFixed(numsAfterDecimal);
            }
            return value;
        }
        return value;
    }, spacing)
}

export default monacoStringify;

That I directly pass the following Ajax response:

Ajax response

But the value variable on line 3 is 13, not 13.0 like it says in the developer console’s network response tab.

Is there any way to keep these values formatted exactly the way they are received?

Why is my diary section(5th) appearing/working in my teachers section(4th)?

I’m still a begginer in html, css, and javascript. I watched a tutorial on youtube and decided to try it, I added a few changes and it’s working fine, until the diary section started to appear on the teachers section, which is completely a different section.

This is the teacher section (teachers section). But as you can see (diary section), the image I put in the diary section is appearing under the teachers section, behind the elements of the teachers section.

This is the html code:

<!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>DEAR ST. LORENZO RUIZ</title>

    <!-- font awesome cdn link  -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    
    <!-- custom css file link  -->
    <link rel="stylesheet" href="css/style.css">

</head>
<body>
    

<!-- header section starts  -->

<header class="header">

    <a href="#" class="lsclogo">
        <img src="images/lsclogo.png" width="8%" height="8%" alt="">
    </a>

    <nav class="navbar">
        <a href="#headstart">headstart</a>
        <a href="#background">background</a>
        <a href="#students">students</a>
        <a href="#teachers">teachers</a>
        <a href="#diary">diary</a>
        <a href="#memes">memes</a>
        <a href="#group">group</a>
    </nav>

    <div class="icons">
        <div class="fas fa-search" id="search-btn"></div>
        <div class="fas fa-bars" id="menu-btn"></div>
    </div>

</header>

<!-- header section ends  -->


<!-- headstart section starts  -->

<section class="headstart" id="headstart">

    <div class="content">
        <h3>Dear St. Lorenzo Ruiz</h3>
        <p>Warm greetings from the one and only humble section, 9 St. Lorenzo Ruiz.</p>
    </div>

</section>

<!-- headstart section ends  -->


<!-- background section starts  -->

<section class="background" id="background">

    <h1 class="heading"> something <span>about</span> us </h1>

    <div class="row">

        <div class="image">
            <img src="images/about us.jpeg" alt="">
        </div>

        <div class="content">
            <h3>What makes us St. Lorenzo, a Lorenzo?</h3>
            <p>Some of us are blessed with inteligence, some of us are artists, musicians, singers, dancers, and many more. And Of course, hindi rin mawawala ang mga pasaway sa room, sometimes called as the geng geng boys ng lorenzo.</p> <br>
            <p>Above everything, we are all stil unique in different ways.</p>
        </div>

    </div>

</section>

<!-- background section ends  -->


<!-- students section starts  -->

<section class="students" id="students">

    <h1 class="heading"> the <span>students</span> of st. lorenzo ruiz </h1>
        
    <div class="row">
        
        <div class="column">
            <img src="images/lance.jpg" width="100%" height="100%" alt="">
            <h2>Acoba, Lance Julian</h2>
        </div>

        <div class="column">
            <img src="images/qatlyn.jpg" width="100%" height="100%" alt="">
            <h2>Altoveros, Qatlyn Rexi</h2>
        </div>

        <div class="column">
            <img src="images/justine.jpg" width="100%" height="100%" alt="">
            <h2>Asuncion, Justine Clyde</h2>
        </div>

        <div class="column">
            <img src="images/rhyeiza.jpg" width="100%" height="100%" alt="">
            <h2>Balmaceda, Rhyeiza Bless</h2>
        </div>

        <div class="column">
            <img src="images/rainier.jpg" width="100%" height="100%" alt="">
            <h2>Baltazar, Ranier</h2>
        </div>

        <div class="column">
            <img src="images/kimberly.jpg" width="100%" height="100%" alt="">
            <h2>Barakel, Kimberly Joy</h2>
        </div>

        <div class="column">
            <img src="images/harry.jpg" width="100%" height="100%" alt="">
            <h2>Bayang, Adrienne Harry</h2>
        </div>

        <div class="column">
            <img src="images/carla.jpg" width="100%" height="100%" alt="">
            <h2>Bautista, Carla Mae</h2>
        </div>

        <div class="column">
            <img src="images/jek.jpg" width="100%" height="100%" alt="">
            <h2>Carorocan, John Gerald *unable to find pictures*</h2>
        </div>
        
    </div>

</section>

<!-- students section ends  -->


<!-- teachers section starts  -->

<section class="teachers" id="teachers">

    <h1 class="heading"> the <span>teachers</span></h1>

    <div class="container">

        <div class="adviser">
            <img src="images/sireugie.jpg" width="20%" height="20%" alt="">
            <h2> Eugiemhar S. Videra </h2>
            <p> - Our one and only humble and loving adviser. Laging mabait, mainit lang ang ulo 'pag maingay ang lorenzo</p>
            <p> - Siya lagi nagpapa-ayos sa'min ng gym huhu</p>
        </div>

        <div class="comp">
            <img src="images/sirmacky.jpg" width="20%" height="20%" alt="">
            <h2> Macky Ibay </h2>
            <p> - Tatay ni vernix </p>
            <p> -Poging computer teacher</p>
        </div>

        <div class="science">
            <img src="images/sirvill.jpg" width="20%" height="20%" alt="">
            <h2> Villamor Toquero </h2>
            <p> - Pinaka mabait na science teacher</p>
            <p> - The best science teacher st. lorenzo ruiz could ever have</p>
        </div>

        <div class="english">
            <img src="images/sirace.jpg" width="20%" height="20%" alt="">
            <h2> Aceyork Claro </h2>
            <p> - Teaches english very well </p>
        </div>

        <div class="socsci">
            <img src="images/sirniño.jpg" width="20%" height="20%" alt="">
            <h2> Niño Jay Robles </h2>
            <p> - Magaling magturo ng economics (may natututunan) + hindi masyadong boring yun subject kasi siya yun nagtuturo</p>
            <p> - Poging SOCSCI teacher din</p>
        </div>

        <div class="religion">
            <img src="images/ma'amerika.jpg" width="20%" height="20%" alt="">
            <h2> Erika Silverio </h2>
            <p> - Pinaka-batang religion teacher</p>
            <p> - The best magturo ng religion</p>
        </div>

        <div class="filipino">
            <img src="images/ma'amalpha.jpg" width="20%" height="20%" alt="">
            <h2> Alpha Mariz Binala </h2>
            <p> - Filipino teacher na kakaiba ang humor</p>
            <p> - Laging lt sa subject niya (minsan lang magalit)</p>
        </div>

        <div class="mapeh">
            <img src="images/ma'amsab.jpg" width="20%" height="20%" alt="">
            <h2> Sabrina Tanya Santos </h2>
            <p> - Open-minded na MAPEH teacher</p>
            <p> - The best magpalaro ng PE</p>
        </div>

        <div class="tle">
            <img src="images/ma'amregina.jpg" width="20%" height="20%" alt="">
            <h2> Regina Mhae Naval; </h2>
            <p> - Soft TLE teacher</p>
            <p> - Cute magalit (normal lang tone ng voice niya kahit galit)</p>
        </div>

    </div>

</section>

<!-- teachers sections ends  -->


<!-- diary section starts  -->

<section class="diary" id="diary">

    <h1 class="heading"> fun <span>memories</span> of st. lorenzo ruiz</h1>

    <div class="row">

        <div class="column">
            <img src="images/feastday.jpeg" alt="">
            <h2>feast day of st. lorenzo ruiz</h2>
            <p>this was our first picnic and bonding with sir eugie and it was fun. lahat kami ay may dala-dalang sariling foods na pinagsaluhan, we all shared each other's food (busog much). medyo magulo lang kasi kulang yun banig, pero masaya. hindi rin mawawala yun kalokohan ng boy, nagtago sila ng shoes and nilagay pa sa bubong yun iba. hay nako lorenzo. it went well though, lahat kami nabusog.</p>
        </div>

    </div>

</section>


<!-- diary section ends  -->





<!-- custom js file link  -->
<script src="js/script.js"></script>

</body>
</html>

This is the css code:

@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@100;300;400;500;700&display=swap');

:root{
    --main-color:#04246b;
    --black:#13131a;
    --bg:#add8e6;
    --border:.1rem solid rgba(0, 0, 0, 0.3);
}

*{
    font-family: 'Roboto', sans-serif;
    margin:0; padding:0;
    box-sizing: border-box;
    outline: none; border:none;
    text-decoration: none;
    text-transform: capitalize;
    transition: .2s linear;
}


html{
    font-size: 62.5%;
    overflow-x: hidden;
    scroll-padding-top: 9rem;
    scroll-behavior: smooth;
}

html::-webkit-scrollbar{
    width: .8rem;
}

html::-webkit-scrollbar-track{
    background: transparent;
}

html::-webkit-scrollbar-thumb{
    background: #fff;
    border-radius: 5rem;
}


body{
    background: var(--bg);
}


section{
    padding:2rem 7%;
}


.heading{
    text-align: center;
    color: #fff;
    text-transform: uppercase;
    padding-bottom: 3.5rem;
    font-size: 4rem;
}

.heading span{
    color: var(--main-color);
    text-transform: uppercase;
}


.header{
    background: var(--bg);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding:1.5rem 7%;
    border-bottom: var(--border);
    position: fixed;
    top: 0; left: 0; right: 0;
    z-index: 1000;
    height: 10rem;
}

.lsclogo img{
    height: 10rem;
    width: 10rem;
}

.header .navbar a{
    margin:0 1rem;
    font-size: 1.6rem;
    color: #162a2c;
}

.header .navbar a:hover{
    color:var(--main-color);
    border-bottom: .1rem solid var(--main-color);
    padding-bottom: .5rem;
}

.header .icons div{
    color: #162a2c;
    cursor: pointer;
    font-size: 2.5rem;
    margin-left: 2rem;
}

.header .icons div:hover{
    color: var(--main-color);
}

#menu-btn{
    display: none;
}

.header .search-form{
    position: absolute;
    top:30%; right: 1%;
    background: #fff;
    width: 35rem;
    height: 3.5rem;
    display: flex;
    align-items: center;
    transform: scaleY(1);
    transform-origin: top;
}

.header .search-form.active{
    transform: scaleY(1);
}

.header .search-form input{
    height: 100%;
    width: 100%;
    font-size: 1.6rem;
    color:var(--black);
    padding:1rem;
    text-transform: none;
}

.header .search-form label{
    cursor: pointer;
    font-size: 2.2rem;
    margin-right: 1.5rem;
    color:var(--black);
}

.header .search-form label:hover{
    color:var(--main-color);
}


.headstart{
    min-height: 100vh;
    display: flex;
    align-items: center;
    background:url(../images/headstart.jpeg);
    background-size: cover;
    background-position: center;
}

.headstart .content{
    max-width: 60rem;
}

.headstart .content h3{
    font-size: 6rem;
    text-transform: uppercase;
    color: #04246b;
}

.headstart .content p{
    font-size: 2rem;
    font-weight: normal;
    line-height: 1.8;
    padding:1rem 0; 
    color: #eee;
}


.background .row{
    display: flex;
    align-items: center;
    background:var(--main-color);
    flex-wrap: wrap;
}

.background .row .image{
   flex:1 1 61rem;
}

.background .row .image img{
    width: 100%;
}

.background .row .content{
    flex:1 1 45rem;
    padding:4.5rem;
    font-size: 1rem;
}

.background .row .content h3{
    font-size: 2rem;
    color: #fff;
}

.background .row .content p{
    font-size: 1.3rem;
    color: #ccc;
    padding:1 rem 0;
    line-height: 1.8;
}


.row .column{
    float: left;
    width:20%;
    padding:.1rem;
}

.row::after{
    content: "";
    display: table;
    clear: both;
}

.row .column h2{
    margin-left: 70px;
}

.row .column img:hover{
    background: #04246b;
}


.teachers .container{
    position: absolute;
    width: 90%;
    right: 4.5%;
    background-color: #04246b;
    padding: 110px;
}

.teachers .container .adviser img{
    float: left;
    width: 30;
    border: 10px solid #ddd;
    width: 150px;
}
.teachers .container .adviser h2{
    font-size: 2rem;
    color: #fff;
    margin-left: 17rem;
    }
    
.teachers .container .adviser p{
    font-size: 1.3rem;
    color: #ccc;
    padding:1 rem 0;
    line-height: 1.8;
    margin-left: 17rem;
}

.teachers .container .comp{
    margin-top: 12rem;
}

.teachers .container .comp img{
    float: right;
    width: 30;
    border: 10px solid #ddd;
    width: 150px;
}

.teachers .container .comp h2{
    font-size: 2rem;
    color: #fff;
    margin-left: 83rem;
    }
    
.teachers .container .comp p{
    font-size: 1.3rem;
    color: #ccc;
    padding:1 rem 0;
    line-height: 1.8;
    margin-left: 83rem;
}

.teachers .container .science{
    margin-top: 12rem;
}

.teachers .container .science img{
    float: left;
    width: 30;
    border: 10px solid #ddd;
    width: 150px;
}
.teachers .container .science h2{
    font-size: 2rem;
    color: #fff;
    margin-left: 17rem;
    }
    
.teachers .container .science p{
    font-size: 1.3rem;
    color: #ccc;
    padding:1 rem 0;
    line-height: 1.8;
    margin-left: 17rem;
}

.teachers .container .english{
    margin-top: 12rem;
}

.teachers .container .english img{
    float: right;
    width: 30;
    border: 10px solid #ddd;
    width: 150px;
}

.teachers .container .english h2{
    font-size: 2rem;
    color: #fff;
    margin-left: 83rem;
    }
    
.teachers .container .english p{
    font-size: 1.3rem;
    color: #ccc;
    padding:1 rem 0;
    line-height: 1.8;
    margin-left: 83rem;
}

.teachers .container .socsci{
    margin-top: 12rem;
}

.teachers .container .socsci img{
    float: left;
    width: 30;
    border: 10px solid #ddd;
    width: 150px;
}
.teachers .container .socsci h2{
    font-size: 2rem;
    color: #fff;
    margin-left: 17rem;
    }
    
.teachers .container .socsci p{
    font-size: 1.3rem;
    color: #ccc;
    padding:1 rem 0;
    line-height: 1.8;
    margin-left: 17rem;
}

.teachers .container .religion{
    margin-top: 12rem;
}

.teachers .container .religion img{
    float: right;
    width: 30;
    border: 10px solid #ddd;
    width: 150px;
}

.teachers .container .religion h2{
    font-size: 2rem;
    color: #fff;
    margin-left: 83rem;
    }
    
.teachers .container .religion p{
    font-size: 1.3rem;
    color: #ccc;
    padding:1 rem 0;
    line-height: 1.8;
    margin-left: 83rem;
}

.teachers .container .filipino{
    margin-top: 12rem;
}

.teachers .container .filipino img{
    float: left;
    width: 30;
    border: 10px solid #ddd;
    width: 150px;
}
.teachers .container .filipino h2{
    font-size: 2rem;
    color: #fff;
    margin-left: 17rem;
    }
    
.teachers .container .filipino p{
    font-size: 1.3rem;
    color: #ccc;
    padding:1 rem 0;
    line-height: 1.8;
    margin-left: 17rem;
}

.teachers .container .mapeh{
    margin-top: 12rem;
}

.teachers .container .mapeh img{
    float: right;
    width: 30;
    border: 10px solid #ddd;
    width: 150px;
}

.teachers .container .mapeh h2{
    font-size: 2rem;
    color: #fff;
    margin-left: 83rem;
}
.teachers .container .mapeh p{
    font-size: 1.3rem;
    color: #ccc;
    padding:1 rem 0;
    line-height: 1.8;
    margin-left: 83rem;
}

.teachers .container .tle{
    margin-top: 12rem;
}

.teachers .container .tle img{
    float: left;
    width: 30;
    border: 10px solid #ddd;
    width: 150px;
}
.teachers .container .tle h2{
    font-size: 2rem;
    color: #fff;
    margin-left: 17rem;
    }
    
.teachers .container .tle p{
    font-size: 1.3rem;
    color: #ccc;
    padding:1 rem 0;
    line-height: 1.8;
    margin-left: 17rem;
}




This is the javascript code:

let navbar = document.querySelector('.navbar');

document.querySelector('#menu-btn').oneclick = () =>{
    navbar.classList.toggle('active');
    navbar.classList.remove('active');
    searchForm.classList.remove('active');
}    

let searchForm = document.querySelector('.search-form');

document.querySelector('#search-btn').oneclick = () =>{
    searchForm.classList.toggle('active');
    navbar.classList.remove('active');
    searchForm.classList.remove('active');
}    

window.onscroll = () =>{
    navbar.classList.remove('active');
    searchForm.classList.remove('active');
}

I though the problem was the section tag. I tried rewriting the code in the diary section but it still doesn’t solve the problem.

Adding items to list app with the enter key has made other features not work properly

List app works great until I add a keydown for the enter key. I can only get it to work if it’s outside of the newItem() function. When I have the keydown function inside of newItem() function, the input field just clears and I don’t get any errors, but nothing submits.

My problem is when I put the keydown function outside of newItem() function, the crossOutButton(), strike css feature, and sortable() don’t work because they’re now outside of the scope. I’m guessing there is a solution to where it can all go inside the newItem() function, but I’m stuck.


  <form name="toDoList">
                <input type="text" name="listItem" id="input">
            </form>

            <div onclick="newItem()" id="button">Add</div>
            <br/>
            <ol id="list"></ol>

function newItem() {

//Adds new item to the list
let li = $('<li></li>');
let inputValue = $('#input').val();
li.append(inputValue);

if (inputValue === '') {
    alert('You must write something');
} else {
    $('#list').append(li);
    //clears input field after selecting 'Add' button
    $('#input').val(''); 
}

//Crossing out an item from the list of items
function crossOut() {
    li.toggleClass('strike');
}

li.on('dblclick', function crossOut() {
    li.toggleClass('strike');
});

//Adding the delete button 'X'
let crossOutButton = $('<crossOutButton></crossOutButton>');
crossOutButton.append(document.createTextNode('X'));
li.append(crossOutButton);

crossOutButton.on('click', deleteListItem);
//Adding class delete (display: none) from css
function deleteListItem() {
    li.addClass('delete');
}

//reordering the items
$('#list').sortable();

}

//keydown function to listen for enter key
    $(document).ready(function() {
        $('#input').keydown(function(e) {
    
        //initialized variable and set as undefined
        let inputValue;
     
        if (inputValue === '') {
                alert("You must enter something");
        } else {
                //Enter key holds the value of 13
                if (e.keyCode === 13) {
                let li = `<li>${$(this).val()}</li>`;
                $('#list').append(li);
                console.log('Form submitted');
    
                e.preventDefault(); 
                //clears input field after hitting enter
                $('#input').val('');
                }
        }
        })
    });

Why is my website running GET instead of POST

When Use Javascript to try to POST something using method: 'POST' it for some reason resorts to GET. It gives me the error Cannot GET /openai/generateimage but I don’t understand why it won’t try to POST it.

const response = await fetch('/openai/generateimage', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    prompt,
    size,
  }),
});

Is there a way for me to reuse a javascript function without copy/pasting it?

I’ve coded a javascript function and I need to use the exact same code at least 6 different times in one page. Copy/pasting the function every time and switching out the IDs is going to get repetitive and take up a lot of space so I wanted to know if there’s a way I can use the one function for every instance I need it instead. It’s been hard trying to find a solution because the function effects three different elements at once so if anyone maybe has an idea of how to simplify the code that would be amazing.

I know the code here is invalid but here’s an example of what I’m trying to do plus the jfiddle I’ve been working on because I’m not fighting with this website’s formatting. The first one works how it’s supposed to, I don’t know how to duplicate that code for the other two examples.

var div1 = document.getElementById("image1");
var div2 = document.getElementById("image2");
const button = document.getElementById("button");


function myFunction() {
  if (button.innerHTML == ("see original")) {
    div2.style.animation = "show 1s 1 forwards";
    div1.style.animation = "shuffle 1s 1 forwards";
    button.style.animation = "nobtn1 1.75s 1 linear";
    button.innerHTML = "see official";
    div1.style.zIndex = "0";
    div2.style.zIndex = "1";
  } else {
    div1.style.animation = "show 1s 1 forwards";
    div2.style.animation = "shuffle 1s 1 forwards";
    button.style.animation = "nobtn2 2s 1 linear";
    button.innerHTML = "see original";
    div2.style.zIndex = "0";
    div1.style.zIndex = "1";
  }
}
<div class="thumbnail">
  <div class="roster">

    <div class="colourbox"></div>
    <img id="image1" src="#">
    <img id="image2" src="#">
    <div id="button" onclick="myFunction()">see original</div>

  </div>
</div>
<div class="thumbnail">
  <div class="roster">

    <div class="colourbox"></div>
    <img id="image1" src="#">
    <img id="image2" src="#">
    <div id="button" onclick="myFunction()">see original</div>

  </div>
</div>
<div class="thumbnail">
  <div class="roster">

    <div class="colourbox"></div>
    <img id="image1" src="#">
    <img id="image2" src="#">
    <div id="button" onclick="myFunction()">see original</div>

  </div>
</div>

https://jsfiddle.net/consumed_by_m0ss/vxdf6puh/208/

It might also be important to note that I’ve also tried in multiple different ways to switch the IDs to classes as suggested in some other posts I’ve seen, but that always causes an error that makes the code either unable to define the animation property or read the innerHTML

Regex to split string along &

I have this string

PENNER,JANET E TR-50% & PENNER,MICHAEL G TR - 50% & SOURCE LLC & LARRY & FREDDY INC

and I want to split it up into groups like this

PENNER,JANET E TR

PENNER,MICHAEL G TR

SOURCE LLC

LARRY & FREDDY INC

I’m using javascript (node) with matchAll
and this is my attempt so far

/s*([^&]+) ((L.?L.?C.?)|(T.?R.?)|(I.?N.?C.?)|(C.?O.?)|(REV LIV))(?=-)?/g

The hard part is that some business names include ampersands (&) so how would I do this?

PWA. Recent updates to iOS/Android now strip any and all parameters and/or hash from URLs to prevent Cross Site Tracking

I’ve created a PWA Clock App for work and until recently I could have a single page dynamically load ANY employee clock profile by simply doing the following:

  1. Type their unique link in the browser: https://example.com/clock/?id=1001
  2. Click Share then click Add To Home Screen.
  3. Set a custom name for the icon if I want to.
  4. Click Add.

Done. Awesome web app ready to use.

Then one day… this stopped working on everyone’s phone. Meaning…

Forget this:

// https://example.com/clock/?id=1001
const parsedUrl = new URL(window.location.href);
const employeeId = parseInt(parsedUrl.searchParams.get("id")); // "1001"

And also, forget this:

// https://example.com/clock/#1001
// https://example.com/clock#1001
const employeeId = parseInt(window.location.hash.slice(1)); // "1001"

After hours of frustration I’ve decided to do the dumbest thing I could think of which is to create a physical directory for an employee using the same employee id just to say I’ve tried everything I could think of and what do you know… It worked.

Now I have to use this:

// https://example.com/clock/1001
const parsedUrl = new URL(window.location.href);
const pathParts = parsedUrl.pathname.split('/');
const employeeId = parseInt(pathParts[pathParts.length - 1]); // "1001"

Please “…say it ain’t so. This joke is a heart breaker.”

Change action (url_for) in javascript using variable

Trying to change action on clicking certain button.

On clicking certain button, I changed Submit button text (submit -> update).

Current action is like

<form method ='POST' action=''>
 // do something
</form>

On changing to update text, I want change this action to url_for using javascript instead ''.

And inside url_for I need to insert variable.

Tried code 1.

  • Give url string to action.
<script>
 var sel = 'space';
 var new_url = "{{ url_for('abc', selected='" + sel + "') }}"
</script>

Using console.log(new_url);
I get /abc/%20%29sel%29%20

What I need was /abc/space

The main problem is that jinja does not allow variables in script section. Looked up stack to solve this problem. But cant find a way to solve this problem..

Tried code 2.

  • Using $.post()
    This executed on everything. ex) onload window, on click submit button etc.

Could anyone help me with changing action in js using variables?

How to pass an array to node’s pg client for being used by an unnest() function?

I want to be able to change order position of a lists table. Each list has it’s own position field. As I update list order I want to save this to the database. So I pass an array with the lists id field in the correct order and use a middly complex query to update the list:

with pos as (
    select 
        id as pos_id,
        row_number() over() as position
    from (
        select unnest(
            array[36, 33, 35, 37, 46, 39, 40, 41, 43, 45, 38, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 58, 59, 60, 61, 62, 65, 66, 67, 68, 78, 79, 82, 83]
        ) as id 
    ) a 
)  
update lists l
    set position = pos.position
from 
    pos
where 
    l.id = pos.pos_id

This works perfectly in pg_admin but when I try to put this in Node it just won’t work.

I’ve tried to send $1 parameter using these forms:

  1. unnest($1)
  2. unnest($1::bigint[])
  3. unnest($1:list)
  4. unnest(ARRAY[$1])
  5. unnest(ARRAY[$1::bigint[])
  6. unnest(ARRAY[$1::list)
  7. unnest(ARRAY[$1::bigint[])
  8. unnest(ARRAY[‘ + positions.join(‘, ‘) + ‘])
  9. unnest(‘{‘ + positions.join(‘, ‘) + ‘}’)
  10. unnest(‘{‘ + positions.join(‘, ‘) + ‘}’::bigint[])

None worked. Some of them return a parse error, some a “need to add explicit type casts” error. How do I pass an array to pool.query in this case ?

javascript drag and drop not offsetting dragimage when using touch input

I am using html5 drag and drop functionality in a project. I am trying to alter the position of the drag image relative to the position of the input (mouse or finger). The following code works fine on a desktop when using a mouse, however when using a touch panel on a phone screen, the image is never offset.

I originally thought it might be a screen pixel-density issue, but even when I replace the offset with much bigger numbers, nothing happens.

    function dragStart(ev)
    {
        console.log("dragging");
        console.log(ev);

        // Place the drag image offset to the mouse cursor location
        ev.dataTransfer.setDragImage(ev.target, 50, 50);

        ev.dataTransfer.setData("text", ev.target.dataset.tileIndex);
    }

How do I fix my clicker game from reverting the code after pressing the “im feeling lucky” game

So every time I try to click the “im feeling lucky button, it works for a second, then it decides to go back to the original number but adds a click from the autoclicker part of the code. Here is the code (also ignore the cooldown that was just for testing to make sure it works):

gambling.js:

function initClickerGame() {
  // Obtain references to counter, button, and message elements
  const counterEl = document.getElementById('counter');
  const luckyBtn = document.getElementById('luckyBtn');
  const messageEl = document.getElementById('message');
  let isCooldown = false;

  luckyBtn.addEventListener('click', () => {
    if (isCooldown) {
      messageEl.textContent = 'Cooldown in effect. Please wait 30 seconds.';
      messageEl.style.display = 'block';
      return;
    }

    const gamble = Math.random();
    let points = parseInt(counterEl.textContent) || 0; // Retrieve current points and convert to integer

    if (points < 100) {
      messageEl.textContent = 'You need at least 100 points to gamble.';
    } else {
      if (gamble < 0.4) {
        const pointsWon = Math.floor(points / 2);
        points += pointsWon;
        counterEl.textContent = points;
        messageEl.textContent = `You won ${pointsWon} points!`;
      } else if (gamble >= 0.4 && gamble < 0.7) {
        const pointsLost = Math.floor(points / 3);
        if (pointsLost >= points) {
          points = 0;
          counterEl.textContent = points;
          messageEl.textContent = 'You lost all your points!';
        } else {
          points -= pointsLost;
          counterEl.textContent = points;
          messageEl.textContent = `You lost ${pointsLost} points!`;
        }
      } else if (gamble >= 0.7 && gamble < 0.9) {
        points *= 2;
        counterEl.textContent = points;
        messageEl.textContent = `Congratulations! Your points have been doubled!`;
      } else {
        points = 0;
        counterEl.textContent = points;
        messageEl.textContent = 'Bad luck! You lost all points!';
      }
    }

    messageEl.style.display = 'block';
    isCooldown = true;

    setTimeout(() => {
      isCooldown = false;
      messageEl.style.display = 'none';
    }, 3); // 30 seconds cooldown
  });
}

window.onload = initClickerGame;

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clicker Game</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <link rel="icon" type="image/x-icon" href="favicon.ico">
    <div class="container">
        <h1 id="counter" class="counter">0</h1>
        <br>
        <button class="clicker" id="clickerBtn">Click Me!</button><br><br>
        <button class="clicker" id="upgradeBtn">Buy Upgrader (Cost: 10)</button><br><br>
        <button class="clicker" id="luckyBtn">I'm Feeling Lucky</button><br><br>
        <button class="clicker" id="saveBtn" onclick="saveProgress()">Save Game</button><br><br>
        <button class="clicker" id="loadBtn" onclick="loadProgress()">Load Game</button><br><br>
        <button class="clicker" id="resetBtn" onclick="confirmReset()">Reset Game</button><br>
    </div>

    <div class="message" id="message"></div>

    <script src="anticheat.js"></script>
    <script src="gambling.js"></script>
    <script src="save.js"></script>

    <script>
        const counterEl = document.querySelector('.counter');
        let count = 0;
        let clickValue = 1;
        let upgradeCost = 10;
        let upgradeMultiplier = 2;
        let upgradeLevel = 1;
        let isCooldown = false;

        const clickerBtn = document.getElementById('clickerBtn');
        const upgradeBtn = document.getElementById('upgradeBtn');
        const luckyBtn = document.getElementById('luckyBtn');
        const messageEl = document.getElementById('message');

        clickerBtn.addEventListener('click', () => {
            count += clickValue;
            counterEl.textContent = count;
        });

        upgradeBtn.addEventListener('click', () => {
            if (count >= upgradeCost) {
                count -= upgradeCost;
                counterEl.textContent = count;
                clickValue *= upgradeMultiplier;
                upgradeLevel++;
                upgradeCost = upgradeCost * upgradeMultiplier;

                upgradeBtn.textContent = `Buy Upgrader (Cost: ${upgradeCost})`;

                if (upgradeLevel === 500) {
                    upgradeBtn.disabled = true;
                    upgradeBtn.textContent = `Upgrader Maxed!`;
                }
            } else {
                showMessage("Insufficient funds!");
            }
        });

        function updateCounter() {
            count += clickValue;
            counterEl.textContent = count;
        }

        function showMessage(text) {
            messageEl.textContent = text;
            messageEl.style.display = 'block';
            setTimeout(() => {
                messageEl.style.display = 'none';
            }, 5000);
        }

        function confirmReset() {
            const answer = prompt("WARNING: THIS WILL DELETE YOUR SAVE FILE AND START OVER!! To confirm the reset, what is the result of 100 + 5?");
            if (answer === "105") {
                resetGame();
            } else {
                showMessage("Incorrect answer. Reset not confirmed.");
            }
        }

        function resetGame() {
            count = 0;
            upgradeCost = 10;
            upgradeLevel = 1;
            clickValue = 1;

            counterEl.textContent = count;
            upgradeBtn.textContent = `Buy Upgrader (Cost: ${upgradeCost})`;

            showMessage("Game reset successfully!");
        }

        setInterval(updateCounter, 1000);
    </script>
</body>
</html>


I have tried rewriting the code with a new structure but it broke it more, so I just reverted the code.

The drawing start and end position are not correct

The starting and ending points of the drawing do not coincide with the mouse click.
The inclined plane is not doing any favors and the closest I’ve managed to get to success is in the code below.
The shared code snippet contains adjustments to offset calculations to take plane tilt into account. They may be adjusting the coordinates of the mouse click according to the position and rotation of the .floor element, thus ensuring that the start and end points of the drawing align correctly with the click position, but they are not perfect.

.container {
  height: 100%;
  perspective: 800px;
  display: flex;
  justify-content: center;
  align-items: flex-end;
}

.floor {
  top: 80%;
  width: 85%;
  height: 300px;
  background-color: #e0e0e0;
  position: relative; 
  bottom: 0;
  transform-style: preserve-3d;
  transform: rotateX(70deg) translateZ(0px);
  box-shadow: 0px 0px 30px rgba(0, 0, 0, 0.1);
}

.colored-point {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  position: absolute;
}

.grey-point {
  background-color: grey;
}

.blue-point {
  background-color: blue;
}

.yellow-point {
  background-color: yellow;
}

.green-point {
  background-color: green;
}
    const [closestGreyPoint, setClosestGreyPoint] = useState<{ x: number; y: number; distance: number } | null>(null);

    const canvasRef = React.useRef<HTMLCanvasElement>(null);
    const [isDrawing, setIsDrawing] = React.useState(false);

    const [greyPoints, setGreyPoints] = useState<{ x: number; y: number }[]>([]);
    const [greenPoints, setGreenPoints] = useState<{ x: number; y: number }[]>([]);


    const handleMouseMove: MouseEventHandler<HTMLCanvasElement> & TouchEventHandler<HTMLCanvasElement> = (event) => {
        if (!isDrawing) {
            return;
        }

        let offsetX;
        let offsetY;

        if ('touches' in event) {
            // É um evento de toque
            const touch = event.touches[0];
            const rect = event.currentTarget.getBoundingClientRect();
            offsetX = touch.clientX - rect.left;
            offsetY = touch.clientY - rect.top;
        } else {
            // É um evento de mouse
            const rect = event.currentTarget.getBoundingClientRect();
            offsetX = event.clientX - rect.left;
            offsetY = event.clientY - rect.top;
        }

        const canvas = canvasRef.current;
        if (canvas) {
            const ctx = canvas.getContext("2d");
            if (ctx) {
                ctx.beginPath();
                ctx.lineTo(offsetX, offsetY);
                ctx.strokeStyle = "black";
                ctx.lineWidth = 3;
                ctx.lineCap = "round";
                ctx.lineJoin = "round";
                ctx.stroke();
            }
        }
    };

    // Função auxiliar para adicionar pontos coloridos
    const addPoint = (parent: HTMLElement, color: string, x: number, y: number) => {
        const point = document.createElement('div');
        point.classList.add(`${color}-point`);
        point.classList.add('colored-point');
        point.style.left = `${x}px`;
        point.style.top = `${y}px`;
        parent.appendChild(point);
    };

    useEffect(() => {
        const floor = document.getElementById('floor');
        if (floor) {
            const pontos = document.getElementsByClassName('colored-point');
            while (pontos.length > 0) {
                const ponto = pontos[0];
                if (ponto.parentNode) {
                    ponto.parentNode.removeChild(ponto);
                }
            }

            const floorWidth = floor.offsetWidth;
            const floorHeight = floor.offsetHeight;

            addPoint(floor, 'blue', floorWidth * (0.1 + Math.random() * 0.1), floorHeight * (0.1 + Math.random() * 0.1));
            addPoint(floor, 'yellow', floorWidth * (0.9 - Math.random() * 0.1), floorHeight * (0.1 + Math.random() * 0.1));
            addPoint(floor, 'green', floorWidth * (0.1 + Math.random() * 0.1), floorHeight * (0.9 - Math.random() * 0.1));

            const centralX = floorWidth / 2;
            const centralY = floorHeight / 2;
            const separationFactor = 100;
            const greyPointsProv: { x: number; y: number }[] = [];

            for (let i = 0; i < 3; i++) {
                let randomX: number, randomY: number;
                do {
                    randomX = centralX + (Math.random() * separationFactor * 2 - separationFactor);
                    randomY = centralY + (Math.random() * separationFactor * 2 - separationFactor);
                } while (
                    (randomX < floorWidth * 0.2 && randomY < floorHeight * 0.2) ||
                    (randomX > floorWidth * 0.8 && randomY < floorHeight * 0.2) ||
                    (randomX < floorWidth * 0.2 && randomY > floorHeight * 0.8) ||
                    Math.sqrt((randomX - centralX) ** 2 + (randomY - centralY) ** 2) > separationFactor ||
                    greyPointsProv.some(point => Math.sqrt((randomX - point.x) ** 2 + (randomY - point.y) ** 2) < separationFactor)
                );

                addPoint(floor, 'grey', randomX, randomY);
                greyPointsProv.push({ x: randomX, y: randomY });
                setGreyPoints(greyPointsProv);
            }

            const greenPoint = document.querySelector('.green-point') as HTMLElement;
            if (greenPoint) {
                const greenX = parseFloat(greenPoint.style.left || '0');
                const greenY = parseFloat(greenPoint.style.top || '0');

                greyPointsProv.forEach(point => {
                    const distance = Math.sqrt((greenX - point.x) ** 2 + (greenY - point.y) ** 2);
                    if (!closestGreyPoint || distance < closestGreyPoint.distance) {
                        setClosestGreyPoint({ ...point, distance });
                    }
                });

                if (closestGreyPoint) {
                    const yellowPoint = document.querySelector('.yellow-point') as HTMLElement;
                    const bluePoint = document.querySelector('.blue-point') as HTMLElement;
                    const closestYellowDistance = yellowPoint ? Math.sqrt((closestGreyPoint.x - parseFloat(yellowPoint.style.left || '0')) ** 2 + (closestGreyPoint.y - parseFloat(yellowPoint.style.top || '0'))) : Infinity;
                    const closestBlueDistance = bluePoint ? Math.sqrt((closestGreyPoint.x - parseFloat(bluePoint.style.left || '0')) ** 2 + (closestGreyPoint.y - parseFloat(bluePoint.style.top || '0'))) : Infinity;

                    if (closestGreyPoint.distance > 1.5 * Math.min(closestYellowDistance, closestBlueDistance)) {
                        addPoint(floor, 'green', floorWidth * (0.9 - Math.random() * 0.1), floorHeight * (0.9 - Math.random() * 0.1));
                    }
                }
            }
        }

        const greyPointsProv: { x: number; y: number }[] = [];
        const greenPointsProv: { x: number; y: number }[] = [];

        const greyElements = document.querySelectorAll('.grey-point');
        greyElements.forEach(element => {
            const rect = element.getBoundingClientRect();
            greyPointsProv.push({ x: rect.left + window.scrollX, y: rect.top + window.scrollY });
            setGreyPoints(greyPointsProv);
        });

        const greenElements = document.querySelectorAll('.green-point');
        greenElements.forEach(element => {
            const rect = element.getBoundingClientRect();
            greenPointsProv.push({ x: rect.left + window.scrollX, y: rect.top + window.scrollY });
            setGreenPoints(greenPointsProv);
        });


    }, []);


    useEffect(() => {
        console.log(greyPoints)
        console.log(greenPoints)
        const floor = document.getElementById('floor');

        if (floor) {
            const canvas = canvasRef.current;
            if (canvas) {
                canvas.width = floor.offsetWidth;
                canvas.height = floor.offsetHeight;
            }
        }
    }, [greyPoints, greenPoints]);

        <div className="container">
            <div id="floor" className="floor"
            // onClick={handleFloorClick}
            >
                <canvas
                    onMouseDown={() => setIsDrawing(true)}
                    onMouseUp={() => setIsDrawing(false)}
                    onMouseMove={handleMouseMove}
                    onTouchStart={() => setIsDrawing(true)}
                    onTouchEnd={() => setIsDrawing(false)}
                    onTouchMove={handleMouseMove}
                    ref={canvasRef}
                ></canvas>
            </div>
        </div>