how to get the grid to be of the same size

i have created an input button which will add more squares to the grid but i need the grid to be of the same size regardless of how many squares i add to it while the squares become smaller to account for themselves inside the grid

const grid = 
document.querySelector('.grid');
const blackButton = 
document.querySelector('.blackbutton');
blackButton.addEventListener('click', 
blkButton);
const clear = 
document.querySelector('.clearbutton')
clear.addEventListener('click', 
clearGrid);
const eraserButton = 
document.querySelector('.eraserbutton')
eraserButton.addEventListener('click', 
ersButton)
const rainbowButton =document.querySelector('.rainbowbutton')
rainbowButton.addEventListener('click', 
rbwButton)
 //DOM handling



function getGrid(size) {
const grid = 
document.querySelector('.grid');
 const boxs = 
grid.querySelectorAll(".box");
boxs.forEach((div) => div.remove());
grid.style.gridTemplateColumns = 
`repeat( ${size} , 1fr)`;
grid.style.gridTemplateRows = `repeat( 
${size} , 1fr)`;

   let amount = size * size
    for (let i = 0; i < amount; i++) {
  const box = 
  document.createElement('div');
  box.classList.add('box');
  grid.appendChild(box);
} 
}

getGrid(16)

 function changeSize(input){
if (input >= 2 && input <= 100) {
  getGrid(input);
 }
 else {
  console.log("Only between 2 to 100 Fam!")
}

}

D3.JS area fill chart

Hi I was wondering how do I fill the area d3.js line chart? I am not too sure what to add or change. Would be helpful if you helped me out 🙂 I am trying to add a gradient to it but no luck. If i did change something in the code, the chart would just give an error and not show up in the page

JS BABEL

https://codepen.io/klattman/pen/bxLoQY

let dataType = 'price_usd'
let currency = 'bitcoin'
let data = null
let rawData = null
let range = [0, 0]

const dataTypeCaptions = {
  'price_usd': 'US Dollar',
  'market_cap': 'Market capitalization',
  '24h_vol': 'Trading Volume'
}

const margin = { left: 80, right: 100, top: 50, bottom: 100 }
const totalHeight = 500
const totalWidth = 800
const height = totalHeight - margin.top - margin.bottom
const width = totalWidth - margin.left - margin.right

const slider = $('#date-slider')

const svg = d3
 .select('#chart-area')
 .append('svg')
 .attr('width', totalWidth)
 .attr('height', totalHeight)
 .attr('viewBox', `0 0 ${totalWidth} ${totalHeight}`)

const g = svg
 .append('g')
 .attr('transform', `translate(${margin.left}, ${margin.top})`)

// Time parser for x-scale
const parseTime = d3.timeParse('%d/%m/%Y')
// For tooltip
const bisectDate = d3.bisector(d => d.year).left

// Scales
const x = d3.scaleTime().range([0, width])
const y = d3.scaleLinear().range([height, 0])

const formatSi = d3.format('.2s')
function formatAbbreviation(x) {
  const s = formatSi(x)
  switch (s[s.length - 1]) {
    case "G":
      return s.slice(0, -1) + 'B'
    case "k": 
      return s.slice(0, -1) + 'K'
    default:
      return s
  }
}

// Axis generators
const xAxisCall = d3.axisBottom().ticks(4)
const yAxisCall = d3
 .axisLeft()
 .ticks(6)
 .tickFormat(d => formatAbbreviation(d))

// Axis groups
const xAxis = g
 .append("g")
 .attr("class", "x axis")
 .attr("transform", "translate(0," + height + ")")

const yAxis = g.append("g").attr("class", "y axis")

// Y-Axis label
const yLabel = yAxis
 .append("text")
 .attr("class", "axis-title")
 .attr("transform", "rotate(-90)")
 .attr("y", 6)
 .attr("dy", ".71em")
 .style("text-anchor", "end")
 .attr("fill", "#5D6971")

// Line path generator
const line = d3
 .line()
 .x(d => x(d.year))
 .y(d => y(d.value))

const dataUrl = "https://raw.githubusercontent.com/adamjanes/udemy-d3/master/06/6.10.1/data/coins.json"

