Add random/uneven spacing between pixel blocks in an HTML canvas

I have this code that takes an image and divides it into blocks with a size of blockSize, then deletes the surrounding pixels and spaces them out by a spacing defined by spacing. This creates a uniform split, but I want to add some randomness to the spacing to distribute the blocks unevenly (controlled by variance variable).

Bonus answer: Also add some randomness to the blockSize to make some blocks larger than others. This is my current code:

const canvas = document.createElement("canvas")
const ctx = ref.current.getContext("2d")!
const imgData = ctx.getImageData(0, 0, ref.current.width, ref.current.height)
const pixels = imgData.data

let blockSize = 5
let spacing = 70
let variance = 50

for (let row = 0; row < imgData.height; row++) {
    for (let col = 0; col < imgData.width; col++) {
        const i = (row * imgData.width + col) * 4
        let r = pixels[i]
        let g = pixels[i+1]
        let b = pixels[i+2]
        let a = pixels[i+3]
        const adjustedSpacing = spacing // Add randomness?
        const blockRow = Math.floor(row / (blockSize + adjustedSpacing))
        const blockCol = Math.floor(col / (blockSize + adjustedSpacing))
        const blockRowPixel = blockRow * (blockSize + adjustedSpacing)
        const blockColPixel = blockCol * (blockSize + adjustedSpacing)

        const withinBlockRow = row >= blockRowPixel && row < blockRowPixel + blockSize
        const withinBlockCol = col >= blockColPixel && col < blockColPixel + blockSize
        if (withinBlockRow && withinBlockCol) {
            pixels[i] = r
            pixels[i+1] = g
            pixels[i+2] = b
            pixels[i+3] = a
        } else {
            pixels[i] = 0
            pixels[i+1] = 0
            pixels[i+2] = 0
            pixels[i+3] = 0
        }
    }
}
ctx.putImageData(imgData, 0, 0)

This was my attempted solution, but it doesn’t work. It destroys the blocks:

const adjustedSpacing = Math.floor(Math.random() * variance) + spacing

Compiled javascript file have the duplicate variable declaration in the class constructor while using access modifiers in typescript class

I am trying to build a class in typescript which have few of the properties with access modifiers as in the below code.

class Coder {
    age : number;

    constructor(
    public readonly name : string,
    age : number,
    public lang : string,
    private address : string,
    protected id : number = 234
    )
    {
        this.name = name;
        this.age = age;
        this.lang = lang;
        this.address = address;
        this.id = Math.random();
    }

    getName()
    {
        return `My name is ${this.name}`;
    }
}

let coder = new Coder('Nayan', 28, 'JavaScript', 'LMP');

// Not possible as name is readOnly
// coder.name = 'Golu'; 

But the compiled code has the class with duplicate property decalation in the constructor as in the below code.

Once I try to remove any of the modifiers then the duplicate property get removed in compiled js file too (see age property).

"use strict";
class Coder {
    constructor(name, age, lang, address, id = 234) {
        this.name = name;
        this.lang = lang;
        this.address = address;
        this.id = id;
        this.name = name;
        this.age = age;
        this.lang = lang;
        this.address = address;
        this.id = Math.random();
    }
    getName() {
        return `My name is ${this.name}`;
    }
}
let coder = new Coder('Nayan', 28, 'JavaScript', 'LMP');
// Not possible as name is readOnly
// coder.name = 'Golu'; 

Not sure why is this happening as it is just violating the DRY rule.

React | MAterial UI table high load time

I am creating a material UI table based on a response from an API. the data has about 100 rows. For some of the columns, the table cells need to be text fields, that user can change on the go.
However, mapping over all the rows and creating text fields for some of the columns is making the table to load slower. I have attached the code for the table component, is there a way to optimize this?

const StyledTableCell = styled(TableCell)(({ theme }) => ({
  [`&.${tableCellClasses.head}`]: {
    backgroundColor: '#E10174',
    color: theme.palette.common.white,
    minWidth: '100px'
  },
  [`&.${tableCellClasses.body}`]: {
    fontSize: 12,
  },
}));

const StyledTableRow = styled(TableRow)(({ theme }) => ({
  '&:nth-of-type(odd)': {
    backgroundColor: theme.palette.action.hover,
  },
  // hide last border
  '&:last-child td, &:last-child th': {
    border: 0,
  },
}));



