How to find if two given dates are in same month using Javascript? [closed]

I would like to check if two given dates are in same month and year. The code should also be able to check if a date is valid or not. It should not permit 30th February, 31st April and so on. It should be able to check if the dates are valid and return if the dates fall under same month of the year using JAVASCRIPT.

I tried matching the month and year alone. It works if the dates are in same month but doesn’t check if a date is valid. For example, 01012023 and 31012023 works. But 01022023 and 30022023 fails.

How do I convert a string to React elements that can be rendered?

I have strings stored in a DB that are partial HTML, for example:

“Intro<br /><br />Paragraph 1<br /><br />Paragraph 2”

Say I want to render this string within a new <p> element, what is a simple way to accomplish this?

I am looking for a solution that doesn’t use an additional package and instead uses native JavaScript or a non-deprecated React function.

I am serving these string snippets to the React client, and I want React to eventually convert them from strings to HTML elements. However, doing so using document.createElement and manipulating the innerHTML of this new element gives me an error saying that Objects cannot be rendered in React. Say this new element is called elem, I am trying to render is like so:
render(<div>{elem}</div>)

How can I sum contents of array in Javascript? [closed]

I have an array called newresult which prints to the console like this:

const newresult = [
  1, 0, 3, 0, 0, 0, 1, 2,
  0, 0, 0, 1, 3, 0, 0, 0,
  0, 0, 0, 2, 0, 0, 0, 3,
  0, 0, 2
];

const sum = [newresult].reduce((partialSum, a) => partialSum + a, 0);
console.log(sum);

The array contents just printing as individual numbers.

Apologies, as I’m sure this is obvious, but what schoolboy error am I making here?

Also tried this:

const array1 = [newresult];
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue,
);

Same result:

01,0,3,0,0,0,1,2,0,0,0,1,3,0,0,0,0,0,0,2,0,0,0,3,0,0,2

Thank you

Trouble with ‘keydown’ Event in Chrome Extension: Capturing Backspace Action

I am creating a Chrome extension (code here) and am having trouble with the “keydown” event. I want to use it to capture a ‘backspace’ before it happens, in order to switch the text the user is typing before it is deleted. However, with the current way I am doing things, which involves creating a function keyDown(event){...} and adding document.addEventListener("keydown", keyDown), when the function is called, the event.srcElement.innerText contains the text after the deletion takes place. To clarify, if an editable element contains ‘abcd’ and I press backspace, I will get the text ‘abc’ from the event handler, rather than ‘abcd’.

P.S. If you view my code and notice any other issues with it, please do let me know. I am not a seasoned developer and would appreciate any input.

How to change offset of horizontal bars in react-chartjs-2

I have used following graph config to render graph:

{
    type: 'horizontalBar',
    indexAxis: 'y',
    barThickness: 12,
    scales: {
      x: {
        suggestedMax: 6,
        suggestedMin: 0,
        grid: {
          display: false,
          drawBorder: false,
        },
        ticks: {
          stepSize: 2,
          callback: function (value, index, ticks) {
            return value ? value + 'h' : value;
          },
        }
      },
      y: {
        type: 'category',
        grid: {
          drawBorder: false,
          borderDash: [4, 3],
          color: "#C2C8CD",
          drawTicks: false,
          offset: false,
        },
        ticks: {
        }
      }
    }

What I’m getting using above configuration.
I'm getting this graph

what I want:

what I want

Kindly help to render this graph using react-chartjs-2.

Post by Author does not show [closed]

I’ve encountered a problem: posts by the author aren’t showing up for me. I recently bought a course on JavaScript and have been studying it, but I’m stuck on lesson 82 and can’t move forward.

What could be the issue in the code? I’ve done everything as the author does, but still, the posts aren’t showing up for me.

Here is the code from profile.ejs

<%- include('includes/header') %>

<div class="container py-md-5 container--narrow">
  <h2><img class="avatar-small" src="<%= profileAvatar %>"> <%= profileUsername %> 
    <form class="ml-2 d-inline" action="#" method="POST">
      <button class="btn btn-primary btn-sm">Follow <i class="fas fa-user-plus"></i></button>
      <!-- <button class="btn btn-danger btn-sm">Stop Following <i class="fas fa-user-times"></i></button> -->
    </form>
  </h2>

  <div class="profile-nav nav nav-tabs pt-2 mb-4">
    <a href="#" class="profile-nav-link nav-item nav-link active">Posts: 3</a>
    <a href="#" class="profile-nav-link nav-item nav-link ">Followers: 3</a>
    <a href="#" class="profile-nav-link nav-item nav-link ">Following: 2</a>
  </div>

  <div class="list-group">
    <% posts.forEach(function(post) { %>
      <a href="/post/<%= post._id %>" class="list-group-item list-group-item-action">
        <img class="avatar-tiny" src="<%= post.author.avatar %>">
        <strong><%= post.title %></strong> on <%= post.createdDate.getMonth() + 1 %>/<%= post.createdDate.getDate() %>/<%= post.createdDate.getFullYear() %>
      </a>
    <% }) %>
  </div>
</div>

<%- include('includes/footer') %>

And this is model/Post.js

const postsCollection = require('../db').db().collection("posts")
const ObjectId = require('mongodb').ObjectId
const User = require('./User')

let Post = function(data, userid) {
  this.data = data
  this.errors = []
  this.userid = userid
}

Post.prototype.cleanUp = function() {
  if (typeof(this.data.title) != "string") {this.data.title = ""}
  if (typeof(this.data.body) != "string") {this.data.body = ""}

  // get rid of any bogus properties
  this.data = {
    title: this.data.title.trim(),
    body: this.data.body.trim(),
    createdDate: new Date(),
    author: ObjectId(this.userid)
  }
}

Post.prototype.validate = function() {
  if (this.data.title == "") {this.errors.push("You must provide a title.")}
  if (this.data.body == "") {this.errors.push("You must provide post content.")}
}

Post.prototype.create = function() {
  return new Promise((resolve, reject) => {
    this.cleanUp()
    this.validate()
    if (!this.errors.length) {
      // save post into database
      postsCollection.insertOne(this.data).then(() => {
        resolve()
      }).catch(() => {
        this.errors.push("Please try again later.")
        reject(this.errors)
      })
    } else {
      reject(this.errors)
    }
  })
}

Post.reusablePostQuery = function(uniqueOperations) {
  return new Promise(async function(resolve, reject) {
    let aggOperations = uniqueOperations.concat([
      {$lookup: {from: "users", localField: "author", foreignField: "_id", as: "authorDocument"}},
      {$project: {
        title: 1,
        body: 1,
        createdDate: 1,
        author: {$arrayElemAt: ["$authorDocument", 0]}
      }}
    ])

    let posts = await postsCollection.aggregate(aggOperations).toArray()

    // clean up author property in each post object
    posts = posts.map(function(post) {
      post.author = {
        username: post.author.username,
        avatar: new User(post.author, true).avatar
      }

      return post
    })

    resolve(posts)
  })
}

Post.findSingleById = function(id) {
  return new Promise(async function(resolve, reject) {
    if (typeof(id) != "string" || !ObjectId.isValid(id)) {
      reject()
      return
    }
    
    let posts = await Post.reusablePostQuery([
      {$match: {_id: ObjectId(id)}}
    ])

    if (posts.length) {
      console.log(posts[0])
      resolve(posts[0])
    } else {
      reject()
    }
  })
}

Post.findByAuthorId = function(authorId) {
  return Post.reusablePostQuery([
    {$match: {author: authorId}},
    {$sort: {createdDate: -1}}
  ])
}

module.exports = Post

And this is controller/userController.js

const User = require('../models/User')
const Post = require('../models/Post')

exports.mustBeLoggedIn = function(req, res, next) {
  if (req.session.user) {
    next()
  } else {
    req.flash("errors", "You must be logged in to perform that action.")
    req.session.save(function() {
      res.redirect('/')
    })
  }
}

exports.login = function(req, res) {
  let user = new User(req.body)
  user.login().then(function(result) {
    req.session.user = {avatar: user.avatar, username: user.data.username, _id: user.data._id}
    req.session.save(function() {
      res.redirect('/')
    })
  }).catch(function(e) {
    req.flash('errors', e)
    req.session.save(function() {
      res.redirect('/')
    })
  })
}

exports.logout = function(req, res) {
  req.session.destroy(function() {
    res.redirect('/')
  })
}

exports.register = function(req, res) {
  let user = new User(req.body)
  user.register().then(() => {
    req.session.user = {username: user.data.username, avatar: user.avatar, _id: user.data._id}
    req.session.save(function() {
      res.redirect('/')
    })
  }).catch((regErrors) => {
    regErrors.forEach(function(error) {
      req.flash('regErrors', error)
    })
    req.session.save(function() {
      res.redirect('/')
    })
  })
}

exports.home = function(req, res) {
  if (req.session.user) {
    res.render('home-dashboard')
  } else {
    res.render('home-guest', {errors: req.flash('errors'), regErrors: req.flash('regErrors')})
  }
}

exports.ifUserExists = function(req, res, next) {
  User.findByUsername(req.params.username).then(function(userDocument) {
    req.profileUser = userDocument
    next()
  }).catch(function() {
    res.render("404")
  })
}

exports.profilePostsScreen = function(req, res) {
  // ask our post model for posts by a certain author id
  Post.findByAuthorId(req.profileUser._id).then(function(posts) {
    res.render('profile', {
      posts: posts,
      profileUsername: req.profileUser.username,
      profileAvatar: req.profileUser.avatar
    })
  }).catch(function() {
    res.render("404")
  })

}

And this is router.js

const express = require ('express')
const router = express.Router()
const userController = require ('./controllers/userController')
const postController = require ('./controllers/postController')

// user related routes
router.get('/', userController.home)
router.post('/register',userController.register)
router.post('/login', userController.login)
router.post('/logout', userController.logout)

// profile related routes
router.get('/profile/:username', userController.ifUserExists, userController.profilePostsScreen)

// post related routes
router.get('/create-post', userController.mustBeLoggedIn, postController.viewCreateScreen)
router.post('/create-post', userController.mustBeLoggedIn, postController.create)
router.get('/post/:id', postController.viewSingle)

module.exports = router

I hope someone can help me with this.

I did the same thing like author did, I copied the whole code from the original source and past it but still the same problem

Converting array to filelist makes file-size 0

I have an array that looks like:

Array [ "state/file1.xlsx", "state/file2.xlsx" ]

I am trying to convert this array to filelist with below method:

function createFileList(files) {
        var fileListTextarea = document.getElementById('uploaded_files');
        var files = fileListTextarea.value.trim().split('n');
        var dataTransfer = new DataTransfer();
        files.forEach(function (fileKey) {
            var fileName = fileKey.split('/').pop(); 
            var file = new File([], fileName);
            dataTransfer.items.add(file);
        });
        return dataTransfer.files;
    }

This conversion makes the filesize to 0.

FileList [ File, File ]
0: File { name: "file1.xlsx", lastModified: 1710863577685, size: 0, … }
1: File { name: "file2.xlsx", lastModified: 1710863577685, size: 0, … }

how to convert an array to file list without losing the filesize? the file object is not getting created correctly. any help?

JavaScript – Event listener for navigating through options

I have a <select> element with multiple options. Currently added event listener change for calling function. But it triggers only when the value is changed. I want to trigger ir while scrolling through the options as well. So I can see what each option does in real-time without actually selecting it. Tried setting event listener as input as well, but didn’t work.

Note: There are more than 1000 options inside select

<select id="dropdown">
  <option value="A">A</option>
  <option value="B">B</option>
  <option value="C">C</option>
  <option value="D">D</option>
  <option value="E">E</option>
</select>
const dropdownSelect = document.querySelector("#dropdown");

function updateChanges() {
  console.log("Value changed");
};

dropdownSelect.addEventListener("change", updateChanges);

jqui-resizable boxes that fill space like the cards from Bootstrap masonry package

I’m trying to make a R shiny dashboard where a user can add and remove resizable boxes with a click of a button. Here is my code so far:


library(shinydashboard) 
library(shiny)
library(shinyjqui)

ui <- dashboardPage(
  dashboardHeader(title = "render Boxes"),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Test", tabName = "Test")
    )
  ),
  dashboardBody(
    tags$head(
      tags$style(
        HTML('
          .box {
            margin: 0px;
          }
          [class*="jqui-interaction-"] {
            padding-left: 5px;
            padding-right: 5px;
            margin-top: 5px;
            margin-bottom: 5px;
          }
          .row {
            height: 220px;
          }
        ')
      )
    ),
    tabItems(
      tabItem(
        tabName = "Test",
        fluidRow(
          tabPanel("Boxes", uiOutput("myboxes"))
        ),
        fluidRow(
          actionButton("addBox", "add Box")
        )
      )
    )
  )
)