const graphLine = g
  .append("path")
    .attr("class", "line")
    .attr("fill", "none")
    .attr("stroke", "grey")
    .attr("stroke-with", "3px")
 

$("#coin-select").change(function() {
  currency = $(this).val()
  update()
})

$("#var-select").change(function() {
  dataType = $(this).val()
  update()
})

const $dateLabel1 = $("#dateLabel1")
const $dateLabel2 = $("#dateLabel2")

const getSelectedData = () => rawData[currency]

const update = () => {
  
  const allSelectedData = getSelectedData()
  data = allSelectedData
    .filter((d, i) => i >= range[0] && i <= range[1])
    .map(d => ({
      year: parseTime(d.date),
      value: +d[dataType],
    }))

  slider.slider({
    max: allSelectedData.length - 1,
    min: 0,
    step: 1,
    range: true,
    values: range,
    slide: (event, ui) => {
      range = ui.values
      update()
    },
  })
 
 $dateLabel1.text(allSelectedData[range[0]].date)
 $dateLabel2.text(allSelectedData[range[1]].date)

  // Set scale domains
  x.domain(d3.extent(data, d => d.year))
  y.domain([
    d3.min(data, d => d.value) / 1.005,
    d3.max(data, d => d.value) * 1.005
  ])

  // Generate axes once scales have been set
  xAxis.transition().call(xAxisCall.scale(x))
  yAxis.transition().call(yAxisCall.scale(y))
  
  yLabel.text(dataTypeCaptions[dataType])
 
  graphLine
    .transition()
    .ease(d3.easeLinear)
    .duration(100)
    .attr("d", line(data))
};

function mousemove() {
  const x0 = x.invert(d3.mouse(this)[0])
  const i = bisectDate(data, x0, 1)
  const d0 = data[i - 1]
  const d1 = data[i]
  const d = x0 - d0.year > d1.year - x0 ? d1 : d0;
  focus.attr("transform", `translate(${x(d.year)},${y(d.value)})`)
  focus.select("text").text(d.value)
  focus.select(".x-hover-line").attr("y2", height - y(d.value))
  focus.select(".y-hover-line").attr("x2", -x(d.year))
}

/******************************** Tooltip Code ********************************/
const focus = g
  .append("g")
  .attr("class", "focus")
  .style("display", "none")

focus
  .append("line")
  .attr("class", "x-hover-line hover-line")
  .attr("y1", 0)
  .attr("y2", height)

focus
  .append("line")
  .attr("class", "y-hover-line hover-line")
  .attr("x1", 0)
  .attr("x2", width)

focus.append("circle").attr("r", 7.5)

focus
  .append("text")
  .attr("x", 15)
  .attr("dy", ".31em")

g
  .append("rect")
  .attr("class", "overlay")
  .attr("width", width)
  .attr("height", height)
  .on("mouseover", () => focus.style("display", null))
  .on("mouseout", () => focus.style("display", "none"))
  .on("mousemove", mousemove)

 /******************************** Tooltip Code ********************************/

d3.json(dataUrl).then(response => {
 rawData = response
 const data = getSelectedData()
 range = [0, data.length - 1]
 update()
})

Thanks!

Why does import operation works in the below react component?

Why does the below react work? As the function name in Hello.js component is Hello but it was not mentioned in main component that imported the Hello.js , Is it a property of arrow function?

The Hello.js component :

import React from 'react';
const Hello =() => <h1> HELLO <h1/>
export default hello

Where Hello.js component got exported/ been Called.

import React from 'react';
import MyComponent form './Hello'
class App extends React.Component{
   render(){
     return(
            <div>
               <MyComponent />
            <div/>
           );
      }
 }

Failed to upload data using Postman

I have created a product uploaded system and the admin can upload the information but I have faced an error below the code given,

Below the code of Product models is given below,

ProductModel.js

const {Schema, model} = require('mongoose');
const Joi = require('joi');

const Product = model('Product', Schema({
    name: String,
    description: String,
    price: Number,
    category:{
        type: Schema.Types.ObjectId,
        ref: "Category",
        required: true
    },
    quantity: Number,
    photo: {
        data: Buffer, 
        contentType: String,
    }
}, {timestamps: true}));