export default function CustomizedTables(props) {

  const {data, checked, handleChange, lockGroupOptions} = props
// The data prop is the data I am sending from the app component. It is an API response. the first object in the array may look like following
//{SKU: "xxxxxxxxxxxx", DetailDescription: "some description", Lockgroup: "some category", MaterialStandardName: "name", Notes: "some notes", StandardCost: 12, StatusName: "status", SubCategory: "some subcategory", 2023-05-08: 2 ,2023-05-15: 3, 2023-05-22: 4, 2023-05-29: 5, 2023-06-05: 6, 2023-06-12: null, 2023-06-19: null, 2023-06-26: null, 2023-07-03: null, 2023-07-10: null}

  const [tableHeaderData, setTableHeaderData] = useState([])
  const [tableBodyData, setTableBodyData] = useState([])
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);


// UseEffect is setting the states tableHeaderData and tableBodyData, which is used to create the header cells and body cells respectively

  useEffect(() => {
    if(data.list){
      setTableHeaderData(prevTableHeaderData => Object.keys(data.list[0]))
      setTableBodyData(prevTableBodyData => data.list)
    }
  }, [data.list])

  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };
  
  const lockGroupMenuItems = lockGroupOptions.map(option => <MenuItem value={option}>{option}</MenuItem>)

  const tableHeaderCells = tableHeaderData.map(headerCell => 
    headerCell === 'Lockgroup' 
    ? 

    <StyledTableCell align = 'center'>
      
      <FormControl sx ={{minWidth: '150px'}} size="small">
        <InputLabel sx = {{color: '#fff'}} id="demo-select-small-label">{headerCell}</InputLabel>
        <Select sx ={{}}
          labelId="demo-select-small-label"
          id="demo-select-small"
          value=''
          name='{option}'
          label="LockGroup"
          onChange={() => console.log('hello')}
        >
          <MenuItem value="">
            <em>None</em>
          </MenuItem>
          {lockGroupMenuItems}
        </Select>
      </FormControl>
    </StyledTableCell>
    :
    <StyledTableCell align = 'center'>{headerCell}</StyledTableCell>
  )

  const tableBodyCells = (rowsPerPage > 0 ? tableBodyData.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) : tableBodyData).map(tableRow => 
    <StyledTableRow key={tableRow.SKU} sx = {{cursor: 'pointer'}}>
      <StyledTableCell align = 'center'><Checkbox size = 'small' name = {tableRow.SKU} checked = {checked.includes(tableRow.SKU) ? true : false} onChange = {handleChange} /></StyledTableCell> 
      {tableHeaderData.map(key => !key.includes('-') 
      ? 
      <StyledTableCell align="center">{tableRow[key]}</StyledTableCell>
      :

      <StyledTableCell align = 'center'>
        <TextField
          size="small"
          id="outlined-helperText"
          
          label=''
          value=''
          onChange={() => console.log('clicked')}
          defaultValue={tableRow[key]}
        />
      </StyledTableCell>
      )}
    </StyledTableRow>)
  

  return (
    <ThemeProvider theme = {theme}>
      <TableContainer component={Paper}>
        <Table sx={{borderRadius: '5px'}} aria-label="customized table">
          <TableHead sx = {{position: 'sticky', top: '0'}}>
            <TableRow sx = {{cursor: 'pointer'}}>
              <StyledTableCell sx = {{maxWidth: '200px', backgroundColor: 'black'}} align = 'center' >Select All</StyledTableCell>
              {tableHeaderCells}
            </TableRow>
          </TableHead>
          <TableBody>
            {tableBodyCells}
          </TableBody>
          <TableFooter >
            <TableRow >
              <TablePagination
                rowsPerPageOptions = {[5, 10, 25]}
                component="div"
                count={100}
                page={page}
                onPageChange={handleChangePage}
                rowsPerPage={rowsPerPage}
                onRowsPerPageChange={handleChangeRowsPerPage}
              />  
            </TableRow>
            
          </TableFooter>
        </Table>

      </TableContainer>
    </ThemeProvider>
  );
}

Table pagination helps reduce the load time, but the actual requirement is to show all 100 rows in the page.
Any help would be great. Thanks!

Best way to implement thunder herd problem in React with Axios api call?

During exploring the “Thunder Herd Problem”, I thought to implement it with Axios call in react. So, I ask chatGPT to generate me the code. The code is:

import axios from 'axios';

const MyComponent = () => {
  const [data, setData] = useState(null);

  // Debounce function to delay API call
  const debounce = (func, delay) => {
    let timer;
    return function (...args) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        func.apply(this, args);
      }, delay);
    };
  };

  // Function to handle API call
  const fetchData = async () => {
    try {
      const response = await axios.get('https://api.example.com/data');
      setData(response.data);
    } catch (error) {
      console.error('Error fetching data:', error);
    }
  };

  // Debounced version of the API call function
  const debouncedFetchData = debounce(fetchData, 500);

  // Function to handle button click
  const handleClick = () => {
    debouncedFetchData();
  };

  return (
    <div>
      <button onClick={handleClick}>Fetch Data</button>
      {data && <div>{/* Render the fetched data */}</div>}
    </div>
  );
};

