im.ask.how. add update btn help ??javascript

I ask how add button update **here

>     **
>     
>     
>     var productNameInput = document.getElementById("productName");//input 
>     var productPriceInput = document.getElementById("productPrice");//input saeed
>     var productDescInput = document.getElementById("productDesc");//input k
>     var productCategoryInput = document.getElementById("productCategory");
>     
>     var productsContainer;
>     if (localStorage.getItem("productsList") == null)
>     {
>         productsContainer = [];
>     }
>     else {
>         productsContainer = JSON.parse(localStorage.getItem('productsList'));
>         displayProducts();
>     }
>     function addProduct() {
>     
>     
>         var product = {
>     
>             name: productNameInput.value,
>             price: productPriceInput.value,
>             category: productCategoryInput.value,
>             desc: productDescInput.value
>         }
>         productsContainer.push(product);
>         localStorage.setItem("productsList", JSON.stringify(productsContainer));
>         // clearForm();
>         displayProducts();
>     
>     }
>     
>     function clearForm() {
>         productNameInput.value = "";
>         productPriceInput.value = "";
>         productCategoryInput.value = "";
>         productDescInput.value = "";
>     
>     }
>     
>     
>     
>     function displayProducts() {
>     
>         var cartoona = ``;
>         for (var i = 0; i < productsContainer.length; i++) {//3
>             cartoona += `<tr>
>             <td>${i}</td>
>             <td>${productsContainer[i].name}</td>
>             <td>${productsContainer[i].price}</td>
>             <td>${productsContainer[i].category}</td>
>             <td>${productsContainer[i].desc}</td>
>             <td> <button class="btn btn-outline-warning">update</button></td>
>             <td> <button onclick="deleteProducts(${i})" class="btn btn-outline-danger">delete</button></td>
>         </tr>`;
>         }
>         document.getElementById("tableBody").innerHTML = cartoona;
>     }
>     
>     
>     
>     
>     function searchProducts(term) {
>         var cartoona = ``;
>         for (var i = 0; i < productsContainer.length; i++) {
>     
>             if (productsContainer[i].name.toLowerCase().includes(term.toLowerCase())
> == true) {
>                 cartoona += `<tr>
>                 <td>${i}</td>
>                 <td>${productsContainer[i].name}</td>
>                 <td>${productsContainer[i].price}</td>
>                 <td>${productsContainer[i].category}</td>
>                 <td>${productsContainer[i].desc}</td>
>                 <td> <button class="btn btn-outline-warning">update</button></td>
>                 <td> <button  onclick="deleteProducts(${i})" class="btn btn-outline-danger">delete</button></td>
>             </tr>`;
>             }
>         }
>         document.getElementById("tableBody").innerHTML = cartoona;
>     }
>     
>     
>     function deleteProducts(index) {
>         productsContainer.splice(index , 1);
>         displayProducts();
>         localStorage.setItem("productsList", JSON.stringify(productsContainer));
>       }
>     
>     //    deleteProducts(5);

Is there a way to create a back button in Django that understands a tree structure?

I have a Django website that looks like this:

enter image description here

The arrows represent hyperlinks that take you to the next page. All pages except the Main Page need a “Back” button.

For Page A and Page B, the back button is pretty simple – it always takes you to the Main Page.

For Page C however, there are 2 different ways to get to it (technically 3, if you count the back button on Page D), so it’s no longer obvious where the back button should take you.

The way it should work is this:

  • If the user came from Page A to get to Page C, the Back button should take them back to Page A
  • If the use came from Page B to get to Page C, the Back button should take them back to Page B
  • If the user didn’t come from either Page A or Page B to get to Page C (they could have just entered the URL of Page C into their browser), default to having the Back button take them to Page A

This has been asked before, and none of the answers/suggestions make sense for anything other than the most basic scenario, where Page C is the end node.

The problem:

  • Using a hardcoded url for the back button of Page C won’t work, because there are 2 ways to get to it
  • Using session to keep a single variable that keeps track of whether you last visited Page A or Page B won’t work because multiple browser tabs share the same session variables. If the user has 2 tabs of our website open, navigating around will lead to confusion as both will update the same session variable
  • Using request.META.HTTP_REFERER won’t work, because the user might navigate to Page D, and then back to Page C, so the HTTP_REFERER variable will point to Page D, rather than Page A or Page B
  • Using javascript:history.go(-1) won’t work – same problem as above with HTTP_REFERER

I have come across this issue in multiple projects, and it’s always a pain to deal with. The solution is always hacky. Is this a problem that inherently can’t be handled by Django, and must be handled by something like JavaScript’s sessionStorage?

In Javascript, can a closure share scope with a function return value?