const validate = product=>{
    const schema = Joi.object({
        name: Joi.string().min(3).max(255).required(),
        description: Joi.string().max(2000).required(),
        price: Joi.number().required(),
        quantity: Joi.number().required(),
        category: Joi.string().required(),
    });
    return schema.validate(product);
}


module.exports={
    Product, validate
}

Here is the code of Product Controller’s

productController.js

const _ = require('lodash');
const formidable = require('formidable');
const fs = require('fs');
const {Product, validate} = require('../models/ProductModel');

const createProduct = async (req, res) =>{
    let form = new formidable.IncomingForm();
    form.keepExtensions = true;
    form.parse(req, (err, fields, files) =>{
        if (err) return res.status(400).send("Something went wrong!!!");
        const {error} = validate(_.pick(fields, ["name", "description", "price", "category", "quantity"]));
        if(error) return res.status(400).send(error.details[0].message);

        const product = new Product(fields);

        if(files.photo){
            // <input type="file" name="photo" />
            fs.readFile(files.photo.path, (err, data) =>{
                if(err) return res.status(400).send("Problem in file data!!!");
                product.photo.data = data;
                product.photo.contentType = files.photo.type;
                product.save((err, result) =>{
                    if(err) res.status(500).send("Internal Server Error!!!");
                    else return res.status(201).send({
                        message:"Successfully, Product Created!!!",
                        data: _.pick(result, ["name", "description", "price", "category", "quantity"])
                    })
                })
            })
        }else{
            return res.status(400).send("No image Provided!!!")
        }
    })
}
const getAllProduct = async (req, res) =>{
    const products = await Product.find();
    return res.status(200).send(products);
}


module.exports ={
    createProduct, getAllProduct
}

The Routing Code is here,

productRoute.js

const router = require('express').Router();
const {createProduct, getAllProduct} = require('../controllers/productController');
const admin = require('../../middlewares/admin');
const authorize = require('../../middlewares/authorize');

router.route('/')
    .post([authorize, admin], createProduct)
    .get(getAllProduct);


module.exports = router;

Console error ScreenShot is given below,
enter image description here

Postman Error is given below after submitting data,
enter image description here

Why does constructor of HttpClient in Angular not need param, when I instanstiate it via constructor of other class, but needs via new?

I need to make a static method for instanstiate an object of class, but faced an issue.

import { HttpClient } from '@angular/common/http';

export MyClass {
  // Case 1
  public static init(): MyClass {
    return this(new HttpClient(***), ....); // Need to pass new HttpClient() instead ***
  }

  // Case 2
  public constructor(private http: HttpClient, ....) {} // Need to pass nothing
}

Why I have to pass argument in case 1, but in case 2 not? And how to solve my problem?

Where can I find this Microsoft Emoji Library for Reactjs/Nextjs

I want to ask for the name of this Microsoft emoji library in Dev.to web page. It looks like this:

Example

Example about this library

example 2
Using with markdown editor

example 3
Previewing on IOS

I want to use it as a default emoji library for my web app. Like dev.to, it won’t use other libraries when we access from another os such as IOS that we have Apple Emoji.

I want to add it to my personal project for a blog so as to making markdown editor for this emoji with less difficulty. Thank you for all of your help. I would be so grateful If I figured out because I have been searching for a weak about this.

Append image from array to HTML

I’m trying make buttons to append images to HTML from array. Why the first snippet doesn’t work?

First snippet with array doesn’t work

const fs = require('fs');
const dir = fs.readdirSync('/Files/Изображение').filter(files => files.endsWith('.png'))

let imag = dir[0];

function createImgBlock() {
    const imgBlocks = document.createElement('img');
    imgBlocks.src = '/Files/Изображение/' + dir[0];
    document.body.append(imgBlocks);
}

Second snippet only with the name of image is work

const fs = require('fs');
const dir = fs.readdirSync('/Files/Изображение').filter(files => files.endsWith('.png'))

let imag = dir[0];

function createImgBlock() {
    const imgBlocks = document.createElement('img');
    imgBlocks.src = '/Files/Изображение/' + '1407916_900_600.png';
    document.body.append(imgBlocks);
}

I’m using useState to change the state of an element based on if a checkbox if checked or not, but the state is not updating – couldnt find reason

import { useCallback, useEffect, useState, useRef } from 'react';