export default MyComponent;

But according to me, it is a simple Debounce function which will delay for .5 sec. It is not handling the error or retrying issue. It is not even adding jitter. If I am correct then can you give an example ?

javascript replace regex spaces and newlines

how to replace spaces and newlines together with additional closing code ; in javascript?

function main(){
   var a = 'hello'
   console.log(a)
}

console.log(main.toString().replace(/[n ]/g,''))

output

functionmain(){vara='hello'console.log(a)}

I want

function main(){var a='hello';console.log(a);}

How To View Unlised Videos on any Youtube Channel

As of my knowledge cutoff in September 2021, there is no legitimate way to view unpublished or unlisted videos on any YouTube channel.
Unpublished videos are those that have not been made public by the channel owner. They are only accessible to the owner and selected individuals who have been granted permission. There is no way for the general public to view unpublished videos unless the channel owner decides to make them public.

Add Price to the Main Price with CheckBox Checked

I’m trying to build a cart function for the existing Food ordering system.

There, the user can view the product price in

<div class="product__price m-t-5">
  <span class="product__price product__price--large">[email protected](model => model.ProductPrice)</span>
</div>

section.

If the selected product is customizable, I show the extra items in the view with Checkbox.

So what I want to know is, if the customer selects any extra items, the extra item price should be added to the main price.

Also, if a customer is unchecked, then it should subtract from the main amount.

Want to know how to do this using Javascript?

This is the HTML code.

  <div class="col-md-7">
   <div class="product-details-box m-b-60">
     <h4 class="font--regular m-b-20">@Html.DisplayFor(model => model.ProductName)</h4>
     <div class="product__price m-t-5">
       <span class="product__price product__price--large">[email protected](model => model.ProductPrice)</span>
     </div>
     <div class="product-var p-tb-30">
       <div class="product-quantity product-var__item d-flex align-items-center">
         <span class="product-var__text">Quantity: </span>
         <form class="quantity-scale m-l-20">
           <div class="value-button" id="decrease" onclick="decreaseValue()">-</div>
           <input type="number" id="number" name="number" value="1" />
           <div class="value-button" id="increase" onclick="increaseValue()">+</div>
         </form>
       </div>
       <div>
         <h4 class="font--regular m-b-20">Add Some Extra</h4> 
         @if (Model.CustomizableFoods.Count!=0) 
         { 
         foreach (var item in Model.CustomizableFoods)
         { 
         <div class="row">
           <ul class="list">
             <li class="list__item">
               <label class="label--checkbox">
                 <input type="checkbox" class="checkbox"> &nbsp; &nbsp; &nbsp; @item.ExtraItem - @item.Extra_Item_Price </label>
             </li>
           </ul>
         </div>
            } 
        }
       </div>
       <div class="product-var__item">
         <input class="btn btn--long btn--radius-tiny btn--green btn--green-hover-black btn--uppercase btn--weight m-r-20" type="submit" value="Add to cart" />
         <a href="wishlist.html" class="btn btn--round btn--round-size-small btn--green btn--green-hover-black">
           <i class="fas fa-heart"></i>
         </a>
       </div>
       <div class="product-var__item">
         <span class="product-var__text">Guaranteed safe checkout </span>
       </div>
       <div class="product-var__item d-flex align-items-center">
         <span class="product-var__text">Share: </span>
         <ul class="product-social m-l-20">
           <li>
             <a href="#">
               <i class="fab fa-facebook-f"></i>
             </a>
           </li>
           <li>
             <a href="#">
               <i class="fab fa-twitter"></i>
             </a>
           </li>
           <li>
             <a href="#">
               <i class="fab fa-pinterest-p"></i>
             </a>
           </li>
         </ul>
       </div>
     </div>
   </div>
 </div>

This is a sample of the view,

enter image description here

How can I wait for all async functions to be completed in useEffect before updating loading state?

I am trying to receive a list of book IDs from my API. For each book ID, I want to fetch its data from Google’s book API. Once all book info has been retrieved, I want to render divs for them. However, the loading state is being changed before each fetch has completed. Can someone explain to me why this is happening?