server <- function(input, output, session) {
  rv <- reactiveValues(v = list(), QRSList = c(), width = c(), height = c())
  
  observeEvent(input$addBox, {
    num <- length(rv$QRSList) + 1
    rv$QRSList <- append(rv$QRSList, num)
    
    newBox <- jqui_resizable(
      shinydashboard::box(
        height = "100%",
        width = 1,
        title = paste("Box", num),
        "Box content here", br(),
        paste("More box content", num),
        id = paste("box_", num, sep = "")
      ),
      options = list(
        animate = TRUE,
        animateDuration = "fast",
        ghost = TRUE,
        grid = c(10, 10),
        autoHide = TRUE,
        distance = 30
      )
    )
    rv$v <- append(rv$v, newBox)
    insertUI(selector = "#myboxes", where = "beforeEnd", ui = newBox)
    
  })
  
  observeEvent(input$boxDimensions, {
    new_dimension <- input$boxDimensions
    rv$width[new_dimension$num] <- new_dimension$width
    rv$height[new_dimension$num] <- new_dimension$height
  })
  
}

shinyApp(ui = ui, server = server)

However, this generates an issue where the boxes don’t automatically fill up the space.
Boxes not filling up space
I would ideally like to have box 6 do this:
Box should do this
How can I fix this?
I am open to R and JQuery solutions, as well as solutions which have light JS.