const [changeEl, setChangeEl] = useState(false);
let chosenInput = useRef();
let result = useRef();
let allCheckboxes = [];

 const checkHandler = useCallback(
    async (e) => {
      const allInputs = document.querySelectorAll('input');
      for (const input of allInputs) {
        if (input.type === 'checkbox') {
          allCheckboxes.push(input);
        }
      }
      chosenInput.current = e.target;
      if (chosenInput.current.name === 'notChecked') {
        chosenInput.current.name = 'checked';
      } else {
        chosenInput.current.name = 'notChecked';
      }

      for (const [i, value] of result.current.entries()) {
        if (
          chosenInput.current.name === 'checked'
        ) {
          allCheckboxes[i].disabled = true;
          console.log(allCheckboxes[i].disabled) //TRUE
          chosenInput.current.disabled = false;
          setChangeEl(allCheckboxes[i].disabled); 
          console.log(ChangeEl) //THIS IS STILL FALSE BUT IT IS SUPPOSED TO CHANGE

        }
        if (chosenInput.current.name !== 'checked') {
          allCheckboxes[i].disabled = false;
          setChangeEl(allCheckboxes[i].disabled); 
          console.log(changeEl) //THIS WORKS
        }
      }
    },
    [changeEl, allCheckboxes]
  );

the changeEl is false even when I’m setting it to true. But it is false when I’m setting it to false. I think it has something to do with the useState not updating it immediately but I’m not sure it’s updating it at all.
If I’m using useContext to update it it works but I don’t want to do that because it is unnecessary.
I couldn’t find an answer for this so I would really appreciate the help.

How to handle client-side JavaScript errors with Nuxt.JS

I’m trying to show an error page when an error occurs on the client side Javascript of Vue components.

In dev mode, I get a customer error page I’ve created in the layouts/error.vue page whenever the client runs into an error. But when I build and start the app no error page is displayed even though the error is logged in the console. This error page is only displayed for server errors.

I’ve tried creating a custom error handling component using the following code:

mounted() {
  window.onerror = this.onError
},
methods: {
  onError(msg, source, ln, cn, err) {
    console.log('Error received')
    this.show = true
    this.error = { msg, source, ln, cn, err }
  }
}

However, this function does not seem to handle the client sides error that occurs.

Does anyone know what the best way is to handle all unhandled clients side errors?

How to stop the Closure Compiler from adding Newlines?

I have a javascript file that I have written.
It is larger than it has to be.
I use the closure compiler to solve the problem of it being larger than it has to be.

However, the resulting javascript is still somewhat slightly larger than it has to be.
It has line breaks in it, and the javascript would work without it.
I know why it adds line breaks, but for my purposes, the line breaks are not required.

How would I force the compiler to not add line breaks?
Here is the command line prompt that I use: java -jar closure-compiler.jar input.js > output.js --rewrite_polyfills=false

I have added a delete Function , It is deleteing the row successfully but i want to delete from localstorage tooo in JavaScript

I have added a delete Function , It is deleteing the row successfully but i want to delete from localstorage tooo in JavaScript
And Whenever user reload the page so it could be delete from localstorage alo so the book will be not appear

JavaScript File

class Display {
    add(book) {
        console.log('Adding to UI');
        let tableBody = document.getElementById('tableBody')
        let uiString = `<tr class="tableBody" id="tableBody">
                            <td id="search">${book.name}</td>
                            <td>${book.author}</td>
                            <td>${book.type}</td>
                            <td><input type="button" value="Delete Row" class="btn btn-outline-danger" onclick="RemoveRow()"></td>
                        </tr>`;
        tableBody.innerHTML += uiString;

        // save the data to the browser's local storage -----
        const books = JSON.parse(localStorage.getItem("books"));
        // console.log(books);
        if (!books.some((oldBook) => oldBook.id === book.id)) books.push(book);
        localStorage.setItem("books", JSON.stringify(books));

    }

function RemoveRow(uid) {
    // event.target will be the input element.
    let td1 = event.target.parentNode; 
    let tr1 = td1.parentNode; 
    tr1.parentNode.removeChild(tr1);// the row to be removed
    window.localStorage.setItem("books", JSON.stringify(books));
}

$('tableBody').on('click', 'input[type="button"]', function(e){
    $(this).closest('tr').remove()
})

HTML File