function ReadingListPage({ userID }) {
  const [books, setBooks] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  let bookIds = [];

  useEffect(() => {

    const getBookInfo = async (bookId) => {
      const response = await fetch(`https://www.googleapis.com/books/v1/volumes/${bookId}`);
      const resJson = await response.json();
      setBooks([...books, resJson]);
      Promise.resolve();
    };

    const getBookIds = async () => {
      const response = await fetch(`//localhost:3001/user/reading_list/${userID}`);
      const resJson = await response.json();
      bookIds = resJson;

      await Promise.all(
        bookIds.map(async (bookId) => {
          await getBookInfo(bookId);
        })
      );

      setIsLoading(false);
    };

    getBookIds();
  }, []);

  return (
    <ContentLayout>
      <BookDisplay>
        {!isLoading && <BookSection name={"Your Reading List"} books={books}></BookSection>}
      </BookDisplay>
    </ContentLayout>
  );
}

Getting ‘Undefined array key’ warning in editblog.php view page of CodeIgniter – how to resolve?

Can someone help to get out of this error as i have trapped in this error for a while,It’s became very much frustated for me to get out of this error.
Error is:

Update Blog

A PHP Error was encountered
Severity: Warning

Message: Undefined array key “blog_id”

Filename: blog/editblog.php

Line Number: 8

This is y editblog.php view page

load->view(‘Admin/header’); ?>

Update Blog

” method=”POST”>

Title:
“>

    <!-- by this for the form we can populate the data -->
    <div class="form-group">
        <b><label for="description" class="ms-5">Description:</label></b>
        <?php $textarea = array(
            'name'=>'desc',
            'id' =>'description',
            'value'=>set_value('desc',$blog['desc']),
            'rows'=>'5',
            'cols'=>'5',
            'class'=>'form-control mx-5'
        );
        echo form_textarea($textarea); ?>
        <p ><?= form_error('desc');?></p>

    </div>

    <br>    
    <div class="form-group">
        <b><label for="author" class="ms-5">Author:</label></b>
        <input type="text" class="form-control mx-5" name="author" value="<?= set_value('author',$blog['author']);?>" placeholder="Author of the blog">
        <p><?= form_error('author');?></p>

    </div>
    <br>

    <button class="btn btn-primary mx-5" name="submit" type="submit">Update</button>

</form>

load->view(‘Admin/footer’); ?>

This is my controller:

public function update_blog($blog_id)
{

    $this->load->model('blogmodel');

    $dataarr = $this->blogmodel->getdata($blog_id);
    $datalist = array();

    $datalist['blog'] = $dataarr;

    $this->load->library('form_validation');
    $this->form_validation->set_rules('title', 'Title of the blog', 'trim|required');
    $this->form_validation->set_rules('desc', 'description of the blog', 'trim|required');
    $this->form_validation->set_rules('author', 'author of the blog', 'trim|required');

    if ($this->form_validation->run() == false) {

        $this->load->view('Admin/blog/editblog', $datalist);
    } else {

        $data = array();
        $data['title'] = $this->input->post('title');
        $data['desc'] = $this->input->post('desc');
        $data['author'] = $this->input->post('author');
        $data['created_at'] = date('Y-m-d');
        $this->blogmodel->edit($blog_id, $data);
        $this->session->set_flashdata('success', 'Blog updated successfully');
        redirect('Blog/bloglist');
    }
}

Below is my model as blog_model.php

db->insert(‘blogs’,$formArray);
}

//fetching the all blogs records

public function getAllrecords() {
return $blogs = $this->db->get(‘blogs’)->result_array();
}

//updating the blogs

public function edit($blog_id,$data) {
$this->db->where(‘blog_id’,$blog_id);
$this->db->update(‘blogs’,$data);
}

//fetching one record with blogid

public function getdata($blog_id) {
$this->db->where(‘blog_id’,$blog_id);
$result = $this->db->get(‘blogs’)->result_array();
return $result;
}

function delete_blog($blog_id) {

$this->db->where(‘blog_id’,$blog_id);
$this->db->delete(‘blogs’);

}
}

?>

What is the difference between the two ways of declaring variables in a for in statement?

if i use for in, i always use const to declare variable

const array = ["a","b","c"]

for (const value in array) {
  console.log(value);
}

but the other way is use global scope variable using let

let value
const array = ["a","b","c"]

for (value in array) {
  console.log(value);
}

the result is same, but i don’t know which way is better. Could you explain the difference between the above two methods in terms of memory or cost?

the result is same, but i don’t know which way is better. Could you explain the difference between the above two methods in terms of memory or other cost?

Circular background for a div content