I’ve tried simply re-rendering all of the boxes after a new box is added. This does not solve the problem either, it also gets rid of all of the original box dimensions (that is why there’s a field called input$boxDimensions, it is legacy unneeded code).

If there’s a way to re-render all of the boxes

Header and footer not aligning with main body on mobile site

I’m working on an assignment to build a fully responsive website, however I’ve ran into some issues with the mobile design of the website. When I change the dimensions of the site to mobile, such as an iphone 12, the header and footer doesn’t align with the main body. For example, the main menu extends past the main body hiding the hamburger menu bar. You could only access it if you scroll to the right. Next, the footer doesn’t seem to be aligning properly with the main body as well. There is also a lot of extra white space on the right hand side of the mobile site. I’ve tried to minimize the text in the footer, but this didn’t work out. I’m really stuck here and I don’t want to re-build the site again.

{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Montserrat", sans-serif;
  font-weight: <900>;
  font-style: normal;
}

nav {
  background-color: hsl(220deg 100% 80%);
  box-shadow: hsl(220deg 60% 50%);
  color: #ffffff;
  text-decoration: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 10%;
  border-bottom: 1px solid #000;
  transition: all 0.2s ease-in-out;
  z-index: 100;
}

nav ul li {
  color: #808080;
  list-style: none;
  display: inline-block;
  margin: 10px 20px;
  font-weight: 500;
  cursor: pointer;
}

nav img {
  width: 20%;
  height: 20%;
  position: relative;
  top: 0px;
  bottom: 20px;
  left: 5px;
  right: 300px;
}

.nav-btn {
  background: #000;
  color: #fff;
  font-size: 16px;
  padding: 15px 25px;
  border: 0;
  outline: 0;
  border-radius: 40px;
  cursor: pointer;
}