JS n00b here, I’m trying to understand this unexplained code from Eloquent Javascript :

function trackKeys(keys) {
  let down = Object.create(null);
  function track(event) {
    if (keys.includes(event.key)) {
      down[event.key] = event.type == "keydown";
      event.preventDefault();
    }
  }
  window.addEventListener("keydown", track);
  window.addEventListener("keyup", track);
  return down;
}

var arrowKeys =
  trackKeys(["ArrowLeft", "ArrowRight", "ArrowUp"]);

I think I understand how the inner function track will maintain a reference to down and keys because it is a closure, but I’m lost at return down;

Will that return value be a reference to the exact same down the callbacks are accessing? I don’t understand; I thought local variables could only be accessed by inner functions?

Follow-up: what if down were a primitive data type and not an object, would this still work?

Thanks!

error – TypeError: Cannot read properties of undefined (reading ‘drawer’)

I am trying to copy the exact code from Material UI Drawer to add on my own website. The link is https://mui.com/components/drawers/

  import * as React from 'react';
import Box from '@mui/material/Box';
import Drawer from '@mui/material/Drawer';
import Button from '@mui/material/Button';
import List from '@mui/material/List';
import Divider from '@mui/material/Divider';
import ListItem from '@mui/material/ListItem';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import InboxIcon from '@mui/icons-material/MoveToInbox';
import MailIcon from '@mui/icons-material/Mail';

