Chat NOT scrolling with the messagesr?

I created a GPT chat using the ‘Webview element in Tasker, through a chat.html file. My Tasker GPT projekt here.
The problem I have, is that the chat scroll is not scrolling with the messages. I have to manually scroll through messages that are now hidden at the bottom. What have I done wrong?. The link above gives access to the Tasker project and the Html file used.

</style>
    <script>
        if (!window["global"]) {
            window["global"] = () => {
                return `[
                    {
                        "role": "user",
                        "content": "hello there how are you"
                    },
                    {
                        "role": "assistant",
                        "content": "Hello! As an AI language model, I don't have emotions in the human sense, but I'm functioning well. How can I assist you today?"
                    }
                ]`;
            }
        }

        const sendChat = () => {
            const inputElement = document.querySelector("#chat_input");
            const chat = inputElement.value;
            console.log("Sending chat", chat);
            performTask("-----AI-----System >> Send Chat", 5, chat);
        }
        const clearChat = () => {
            const inputElement = document.querySelector("#chat_input");
            const conversationElement = document.querySelector("#conversation");
            inputElement.value = "";
            conversationElement.innerHTML = "";
            performTask("-----AI-----System >> Clear Chat", 5);
        }
        if (!window["setClip"]) {
            window["setClip"] = (text) => alert(`Setting clipboard to "${text}"`);
        }

        const getMessages = () => {
            var messagesText = global("%Messages");
            if (!messagesText) {
                messagesText = "[]";
            }
            const messagesObject = JSON.parse(messagesText);
            return messagesObject;
        }
        const setClipboardToMessageIndex = (index) => {
            const messages = getMessages();
            const messageToSetOnClipboard = messages[index];
            if(!messageToSetOnClipboard) return;

            setClip(messageToSetOnClipboard.content);
        }
        const updateMessages = () => {
            const messagesObject = getMessages();
            var html = "";
            var index = 0;
            messagesObject.forEach(message => {
                const isAssistant = message.role == "assistant";
                html += `
    <div class="container${isAssistant ? " darker" : ""}">
        <img src="${isAssistant ? "https://assets.website-files.com/5bd07377b823419565a29426/63ee56ec00064ef3dc4ff13d_ChatGPT_logo.png" : "https://cdn-icons-png.flaticon.com/512/6947/6947573.png"}" class="${isAssistant ? "" : "right"}" alt="Avatar" style="width:100%;">
        <p>${message.content}</p>
        ${isAssistant ? `<div class="copy_button" onclick="setClipboardToMessageIndex(${index})"><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSJ8McyNKbbcml1Joy3U7bBV7I0-7KA-QtpNkQ0PooCmWjd7awaKDKyxluDlrdzpkONN7E&usqp=CAU"></div>` : ""}
    </div>`;
                index++;
            });
            const conversationElement = document.querySelector("#conversation");
            conversationElement.innerHTML = html;
        }
        setInterval(updateMessages, 1000);  
    </script>

Unable to remove duplicates from dropdown list in ReactJS

I am trying to implement a Set on the dropdown list object and within the Set, I am using map function . I have tried two different ways by using Set but there has been no removal of the duplicates. Here, devices is the object and from there am trying to execute Set with map function.
devices is the object.

enter image description here

Here is the dropdown list which is showing repeated values. On the right hand-side , you can see the devices array being shown. The dropdown list should show 4-5 options of device_id. Please help.
enter image description here

React js If else not rendering

I am choosing items to my wishlist with id to localStorage. Everything works fine. When i click add to wishlist, it shows me delete from wishlist. But when i refresh page it not shows me remove from wishlist but i added. when i click to other button, then it shows me remove from wishlist.
I think im doing something wrong with my if, when i refresh page at the first time it not seeing if or idk. Can someone help me please?
here is my code

import React, { useEffect, useState } from 'react';
import { Button, Card } from 'react-bootstrap';
import { useThemeHook } from '../GlobalComponents/ThemeProvider';
import { useCart } from 'react-use-cart';
import { BsCartPlus } from 'react-icons/bs';
import { Link } from "@reach/router";
import { useInView } from 'react-intersection-observer';
import { MainContext, useContext } from '../context';
import { FcLike, FcDislike } from 'react-icons/fc'


const ProductCard = (props) => {
    // const [state,setState]=useState({
    //     favourites:[]       
    //    });
    const { favourites, setFavourites } = useContext(MainContext);
    
    


    let { image, price, title, id } = props.data;
    const [theme] = useThemeHook();
    const { addItem } = useCart();

    const { ref: headerAni, inView: headerAniVisible } = useInView();

    const addToCart = () => {
        addItem(props.data);
    };

    

    const handleFavourites = (likedItem) => {
        let oldData = JSON.parse(localStorage.getItem('liked') ?? "[]")
        if (oldData.some((item) => item.id === likedItem.id)) {
            oldData = oldData.filter((m) => m.id !== likedItem.id)
            console.log("if", oldData)
        } else {
            oldData.push(likedItem)
            console.log("else", oldData)
        }
        localStorage.setItem("liked", JSON.stringify(oldData));
        console.log(oldData);
        handleFavouritesState();
    };
    

    const handleFavouritesState = () => {
        let oldData = JSON.parse(localStorage.getItem("liked") ?? "[]")
        let temp = oldData.map((likedItem) => likedItem.id);
        setFavourites([...temp])
        console.log("son", oldData)
    };

    return (
        <>

            <Card
                style={{ width: '18rem', height: 'auto' }}
                className={`${theme ? 'bg-light-black text-light' : 'bg-lihgt text-black'} text-center p-0 overflow-hidden shadow mx-auto mb-4`}

                ref={headerAni}
            >
                <Link to={`/product-details/${id}`}>
                    <div style={{
                        background: 'white', height: '15rem', overflow: 'hidden', display: 'flex',
                        justifyContent: 'center', alignItems: 'center', marginBottom: 'inherit'
                    }}>
                        <div style={{ width: '9rem' }}>
                            <Card.Img variant="top" src={image} className="img-fluid" data-aos-easing="ease-out-cubic"
                                data-aos-duration="2000" data-aos={`${headerAniVisible ? "" : "zoom-out"}`} />
                        </div>
                    </div>
                </Link>
                <Card.Body>
                    <Card.Title style={{ textOverflow: 'ellipsis', overflow: 'hidden', whiteSpace: 'nowrap' }}>
                        {title}
                    </Card.Title>
                    <Card.Title>
                        $ <del><span className="">{price * 2}</span></del>
                    </Card.Title>
                    <Card.Title>
                        $ <span className="h3">{price}</span>
                    </Card.Title>
                    <Button
                        onClick={() => addToCart()}
                        className={`${theme ? 'bg-dark-primary text-black' : 'bg-light-primary'} d-flex m-auto border-0 align-items-center`}
                    >
                        <BsCartPlus size="1.8rem" />
                        Add to cart
                    </Button>
                    <Card.Title>
                        <span style={{ fontSize: '15px' }}>or</span>
                    </Card.Title>
                    
                    {favourites?.includes(id) ? <Button
                        onClick={() => handleFavourites(props.data)}
                        className={`${theme ? 'bg-dark-primary text-black' : 'bg-light-primary'} d-flex m-auto border-0 align-items-center`}
                    >
                        <FcDislike />
                        Delete from wishlist

                    </Button> : <Button
                        onClick={() => handleFavourites(props.data)}
                        className={`${theme ? 'bg-dark-primary text-black' : 'bg-light-primary'} d-flex m-auto border-0 align-items-center`}
                    >
                        <FcLike />
                        Add to wishlist

                    </Button>}

                </Card.Body>
            </Card>
        </>
    );
};

export default ProductCard;

How can I display either a login or logout button in navbar?

My Problem

I’m using Express/Passport to create a login system.

My problem is very simple but every time I try something I get undefined errors. I’m trying to figure out how I can pass my req.body.username to my navbar so that it:

  1. Displays the username
  2. Display either the logout or the register/login buttons, depending if the user is logged in or not.

I know that I will need to use an if statement inside my navbar ejs only like I said, every time I try something like:

  <%if (req.body.username) { %>
  <!--Logout-->
  <li><a href="/users/logout">Logout</a></li>
  <% }else{ %>
  <!--Sign In/Register-->
  <li><a href="/users/register">Register</a></li>
  <li><a href="/users/login">Login</a></li>
  <%}%>

… I get undefined errors.

Please help me understand what I’m doing wrong and how I can fix my code.

My Code

app.js

// setup session
app.use(
  session({
    secret: process.env.SECRET,
    resave: false,
    saveUninitialized: false,
  })
);

// initialize passport
app.use(passport.initialize());

// use passport to deal with session
app.use(passport.session());

app.use(function (req, res, next) {
  res.locals.isAuthenticated = req.isAuthenticated();
  next();
});

userController.js

exports.register = function (req, res, next) {
  if (req.isAuthenticated()) {
    res.redirect("/");
  } else {
    res.render("register");
  }
};

exports.login = function (req, res, next) {
  if (req.isAuthenticated()) {
    res.redirect("/");
  } else {
    res.render("login");
  }
};

exports.register_account = async (req, res) => {
  try {
    const registerUser = await User.register(
      { username: req.body.username },
      req.body.password
    );
    if (registerUser) {
      passport.authenticate("local")(req, res, function () {
        res.redirect("/");
      });
    } else {
      res.redirect("/register");
    }
  } catch (err) {
    res.send(err);
  }
};

exports.login_account = (req, res) => {
  // Create new user object
  const user = new User({
    username: req.body.username,
    password: req.body.password,
  });

  // Check if credentials are correct
  req.login(user, (err) => {
    if (err) {
      console.log(err);
    } else {
      passport.authenticate("local")(req, res, function () {
        res.redirect("/");
      });
    }
  });
};

exports.logout = function (req, res, next) {
  req.logout(function (err) {
    if (err) {
      return next(err);
    }
    res.redirect("/");
  });
};

users.js

/// USER ROUTE ///
router.get("/register", user_controller.register);

router.get("/login", user_controller.login);

// register user in DB
router.post("/register", user_controller.register_account);

// login user
router.post("/login", user_controller.login_account);

// Logout user
router.get("/logout", user_controller.logout);

module.exports = router;

navbar.js

<ul class="navbar">
  <p>USER PANEL</p>

  <!--Logout-->
  <li><a href="/users/logout">Logout</a></li>
  <!--Sign In/Register-->

  <li><a href="/users/login">Login</a></li>
  <li><a href="/users/register">Register</a></li>
</ul>

vue/nuxt how to detect multiple page views when navigating to/back to a page?

will try to explain my use case first. Typically when you use google analytics, they will trigger some pageview event that will be fired everytime the user navigates into the page, as by this definition here

A pageview is defined as a view of a page on your site that is being tracked by the Analytics tracking code. If a user clicks reload after reaching the page, this is counted as an additional pageview. If a user navigates to a different page and then returns to the original page, a second pageview is recorded as well.

I’m trying to manually recreate the second pageview recorded – meaning user navigates to a different page and then returns to the original page, I’m trying to look for a vue/nuxt event that can help me to capture this event. (and also for multiple, meaning pageA -> pageB -> pageA -> pageB -> pageA, page A has 3 pageviews, pageB has 2 pageviews)

mounted– is only called once on page load, so this can’t be used

updated– is called everytime dom changes, so this also can’t be used

watch: $route – seems to be a possible use case, but this event is fired on every route which means I need to always check if the current route matches the original page route where the watcher is (on every navigation) which seems to be really unnecessary work.

Is there any events or lifecycle hooks that I can use for this use case? So i can capture multiple repeated pageviews when a user navigates to and fro pages repeatedly?

Chrome – Extension v3 code: No matching signature

In my Chrome v3 extention app I have changed chrome.tabs.executeScript to chrome.scripting.executeScript. Getting “No matching signature”, Tried to fix it but I was unable.

Please help me here to solve the error..!

Manifest:

{
  "name": "OkBot",
  "description": "OkBot is used as a Personal Asistant.",
  "version": "1.1",
  "manifest_version": 3,
  "content_security_policy": {
    "extension_pages": "script-src 'self'; object-src 'self'"
  },
  "minimum_chrome_version": "88",
  "offline_enabled": false,
  "icons": {
    "48": "web/images/icon_48.png",
    "128": "web/images/icon_128.png"
  },
  "action": {
    "default_icon": {
      "19": "web/images/icon_19.png",
      "38": "web/images/icon_38.png"
    },
    "default_title": "OkBot",
    "default_popup": "popup.html"
  },
  "permissions": [
    "idle",
    "power",
    "management",
    "storage",
    "tabs",
    "activeTab",
    "topSites",
    "scripting"
  ],
  "host_permissions": [
    "*://*/*",
    "<all_urls>"
  ],
  "optional_permissions":[
  ],
  "options_page": "options.html",
  "background":{
    "service_worker":"web/js/background.js"
  },
  "content_scripts": [
    {
      "js": ["web/js/content_script.js"],
      "matches": ["<all_urls>", "*://*/*"]
    }
  ]
}

OkBot.js Script:

chrome.scripting.executeScript(tabs[0].id, {file: "web/js/storage.js"}, function() {
    if(chrome.runtime.lastError) 
        chrome.scripting.executeScript(tabs[0].id, {file: "web/js/content.js"}, function() {
            if(chrome.runtime.lastError) {
                console.error(chrome.runtime.lastError.message);
            }
            else
            {
                setTimeout(function(){ 
                    send_to_content(obj); // Then call send_to_content(obj) again after content.js injected
            }, 300);
        }
    });
});

Error handling response: TypeError: Error in invocation of scripting.executeScript(scripting.ScriptInjection injection, optional function callback): No matching signature.

in my code the stats JS page only renders for a second then it goes back to the app.js page

This is my app.js page using Router Browser and i want to switch to stats.js on pressing button 1. The stats.js page renders on pressing the button but only for less then a second and then the app.js page is rendered back

Below is the app.js code

import React from "react";
    import bgvideo from "./assets/testfootage.mp4";
    import "./background-video.css";
    import "./main-buttons.css";
    import logo from "./assets/logo.png";
    import "./logo.css";
    import Stats from "./stats";
    import {
      BrowserRouter as Router,
      Routes,
      Route,
      Link,
      useNavigate,
      Switch,
    } from "react-router-dom";

    function App() {
      const navigate = useNavigate();

      return (
        <div className="background-video">
          <video autoPlay muted loop>
            <source src={bgvideo} type="video/mp4" />
            console.log("okok");
          </video>
          <div className="logo">
            <img src={logo} alt="Logo" />
          </div>
          <div className="button-container1">
            <button onClick={() => navigate("/stats")}>
              See your Listening Stats
            </button>
          </div>
          <div className="button-container2">
            <button>Generate a Playlist</button>
          </div>
          <div className="button-container3">
            <button>Realtime Friends Playlist</button>
          </div>
          <Routes>
            <Route path="/stats" element={<Stats />} />
          </Routes>
        </div>
      );
    }


    export default App;

And this is the index.js page
I think the problem might be here

 import React from "react";
    import ReactDOM from "react-dom";
    import App from "./App";
    import { BrowserRouter } from "react-router-dom";

    ReactDOM.render(
      <BrowserRouter>
        <App />
      </BrowserRouter>,
      document.getElementById("root")
    );

how collect the AD data

How do I collect the AD data I receive when I browse the edge Web page,especially the literal text.

I tried to modify the existing adblocking plugin but I don’t know if it is feasible.
Hope to provide a feasible idea.Thank you!!!

Creating an email simulation in javascript using OOP

I am busy creating a program which is an email Simulation. I am struggling to be able to make a function where it takes the contents and address of the email to make a new email object and push this into the inbox function. I am also struggling with a function that will mark the emails as read individually.

// An Email Simulation

class Email{
constructor(hasBeenRead, emailContents, isSpam, fromAddress){
    this.hasBeenRead = hasBeenRead;
    this.emailContents = emailContents;
    this.isSpam = isSpam;
    this.fromAddress = fromAddress;
}

getHasBeenRead(){
    return this.hasBeenRead;
}

getEmailContents(){
    return this.emailContents;
}

getIsSpam(){
    return this.isSpam;
}

getFromAddress(){
    return this.fromAddress;
}

markAsRead(){
    this.hasBeenRead = true;
}

markAsSpam(){
    this.isSpam = true;
}
}

const email1 = new Email(false, "Good day sir, I was unaware that i was late in submitting one of my tasks. Please forgive me", false, "[email protected]")
const email2 = new Email(false, "Hello bud, How are you today", false, "[email protected]")
const email3 = new Email(false, "I am sorry for the late reply but thank you very much for the flowers", false, "[email protected]")
const email4 = new Email(false, "I have your package and I am on my way to deliver", false, "[email protected]")
const emailRecieved = new Email(false, "This is the recieved email needed to make a new object",   false, "[email protected]")


let inbox = [email1, email2, email3, email4];
console.log(inbox)

function addEmail(arr, val1){
const newEmail = new Email(false, val1.getEmailContents(), false, val1.getFromAddress())
arr.push(newEmail);
}
console.log(addEmail(inbox, emailRecieved))

userChoice = "";
while(userChoice != "7"){
userChoice = prompt("What would you like to do:n 1. Read emailn 2. Mark spamn3. Send   emailn4. Delete emailn5. View spam emailsn6. View unread emailsn7. quit?");
if(userChoice == "1"){
    
    console.log(email1.getHasBeenRead())
    console.log(email2.getHasBeenRead())
    console.log(email3.getHasBeenRead())
    console.log(email4.getHasBeenRead())
}else if(userChoice == "2"){
    
    console.log
}else if(userChoice == "3"){
    
}else if(userChoice == "4"){
    
}else if(userChoice == "5"){
    
}else if(userChoice == "6"){
    
    console.log(email1.getEmailContents())
    console.log(email2.getEmailContents())
    console.log(email3.getEmailContents())
    console.log(email4.getEmailContents())
}else if(userChoice == "7"){
    console.log("Goodbye");
}else{
    console.log("Oops - incorrect input");
    
}
}

How to get this text layout algorithm to properly scale the text to “font size” option (text made with SVG paths)?

I have this Codepen demo in TypeScript/React showing the layout of Hebrew text according to the “stretched” text design, as described here. It looks like this in a few different font sizes:

32

It looks the best at this “scale” (you can edit the 16 on line #1092 at the bottom of the file, which says setSefer(render(words, 16))).

16

It breaks down at this scale, it’s not laid out correctly in several aspects.

enter image description here

Here is a demo showing the bounding box on one of the SVGs (SVG is generated per line in theory, but notice they don’t go on one line here).

enter image description here

Problem

The problem is to layout the text so the 4 main letters defined here grow to make it so the text is fully “justified” on the sides:

const scalePriority: Record<string, number> = {
  ד: 1,
  ה: 3,
  ר: 2,
  ת: 4,
}

The Codepen is 20% JSON data for the text, 30% glyph data in templated SVG paths, 40% logic for doing the layout of the text at the level of SVG React nodes, and 10% the React rendering.

The 40% logic I have been fiddling with all night, and wondering if you can spot where I am going wrong. I don’t think we need to care about the formatLine function, that is where the offset adjustments are made to grow the letters. There is some slight spacing issue on the letters themselves, I think that has to do with the SVG path code, so not relevant for this question. But that leads me to the main question.

Question

How do I get this to layout at different “font sizes” properly? (Font size is that 16 setting you can change). Why can’t I just say <svg width="100%" height={fontSize}> on each line of the SVG, and it would just take up the full parent width? That way if the screen was 800px, and font size 16, it would be long rows of small text, and at 48px, it would be 800px wide “narrow” rows (since the font is so much bigger), and many more lines. I can’t figure out why the SVG is not behaving like I’d expect.

P.S. I “ported” this text layout code to TypeScript from JS code I had from many years ago, and I’m not sure if I originally wrote it or someone else wrote it. I can’t seem to find anywhere on the web for a reference of it, so I’m not sure haha.

React-Vite doesn’t show react-side-bar and displays a white blank screen

I have been trying tho develop an app using electron react and vite. I used react sidebar for the side bar navigation. However, the sidebar doesn’t get displayed even after installing the latest package [email protected]

The page goes blank when i add <Sidebar isSidebar={isSidebar} /> but works for TopBar

My App.jsx file —

import { useState } from "react";
import { Routes, Route } from "react-router-dom";
import Topbar from "./scenes/global/Topbar";
import Sidebar from "./scenes/global/Sidebar";

function App() {
  const [theme, colorMode] = useMode();
  const [isSidebar, setIsSidebar] = useState(true);

  return (
    <ColorModeContext.Provider value={colorMode}>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <div className="app">
          <Sidebar isSidebar={isSidebar} />
          <main className="content">
            <Topbar setIsSidebar={setIsSidebar} />
          </main>
        </div>
      </ThemeProvider>
    </ColorModeContext.Provider>
  );
}

export default App;

My Sidebar.jsx code –

import { useState } from "react";
import { ProSidebar, Menu, MenuItem } from "react-pro-sidebar";
import "react-pro-sidebar/dist/css/styles.css";
import { Box, IconButton, Typography, useTheme } from "@mui/material";
import { Link } from "react-router-dom";
import { tokens } from "../../theme";

// A seperate component for the menu items
const Item = ({ title, to, icon, selected, setSelected }) => {
  const theme = useTheme();
  const colors = tokens(theme.palette.mode);

  return <MenuItem>{/* code */}</MenuItem>;
};

const Sidebar = () => {
  const theme = useTheme();
  const colors = tokens(theme.palette.mode);

  return <>// code ---</>;
};

export default Sidebar;

I feel import "react-pro-sidebar/dist/css/styles.css"; is the problem but im not sure how to rectify it. Also, please note i have installed the latest package [email protected] but it doesnt solve the problem.

How to insert text at current cursor position in Summernote editor in Angular 12

Description:

I have a Summernote editor (https://www.npmjs.com/package/ngx-summernote) in my Angular 12 project, and I also have a button outside the editor. When the user clicks on this button, I want to insert the text “Heeello” at the current cursor position in the editor.

I’ve tried accessing the editor object through the ngx-summernote directive, but I keep getting errors like “Cannot read properties of undefined”. I’ve also looked at the Summernote API documentation, but I’m not sure how to use it in my Angular project.

<div [ngxSummernote]="config"></div>

Component.ts

import { NgxSummernoteDirective } from 'ngx-summernote';

@ViewChild(NgxSummernoteDirective)  ngxSummernote: NgxSummernoteDirective;

 config = {
    placeholder: '',
    tabsize: 2,
    height: '200px',
    uploadImagePath: '/api/upload',
    toolbar: [
        ['misc', ['codeview', 'undo', 'redo']],
        ['style', ['bold', 'italic', 'underline', 'clear']],
        ['font', ['bold', 'italic', 'underline', 'strikethrough', 'superscript', 'subscript', 'clear']],
        ['fontsize', ['fontname', 'fontsize', 'color']],
        ['para', ['style', 'ul', 'ol', 'paragraph', 'height']],
        ['insert', ['table', 'picture', 'link', 'video', 'hr']]
    ],
    fontNames: ['Helvetica', 'Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', 'Roboto', 'Times']
  }
  ...
}

addText(){
  console.log(this.ngxSummernote);
    console.log(this.ngxSummernote['_editor'][0] )

    this.ngxSummernote['_editor'].insertText('as');
    const currentPosition = this.ngxSummernote['_editor'].sumo.getSelection().index;
    console.log(currentPosition)
    // const currentCursorPosition = ($(this.mySummernote.nativeElement) as any).summernote('code').length;

    // const textToInsert = 'Hello';
}

None of the above is working. Here’s the StackBlitz link to my code: https://stackblitz.com/edit/angular-summernote-demo-duemtn?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts

Can someone help me figure out how to insert text at the current cursor position in the Summernote editor in Angular 12?

Fetch Discord IDs

How do i fetch the ids of peoples who are in a server be be specific, I have a list of IDs and i want to check if any of the users are in a given server if they are then i want to fetch all the ids which are in the list
Example

91287318123, 1282379128, 128923712912, 282139823197, 1282621921, 21832187312, 21832713412
above is the list of IDs

and among those
91287318123, 128923712912 are the one who are in a server with id 1827392683

so i want to return those ids as pings making it <@id>, <@id> and so on

I don exactly know what to do, minimum i know that its a loop

Call class method within try catch block?

I have encountered with something like this:

class Example {
  // ...

  async #privateMethod() {
    return true
  }

  static staticMethod() {
    try {
       // can't access #privateMethod
      this.#privateMethod()
    } catch (error) {
      console.log('error', error);
    }
  }
}

I want to call a private method within the static method, but I can’t access the private method for some reason. What am I doing wrong, please?

This page isn’t working…If the problem continues, contact the site owner. HTTP ERROR 405

I am making this simple login form using html css and js. And I am receiving this error when i click the login button: This page isn’t working…If the problem continues, contact the site owner. HTTP ERROR 405.
Below are the codes:

JAVASCRIPT:

function validate(){
  var username = document.getElementById(username).value
  var password = document.getElementById(password).value
  if(username == "judge1" && password=="1234") {
    alert("Login Successful");
    return false;
  }
  else{
    alert("Login Failed");
  }
}

HTML:

<form class="inputs" action="/" method="POST">
        <input type="text" class="username" placeholder="Username" id="username"> <br/>
        <input type="password" class="password" placeholder="Password" id="password"> <br/>
        <input type="submit" value="Login" onclick="validate()">
    </form>

I tried googling it but I’m having a hard time in finding the solution. I am still new in this so please help.