.nav-btn img {
  width: 12%;
  height: 12%;
  position: absolute;
  top: 100px;
  left: -10px;
}

.header {
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(#c9d0ff 0%, #d3ecff 50%);
  padding: 0 10%;
  display: flex;
  justify-content: center;
  flex-direction: column;
  overflow: hidden;
  background: #C04848;
  background: linear-gradient(#c9d0ff 0%, #d3ecff 50%), url("main.png");
  background-size: cover;
  background-repeat: no-repeat;
}

.header h1 {
  margin-top: 100px;
  font-size: 3vw;
  line-height: 3.5vw;
}

.content {
  height: 1000px;
}

nav.fixedToTop {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
}


/* add space for fixed header when it's fixed to top */

nav.fixedToTop+.content {
  margin-top: 8rem;
}

.menu-icon {
  display: none;
}


/*<------------------------------- FOOTER ------------------------------>*/

footer {
  position: relative;
  width: 100% height: auto;
  padding: 50px 100px;
  background: #ffffff;
}

footer .container {
  width: 100%;
  display: grid;
  grid-template-columns: 2fr 1fr 1fr 1fr;
  grid-gap: 20px;
}

footer .container .sec h3 {
  position: relative;
  color: #333;
  font-weight: 600;
  margin-bottom: 15px;
  padding-bottom: 5px;
}

footer .container .sec p {
  color: #555;
}

footer .container .sci {
  margin-top: 20px;
  display: grid;
  grid-template-columns: repeat(4, 50px);
}

footer .container .sci li {
  list-style: none;
}

footer .container .sci li a {
  display: inline-block;
  width: 36px;
  height: 36px;
  background: #333;
  display: grid;
  align-content: center;
  justify-content: center;
  text-decoration: none;
}

footer .container .sci img {
  color: #fff;
}

footer .container .quicklinks {
  position: relative;
}

footer .container .quicklinks ul li {
  list-style: none;
}

footer .container .quicklinks ul li a {
  color: #555;
  text-decoration: none;
  margin-bottom: 10px;
  display: inline-block;
}

footer .container .contact .info {
  position: relative;
}

footer .container .contact .info li {
  display: grid;
  margin-bottom: 16px;
}

footer .container .contact .info li span {
  color: #555;
}

footer .container .contact .info li a {
  color: #555;
  text-decoration: none;
}

.copyrightText {
  width: 100%;
  background: #fff;
  padding: 20px 100px 30px;
  text-align: center;
  color: #555;
  border: 1px solid rgba(0, 0, 0, 0.15);
}

@media (max-width: 991) {
  footer {
    padding: 40px;
  }
  footer .container {
    width: 100%;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-gap: 20px;
  }
  .copyrightText {
    padding: 20px 40px 30px;
  }
}

@media (max-width: 768px) {
  footer .container {
    width: 100%;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-gap: 20px;
  }
}


/*<------------------------------- END OF FOOTER ------------------------------>*/


/* ------------- Media Queries for navbar ---------- */

@media only screen and (max-width: 991px) {
  nav ul {
    position: absolute;
    width: 100%;
    color: #0000ff;
    top: 2.5rem;
    left: 0%;
    right: 0;
    top: 100%;
    text-decoration: none;
    height: calc(100vh - 3.5rem);
    overflow: auto;
    pointer-events: none;
    opacity: 0;
    transition: top .4s, opacity .3s;
    padding-top: 1rem;
    padding: 1.25rem 1.5rem;
    display: inline-grid;
    justify-content: space-between;
    align-items: center;
    transition: background-color .3s;
  }
  .nav ul::-webkit-scrollbar {
    width: 0;
  }
  nav ul {
    background-color: #000000;
    font-weight: bold;
  }
  .nav ul:hover {
    background-color: ;
  }
  .show-menu {
    opacity: 1;
    top: 3.5rem;
    pointer-events: initial;
  }
  .menu-links {
    color: #fff;
  }
  .nav-btn {
    display: none;
  }
  nav.logo {
    width: 150px;
  }
  .menu-icon {
    display: block;
    width: 30px;
  }
  .show-menu {
    max-height: 300px;
  }
}


}

/*---------- Media Queries for header content --------------- */
@media only screen and (max-width: 991px) {
  .header {
    min-height: auto;
    padding: 0;
  }
  
  .user-img {
    width: 100%;
    right: auto;
    position: relative;
    margin-top: 100px;
  }
}
<!DOCTYPE html>
<html class="html" lang="en">
<meta charset="UTF-8">

<head>

  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Title</title>
  <link rel="stylesheet" href="style.css">
  <link rel="main" href="main.js">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100..900;1,100..900&display=swap" rel="stylesheet">
</head>

<body>
  <nav>
    <img src="" alt="" class="logo">
    <ul id="menu-links">
      <li>Home</li>
      <li>About Us</li>
      <li>Courses</li>
      <li>Pricing</li>
      <li>Contact</li>
      <li>Blog</li>
    </ul>
    <button class="nav-btn">Get Started </button>
    <img src="menu.png" alt="" class="menu-icon" onclick="toggleMenu()">
  </nav>


  <div class="header">
    <h1>JOIN US<br>TODAY!</h1>
    <img src="main.png" alt="" class="user-img">
  </div>

  <footer>
    <div class="container">
      <div class="sec aboutus">
        <h3>About Us</h3>
        <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque placerat quam vel est sodales hendrerit ac sit amet augue. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Pellentesque ipsum enim, venenatis
          at sem ac, facilisis suscipit sapien. </p>
        <ul class="sci">
          <li>
            <a href="#"><img src="facebook.png" alt="facebook"></a>
          </li>
          <li>
            <a href="#"><img src="instagram.png" alt="instagram"></a>
          </li>
          <li>
            <a href="#"><img src="youtube.png" alt="youtube"></a>
          </li>
          <li>
            <a href="#"><img src="twitter.png" alt="twitter"></a>
          </li>
        </ul>
      </div>

      <div class="sec quicklinks">
        <h3>Support</h3>
        <ul>
          <li><a href="#">FAQ</a></li>
          <li><a href="#">Privacy Policy</a></li>
          <li><a href="#">Help</a></li>
          <li><a href="#">Contact</a></li>
        </ul>
      </div>

      <div class="sec quicklinks">
        <h3>Shop</h3>
        <ul>
          <li><a href="#">Courses</a></li>
          <li><a href="#">Packages</a></li>
          <li><a href="#">One-on-one</a></li>
        </ul>
      </div>

      <div class="sec contact">
        <h3>Contact Us</h3>
        <ul class="info">
          <li>
            <span><img src="phone.png" rel="phone"><p><a href="#">+1 557 555 7256</a></p></span>
          </li>
          <li>
            <span><img src="mail.png" rel="email"><p><a href="#">[email protected]</a></p></span>
          </li>
        </ul>
      </div>
    </div>


  </footer>
  <div class="copyrightText">
    <p>Copyright 2024 Online Tutorials. All Rights Reserved.</p>
  </div>

  <script>
    let menuLinks = document.getElementById("menu-links");

    function toggleMenu() {
      menuLinks.classList.toggle('show-menu');
    }

    var prevScrollpos = window.pageYOffset;

    /* Get the header element and it's position */
    var headerDiv = document.querySelector("nav");
    var headerBottom = headerDiv.offsetTop + headerDiv.offsetHeight;

    window.onscroll = function() {
      var currentScrollPos = window.pageYOffset;

      /* if scrolling down, let it scroll out of view as normal */
      if (prevScrollpos <= currentScrollPos) {
        headerDiv.classList.remove("fixedToTop");
        headerDiv.style.top = "-7.2rem";
      }
      /* otherwise if we're scrolling up, fix the nav to the top */
      else {
        headerDiv.classList.add("fixedToTop");
        headerDiv.style.top = "0";
      }

      prevScrollpos = currentScrollPos;
    }

    /*=============== SHOW MENU ===============*/
    const showMenu = (toggleId, navId) => {
      const toggle = document.getElementById(toggleId),
        nav = document.getElementById(navId)

      toggle.addEventListener('click', () => {
        // Add show-menu class to nav menu
        nav.classList.toggle('show-menu')
        // Add show-icon to show and hide menu icon
        toggle.classList.toggle('show-icon')
      })
    }

    showMenu('menu-links', 'menu-links')
  </script>



</body>

</html>

Can I use inertia js with multi pages projects?

I have a laravel project with many blades not just app blade, can I use inertiajs in this project and how?

NOTE: I’m new in Laravel development and interiajs and still discovering 🙂

I still didn’t tried but I just read the inertia documentation and run demo app

Sqlite3 database empty after running migration in javascript

this is db.js

const sqlite3 = require('sqlite3').verbose();
const path = require('path')
const { migrationScript } = require('../db/migrations/migrate');
const WDIR = process.cwd();
const DB_PATH = path.join(WDIR, 'db', 'DB.db');

const db = new sqlite3.Database(DB_PATH, (err) => {if (err) { console.log(err);}});
db.run(migrationScript, (err) => {if (err) { console.log(err);}})
db.close()

migrate.js doesn’t even matter as it’s just a const multiline string and it gets ignored

no matter what i type in it. i also get no erros.
after execution it creates a 0kb file that ofcourse doesn’t have any tables or nothing.
im mentioning that migrationscript starts with pragma foreign_keys = on, but again it doens’t seem to even read it. i tried using serialize and doing the db.run inside it, didn’t matter.
yes i checked, migrationScript object is NOT empty inside db.js. it seems fine

SOLID principles: extract code in superclass

In my application I have N child classes all extending a superclass. Every class has its own implementation of serialize but they share some common code. For example:

class Serializer {
   serialize = () => throw Exception("...")
}

class JSONSerializer extends Serializer {
   serialize = () => {
      console.log("Formatting...")
      // ...
   }
}

class XMLSerializer extends Serializer {
   serialize = () => {
      console.log("Formatting...")
      // ...
   }
}

Do I violate the SOLID principles (in particular interface inheritance over implementation inheritance -Liskov substitution-) if I wrap the common code inside the superclass in a function format and call it inside the child classes? If yes, how can I adhere to the principle?

class Serializer {
   format = () => console.log("Formatting...")
   serialize = () => throw Exception("...")
}

class JSONSerializer extends Serializer {
   serialize = () => {
     this.format()
     // ...
   }
}

class XMLSerializer extends Serializer {
   serialize = () => {
     this.format()
     // ...
   }
}

Basic Event Binding in Angular not working as intended

I am incredibly new to angular and was trying to learn how to use event binding. I began implementing a few, but realized even when I was using basic ones the output would not be as expected. Actually, I wouldn’t get any output at all. One example is the following, where I did not receive any output.

ts file

export class Personal {
   test() { 
    alert("Hello");
   //console.log("Hello") 
   }
}

HTML file

    <button  (click)="test()" >Click here!</button>

With this, in my component’s ts and HTML files, respectively, I should receive a popup alert when clicked, but I received nothing.

I also used console.log(“hello”) and nothing showed up in the console when I inspected. The web app servers without any issues, and the other buttons and text display correctly, even with the different bindings. It’s just the event binding that I am having trouble with. I am on mac if that may be an issue. Thanks.

Poor line quality withJS Graphics 2D Drawing

I am dismayed at the poor quality of lines I draw in Graphics2D. When I draw a line with
lineWidth=1 and strokeStyle="black" I would expect the line to look the same as the border of my canvas, which is 1px solid black. But no, the line is (or at least looks) wider, and is kind of fuzzy and gray rather than black. See attached image which is the output of this code:

<html>
<body>
<canvas id="canvas" width="200" height="200" style="border:1px solid black"></canvas>
</body>
<script>
ctx             = canvas.getContext("2d");
ctx.lineWidth   = 1;
ctx.strokeStyle = "black";
ctx.strokeRect(3, 3, 150, 150);
</script>
</html>

Any ideas ? I am also intrigued by the (very faint) shadow lines on each side of the border as well as the drawn lines (admittedly you only see these when the image is enlarged).