i have a list ltems using flex box i need to get a circular highlight around the dynamic content which are numbers in this case shown by

{galleyCartsDet[0].quantity}

{galleyCartsDet[1].quantity} etc is there a css approach for this

<div className='galley-carts'>
        <div class='flexCol floatRight'>
            <ul>
              <span><b>Galley Details</b></span> <br/>
              <li className='floatRight'>{galleyCartsDet[0].quantity} Full Cart</li><br/>
              <li className='floatRight'>{galleyCartsDet[1].quantity} Half Cart</li><br/>
              <li className='floatRight'>{galleyCartsDet[2].quantity} SMU</li><br/>
              <li className='floatRight'>{galleyCartsDet[3].quantity} Stowage</li>
            </ul>
        </div>
     </div>

i have tried

.carts_circle{
      border-radius: 10px;
      width: 10px;
      height: 10px;
      background: yellow; 
  }

but doesn’t seems to work

<div className='galley-carts'>
        <div class='flexCol floatRight'>
            <ul>
              <span><b>Galley Details</b></span> <br/>
<li className='floatRight'><div classname="cart_circle">{galleyCartsDet[0].quantity}</div> Full Cart</li><br/>
              <li className='floatRight'><div classname="cart_circle">{galleyCartsDet[1].quantity}</div> Half Cart</li><br/>
              <li className='floatRight'><div classname="cart_circle">{galleyCartsDet[2].quantity}</div> SMU</li><br/>
              <li className='floatRight'><div classname="cart_circle">{galleyCartsDet[3].quantity}</div> Stowage</li>
            </ul>
        </div>
     </div>

JS string / Subsrting method undefine

I am building login and registration form in NextJS and MongoDB. Users can sign up and then login. I created a profile page. On profile page I want to display user information: name, email, created date.

If I am using substring() method I am getting:

TypeError: Cannot read properties of undefined (reading 'substring')

I was trying slice() method and the same typeError: as above. Can you tell me why and how to fix it? Thank you.

const [born, setBorn] = useState(user?.user?.createdAt)
console.log(born) // 2023-05-20T04:12:43.952Z

I would like to get 2023-05-20

This is my solution:

const created = born.substring(0,10)
console.log(created) // 2023-05-20 here is all good BUT!

If I put created to the body. I am getting error as I mentioned above.

<p>Created: {created}</p> // TypeError: Cannot read...

Performance and memory impact of different approaches for passing props to a child component in React

I’m relatively new to React and currently learning about passing props to child components. I have a parent component called Counter and a child component called ChildComponent. My goal is to understand the performance and memory implications of different approaches for passing props to the child component.

Parent Component (Counter.js):

import React, { useEffect, useState } from 'react';
import ChildComponent from './CounterChild';

const Counter = () => {
  const [count, setCount] = useState(10);

  const getCount = () => {
    console.count('count me');
    return count * 2;
  };

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <button onClick={increment}>Increment</button>
      <ChildComponent count={getCount()} />
    </div>
  );
};

export default Counter;

Child Component (ChildComponent.js):

import React, { useEffect, useState } from 'react';

const ChildComponent = ({ count }) => {
  const [count1, setCount1] = useState(count);

  console.count('child count', count);

  return (
    <div>
      <h3>Child Component</h3>
      <p>Received count from parent: {count} </p>
      <p>Count From Child Logic: {count1}</p>
    </div>
  );
};

export default ChildComponent;

In Approach 1, I’m passing the prop count to ChildComponent by calling a function getCount() within the parent component and passing its return value as the prop. This function is declared inside the parent component.

In Approach 2, I’m declaring the function getCount() outside the component and directly using it inside the parent component. I’m passing the function itself as the prop.

In Approach 3, I’m passing an arrow function as the prop to ChildComponent which returns count * 2.

<ChildComponent count={()=> count * 2} />


const ChildComponent = ({ count }) => {
  const [count1, setCount1] = useState(count);
// rest of the code

In Approach 4, I’m directly passing the count state variable as the prop to ChildComponent and using the arrow functionn inside the useState.

<ChildComponent count={count} />

const ChildComponent = ({ count }) => {
 const [count1, setCount1] = useState(()=>count*2);

I want to understand the performance and memory implications of each approach.

  • Will declaring the function inside the parent component (Approach 1) cause memory allocation on each re-render?
  • What about Approach 2 where the function is declared outside the component? Will it have any performance impact?
  • Is there a recommended approach from a performance and memory standpoint ?
  • Are there any React best practices for passing the data from parent to child?

I have seen React docs supporting the lazy initialization inside the useState() hook but still people are using functions inside the jsx.