    <div id="table">

        <h1>Your Books</h1>
        <table class="table table-dark table-striped">
            <thead>
                <tr>
                    <th scope="col">Name</th>
                    <th scope="col">Author</th>
                    <th scope="col">Type</th>
                    <th scope="col">Status</th>
                </tr>
            </thead>
            <tbody class="tableBody" id="tableBody"> </tbody>
        </table>
    </div>

</div>

    

How to implement qr code scanner(mobile) in next.js

I am building a website with scanning qr code.
This works fine on desktop but not working on mobile.
In Reactjs, this works with secure connection.
But in Nextjs, this does not work with secure connection.
I run custom server in Nextjs.

https://dev.to/nakib/using-https-on-next-js-local-development-server-bcd

This is my code.

import React, { useState } from 'react';
import { QrReader } from 'react-qr-reader';

const Home = (props) => {
    const [data, setData] = useState('No result');

    return (
        <>
            <QrReader
                onResult={(result, error) => {
                    if (!!result) {
                        setData(result?.text);
                    }

                    if (!!error) {
                        console.info(error);
                    }
                }}
                style={{ width: '100%' }}
            />
            <p>{data}</p>
        </>
    );
};
export default Home;

Filter out duplicate Hough Lines Opencvjs

I’m trying to filter out all lines as a result from HoughLine function in opencv. Currently just using getLines() function to get all lines then sorting them according to their rho value for each line. Then applying for loop to remove duplicates, problem is as follows:

In code if in (r1, θ1) and (r2, θ2) which I’m comparing in inner for loop for both either (r1,r2) positive or (r1,r2) negative (based on html canvas) then it’s easy to filter them. But if either of them is positve or negative respectively then that line also gets included in finalLines array. Which can be explained through following figure:

enter image description here

function:

function getLines(minthresh = 8) {
  let t = 300,
    j = 0;
  linesMat = new cv.Mat();
  let copy = org_img.clone();

  while (t > 0 && j < minthresh) {
    try {
      cv.HoughLines(tmp, linesMat, 1, Math.PI / 180, t);
      j = linesMat.matSize[0]
      console.log(`t=${t} j=${j}`, linesMat.matSize);
    } catch (err) {
      console.log(`error for t=${t}`);
      j = 0;
    } finally {
      t = t - 10;
    }
  }
  console.log('hough lines', linesMat.rows);
  let bool = true;


  let lines = linesMat.data32F;
  let rows = linesMat.rows;
  let foundLines = [];
  finalLines = [];

  for (let i = 0; i < rows; i++) {
    let l = [lines[i * 2], lines[i * 2 + 1]];
    foundLines.push(l);
  }

  foundLines.sort((a, b) => a[0] - b[0]);

  console.log('filtering lines starts, sorted found lines:', foundLines);

  for (let [index, line] of foundLines.entries()) {
    let rho = line[0];
    let theta = line[1];
    let a = Math.cos(theta);
    let b = Math.sin(theta);
    let x0 = a * rho;
    let y0 = b * rho;
    let startPoint = {
      x: x0 - 1000 * b,
      y: y0 + 1000 * a
    };
    let endPoint = {
      x: x0 + 1000 * b,
      y: y0 - 1000 * a
    };
    let color = [random(), random(), random(), 255];


    cv.line(copy, startPoint, endPoint, color);

    bool = false;

    for (let [jindex, linet] of foundLines.slice(index + 1).entries()) {
      console.log(`for index=${index} jindex=${jindex+1} linet=${linet} line=${line}`);

      bool = false;
      if (linet[0] !== line[0]) {
        k = [Math.abs(linet[0] - line[0]) < 50, Math.abs(linet[1] - line[1]) < 0.5];
        console.log(`k=${k}`);

        if (k[0] && k[1]) {
          bool = true;
          break;
        }
      }
    }

    if (bool) {
      continue;
    }
    finalLines.push(line);
    console.log(`push for i=${index}`);
    console.log(`%c rho=${rho} deg=${theta * (180/Math.PI)}`, `background: rgba(${color[0]}, ${color[1]}, ${color[2]}, 1); color: black`);
  }
  cv.imshow('op', copy);
}