export default function TemporaryDrawer() {
  const [state, setState] = React.useState({
    top: false,
    left: false,
    bottom: false,
    right: false,
  });

  const toggleDrawer = (anchor, open) => (event) => {
    if (event.type === 'keydown' && (event.key === 'Tab' || event.key === 'Shift')) {
      return;
    }

    setState({ ...state, [anchor]: open });
  };

  const list = (anchor) => (
    <Box
      sx={{ width: anchor === 'top' || anchor === 'bottom' ? 'auto' : 250 }}
      role="presentation"
      onClick={toggleDrawer(anchor, false)}
      onKeyDown={toggleDrawer(anchor, false)}
    >
      <List>
        {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (
          <ListItem button key={text}>
            <ListItemIcon>
              {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
            </ListItemIcon>
            <ListItemText primary={text} />
          </ListItem>
        ))}
      </List>
      <Divider />
      <List>
        {['All mail', 'Trash', 'Spam'].map((text, index) => (
          <ListItem button key={text}>
            <ListItemIcon>
              {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
            </ListItemIcon>
            <ListItemText primary={text} />
          </ListItem>
        ))}
      </List>
    </Box>
  );

  return (
    <div>
      {['left', 'right', 'top', 'bottom'].map((anchor) => (
        <React.Fragment key={anchor}>
          <Button onClick={toggleDrawer(anchor, true)}>{anchor}</Button>
          <Drawer
            anchor={anchor}
            open={state[anchor]}
            onClose={toggleDrawer(anchor, false)}
          >
            {list(anchor)}
          </Drawer>
        </React.Fragment>
      ))}
    </div>
  );
}

I install both @mui/material and @mui/icons-material but it still shows this error.

Error: TypeError: Cannot read properties of undefined (reading ‘drawer’)

Any help will be appreciated.

The command `npx create-react-app my-app` does not create an application file

I want to install react-create-app. I’m using the command: npx create-react-app my-app. I can see the following information in the console:

Installing packages. This might take a couple of minutes. Installing react, react-dom, and react-scripts with cra-template ... added 1374 packages in 4m 163 packages are looking for funding run npm fund for details

and nothing is happening.

node and npm are the newest

In the folder I just created, I can only see node-modules, package, package-lock. I don’t have a file src. How to solve this problem?

How can I make JavaScript calls to scrape data from a website?

I’ll try to explain everything the way I understand it as clearly as possible, so correct me if I’m confused with something.

I was trying to scrape the users from a member list on a website, I used Python and the first thing I did was making a post request to the Request URL with the required headers so I get a response that contains the data I need but this didn’t work, so I tried to find out the reason.

From what I understand now the website uses AJAX to make XHR and JavaScript calls which respond with the content (users).

The JS code is stored on a static website from what Chrome’s developer tool request initiators
tell me (Here is an image for reference), which responds with the HTML that contains the users

The idea is to create a script that runs this static JS script that’s stored online and fetch the data about the users from it. (Image for clarification)

How do I achieve this, I’m using python. What libraries do I need etc.? Any help/advice is greatly appreciated!

HTML: use one nav bar for multiple pages

below i wanted to create one nav bar for multiple html pages for ease of use .. using JS it gives error ..it seems weird to me,also i wanted to use same method for footer as well

Access to XMLHttpRequest at 'file:///C:/Users/saad/Desktop/myhome-real-estate-free-web-template/navbar.html' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https

fetch('navbar.html')
.then(res => res.text())
.then(text => {
    let oldelem = document.querySelector("script#replace_with_navbar");
    let newelem = document.createElement("div");
    newelem.innerHTML = text;
    oldelem.parentNode.replaceChild(newelem,oldelem);
})
<body>
    
    <div id="wrapper" class="home-page">

        <header>
            <div id="nav-placeholder">

            </div>
            
            <script>
            $(function(){
              $("#nav-placeholder").load("navbar.html");
            });
            </script>
        
        </header>
    
    </body>

and my navbar.html code below:

<!DOCTYPE html>
<html lang="en">
<div class="navbar navbar-default navbar-static-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="index.html"></a>
        </div>
        <div class="navbar-collapse collapse ">
            <ul class="nav navbar-nav">
                <li class="active"><a href="index.html">Home</a></li> 
                 <li class="dropdown">
                <a href="#" data-toggle="dropdown" class="dropdown-toggle">About Us <b class="caret"></b></a>
                <ul class="dropdown-menu">
                    <li><a href="about.html">Company</a></li>
                    <li><a href="#">Our Team</a></li>
                    <li><a href="#">News</a></li> 
                    <li><a href="#">Investors</a></li>
                </ul>
            </li> 
                <li><a href="services.html">Services</a></li>
                <li><a href="projects.html">Projects</a></li>
                <li><a href="pricing.html">Pricing</a></li>
                <li><a href="contact.html">Contact</a></li>
            </ul>
        </div>
    </div>
</div>

</html>

is there a way to solve this? cux i can’t figure out the problem
thanks in advance

JS or jQuery vertical carousel with mouse wheel event

I’m trying to do some scrolling in JS. What i want is when i spin my mouse wheel my page should scroll down by one element. Elements are full screen, so basicaly i want vertical carousel.
My div elements have 100vh so when i resize window it should scroll by the height of the window.

document.addEventListener("wheel", function(event){
    if(event.deltaY<0)
    {
        window.scrollBy(0, -window.innerHeight);
    }
    if(event.deltaY>0)
    {
        window.scrollBy(0, window.innerHeight);
    }
});

I found this code on internet. When I scroll it flickers, it moves window as I want for a milisecond and gets it back where default scroll position is (20px or w/e the number is).
Thanks in advance!

Having problems solving Leetcode Question Max Area of Islands

Below is my code to find the max area of islands but for some reason it kept failing this test case:
[[1],[1]]

Im not entirely sure whats wrong and Ive been thinking to no avail of a possible solution using this method. It was thinking a possible reason why this code is not working properly is because of the synchronous nature of JS when the dfs() is called in the for loop at the bottom.

var maxAreaOfIsland = function(grid) {
        let maxArea = 0
    let currArea = 0

    let dirs = [
        [0,1],
        [1,0],
        [-1,0],
        [0,-1]
    ]

    function dfs(r,c){
        if(grid[r][c] === 0) return
        
        currArea++
        grid[r][c] = 0
        for(let [row,col] of dirs){
            let nr = r+row
            let nc = c+col
            if(nr<0 || nc< 0|| nr >= grid.length|| nc >= grid[0].length){
                return
            }
            dfs(nr,nc)
        }
    }

    for(let i = 0; i < grid.length; i++){
        for(let j = 0; j< grid[0].length; j++){
            if(grid[i][j] === 1){
                
                currArea = 0
                dfs(i,j)
                if(currArea > maxArea){
                    maxArea = currArea
                }
            }
        }
    }

    return maxArea
};

console.log(maxAreaOfIsland( [[1],[1]] ))

getImageData() does not return correct RGB values

I’ve written a website that extracts pixel colors from an image. I do this by using getImageData on a canvas holding the image. However, I do not manage to get the correct values for this sample image.

When using Pillow to extract, for example, the first pixel color (x=0, y=0) it returns (49, 98, 173, 255) for the RGBA color space.

from PIL import Image 
im = Image.open('image.png').convert('RGBA')
pix = im.load()
print(pix[0, 0])

Also Java gives me the same results:

BufferedImage bufferedImage = ImageIO.read(new File("image.png"));
        int rawRGB = bufferedImage.getRGB(0, 0);
        Color color = new Color(rawRGB);

However when I use an HTML canvas I get the following values by getImageData: (26, 99, 179, 255).

        let image = new Image();
        const reader = new FileReader();

        image.addEventListener('load', function () {
            let canvas = document.createElement('canvas');
            let ctx = canvas.getContext("2d");
            canvas.width = this.width;
            canvas.height = this.height;
            ctx.drawImage(this, 0, 0);
            let data = ctx.getImageData(0, 0, 1, 1).data;
            document.getElementById('imageData').innerHTML = data;
        });

        image.addEventListener('load', function () {
            let canvas = document.createElement('canvas');
            let gl = canvas.getContext("webgl2");
            gl.activeTexture(gl.TEXTURE0);
            let texture = gl.createTexture();
            gl.bindTexture(gl.TEXTURE_2D, texture);
            const framebuffer = gl.createFramebuffer();
            gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
            gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this);
            gl.drawBuffers([gl.COLOR_ATTACHMENT0]);
            let data = new Uint8Array(1 * 1 * 4);
            gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, data);
            document.getElementById('webGl').innerHTML = data;
        });

        reader.addEventListener('load', (event) => {
            image.src = event.target.result;
        });

        var fileToRead = document.getElementById("yourFile");

        fileToRead.addEventListener("change", function (event) {
            var files = fileToRead.files;
            if (files.length) {
                reader.readAsDataURL(event.target.files[0]);
            }
        }, false);
<pre>Expected:  49,98,173,255<br>
ImageData: <span id="imageData"></span><br>
WebGL:     <span id="webGl"></span><br></pre>
<input type="file" id="yourFile" name="file">

I do not understand why this happens or how the browser comes up with these values. I’ve tried both Chrome and Firefox and they displayed the same incorrect values. I’ve read about premultiplied alphas but I don’t how this should affect my results as the picture does not make use of the alpha channel. Any help would be appreciated!

Next js ; static generation and SWR in single page

I m building a blog website in next js , the API for the blog is from some headless CMS.

In a page i want to do the following

  1. List some blogs.
  2. Set of buttons available, based on each button click different set of blogs are loading (should replace the blogs in #1).

Since SEO is needed I m pretty confused to use which approach should i choose.

What i thinking is i can use generate the initial list with
getStaticProps (Static Generation), and after loading i want to replace the blogs based on user action (button click).

But i m confused is it possible to use static generation and SWR in single page.

Can somebody give advise on my problem?.

Thanks in advance

Is it better to have data arranged with an array of objects or an object of objects for use in React? 🎅

I am structuring data to be used later to hydrate a table in react, where the data will change dynamically through WebSocket calls. Currently I have an array of objects:

result1
Array(2) [Object, Object]
    [[Prototype]]: Array(0)
    length: 2
    0: Object {name: "pizza", poolsCount: 2, pools: Array(2)}
    1: Object {name: "apple", poolsCount: 3, pools: Array(3)}
    __proto__: Array(0)

I can convert the arrays to objects using result = Object.assign({}, result1);:

result
Object {0: Object, 1: Object}
    [[Prototype]]: Object
    0: Object {name: "pizza", poolsCount: 2, pools: Array(2)}
    1: Object {name: "apple", poolsCount: 3, pools: Array(3)}
    __proto__: Object

With that data, and once I get the React UI setup, I will want to each pools object’s properties to be displayed in its own column:

enter image description here

Which is more convenient and recommended for use in my react application?

Regex match from digit to digit?

Is there a way to regex from digit to digit?
I have this tracklist:
“01. Intro 02. Waage 03. Hyänen (feat. Samra) 04. Ich will es bar (feat. Haftbefehl) 05. Am Boden bleiben (feat. Casper & Montez) 06. Panzerglas (feat. Face) 07. Sobald Du gehst 08. 90’s (feat. Olson) 09. Erzähl‘ mir nix (feat. Nio) 10. Dope & 40s 11. Lila (feat. Bosca) 12. Wo ich wohn‘ 13. Bahnen 14. 200K”

which I tried to split with /dd([^d]*)/g into objects. But I got as a result:

0: ""
1: ". Intro "
2: ""
3: ". Waage "
4: ""
5: ". Hyänen (feat. Samra) "
6: ""
7: ". Ich will es bar (feat. Haftbefehl) "
8: ""
9: ". Am Boden bleiben (feat. Casper & Montez) "
10: ""
11: ". Panzerglas (feat. Face) "
12: ""
13: ". Sobald Du gehst "
14: ""
15: ". "
16: ""
17: "’s (feat. Olson) "
18: ""
19: ". Erzähl‘ mir nix (feat. Nio) "
20: ""
21: ". Dope & "
22: ""
23: "s "
24: ""
25: ". Lila (feat. Bosca) "
26: ""
27: ". Wo ich wohn‘ "
28: ""
29: ". Bahnen "
30: ""
31: ". "
32: ""
33: ""
34: "0K"

How do I include the numbers 01,02,03… and what are the possibilites for cases like track 14 where the title track is “200k”