onClick handler not working with image input control

In this code, the onClick handler never gets called:

<html>
<head>
<title>Sample Web Page</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<form name=sampleform>
<div id="mainpage">
<img class="pageframe" src="images/Page 1.jpg" />
<input type="image" class="page2img" src="images/page2-link.jpg" onClick="DisplayPage2()"></input>
<input type="image" class="page3img" src="images/page3-link.jpg" onClick="DisplayPage3()"></input>
</div>
<script>
function DisplayPage2() {
    document.getElementById("mainpage").innerHTML = "<img class="pageframe" src="images/Page 2.jpg" />";
}
function DisplayPage3() {
    document.getElementById("mainpage").innerHTML = "<img class="pageframe" src="images/Page 3.jpg" />";
}
</script>
</form>
</body>
</html>

I can tell the images are getting clicked because the mouse coordinates are being displayed in the URL when I click on them, but the onClick handler is not being called. According to the documentation, onClick doesn’t work with input controls of type image. Given that, how do I get the image input controls to work?

Trying to run server on http://localhost:80/ without using SSH in GCP VM

I’m writing startup script for instance template to use in a instance group. All instances of this group are going to use this startup script to run node.js server that is in the GitHub repo that i clone to all instances.

#!/bin/bash
sudo apt-get update
sudo apt-get install -y git
sudo git config --global user.email "[email protected]"
sudo git config --global user.name "UserName"
GITHUB_TOKEN=$(gcloud secrets versions access latest --secret="token")
cd /home/user
sudo -u user git clone https://UserName:${GITHUB_TOKEN}@github.com/UserName/repo.git
cd /home/user/repo
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource.gpg.key | sudo gpg --dearmor -o /usr/share/keyrings/nodesource-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/nodesource-archive-keyring.gpg] https://deb.nodesource.com/node_14.x $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/nodesource.list
echo "deb-src [signed-by=/usr/share/keyrings/nodesource-archive-keyring.gpg] https://deb.nodesource.com/node_14.x $(lsb_release -cs) main" | sudo tee -a /etc/apt/sources.list.d/nodesource.list
sudo apt-get install -y nodejs
sleep 10
node -v
sudo apt-get install -y npm
npm -v
sleep 10
sudo node index.js

The startup script is working but except last command, i need to SSH to my VM to run last command to run the server but I don’t want to SSH my VM anytime. I want to startup script does all the job and without SSH to my vm, http://localhost:80/ should run server. How can i do this?

I am validating images uploaded by the user before uploading it to the database, but when user renames a .bat or .exe file to .png, it is allowing

`
<input
type=”file”

                          onChange={async (event) => {
                            setCinLoading(true);

                            const uploadedImage = event.target.files[0];

                            if (!uploadedImage) {
                              setCinLoading(false);
                              return;
                            }

                            const maxSizeInBytes = 10 * 1024 * 1024;
                            if (uploadedImage.size > maxSizeInBytes) {
                              errorAlert("File size exceeds 1 MB limit.");
                              setCinLoading(false);
                              return;
                            }

                            const validTypes = ["image/jpeg", "image/png", "image/jpg"];


                            if (!validTypes.includes(uploadedImage.type)) {
                             
                                  return;
                                }
                               const formData = new FormData();
                            
                            formData.append(
                              "Attachment",
                              uploadedImage,
                              uploadedImage.name
                            );

                              const response = await fetch(
                                `${process.env.REACT_APP_API_BASE_URL}/blob/api/v1/uploadmediaWithContainer`,
                                {
                                  method: "POST",
                                  headers: {
                                    Authorization: `Bearer ${accessToken}`,
                                  },
                                  body: formData,
                                }
                              );

                            

                             

                            } 
                          }}
                          name="image"
                        />

                        Choose File
                      </label>`

I am able to block pdf and zip files but not able to block .bat and .exe files.
I tried comparing it with some binary formats I found on the internet for png, jpg and jpeg separately. That did not work either.
If there is any other method to check file client side please let me know.
Also please let me know if this process is better handled client side or server side.

Axios request: xsrf token in cokkie and in header field

I’m interested why axios post request contains xsrf token in cookie as well as in header field as in image:
enter image description here

For me it seems as doubling data and I can’t find logic purpose of it. To check what happen with only XSRF token set in cookie I made request by fetch api. For this situation I’m getting 419 error from laravel (when i add XSRF field then everything is working). Why laravel cannot use XSRF from cookie and additionally needs XSRF set as field in header? There need to be logic explanation of it.

How to prevent undo/redo event which fires outside the “ element

I want to prevent redo/undo operations in my input box, but when I press cmd+z without focusing on the input box, the text in the input box will still be redo.

// stackoverflow 'Search...' input
const input = document.getElementsByName('q')[0];

input.addEventListener('beforeinput', e => {
  if (e.inputType === 'historyUndo' || e.inputType === 'historyRedo') {
    e.preventDefault();
    console.log('undo/redo prevented');
  }
}, { capture: true });

I tried to use document.addEventListener('beforeinput', ...), but I cannot distinguish whether the target of the event is my input box. What should I do to prevent it without affecting other input elements?

Mock and Spy on third party library

I have a service that uses Google calendar API- @googleapis/calendar, and I trying to test this service with spies on the Google Calendar library functions, but I don’t want to send real requests to google servers so I need to mock the google calendar library.

I succeeded to mock the library by using this code, but I don’t know how I can spy on those mocked functions.

How I can mock and spy on third-party library?

jest.mock('@googleapis/calendar', () => {
  const googleApisMock = {
    auth: {
      JWT: jest.fn().mockImplementation(),
      fromJSON: jest.fn().mockImplementation(),
    },
    calendar: {
      events: {
        insert: jest.fn().mockImplementation(() => {
          return { data: { htmlLink: 'www.test.com' } }
        }),
      },
    },
  }
  return googleApisMock
})

I tried to add spy on the insert function

const googleApisMock = {
  auth: {
    JWT: jest.fn().mockImplementation(),
    fromJSON: jest.fn().mockImplementation(),
  },
  calendar: {
    events: {
      insert: jest.fn().mockImplementation(() => {
        return { data: { htmlLink: 'www.test.com' } }
      }),
    },
  },
}
jest.mock('@googleapis/calendar', () => {
  return googleApisMock
})

describe('Service', () => {
  const insertSpy = jest.spyOn(googleApisMock.calendar.events, 'insert')
})

But I got this error

    ReferenceError: Cannot access 'googleApisMock' before initialization

      13 | }
      14 | jest.mock('@googleapis/calendar', () => {
    > 15 |   return googleApisMock
         |   ^
      16 | })

Java ignore unknown / inexistent JSON property

It’s my first Java project, I’m working on a piece of code to import Magic The Gathering cards info from Scryfall (JSON) and copy it into java objects for further processing. I found a problem I cannot get solved: the info of each Card is reachable on a specific URL (JSON). That JSON has a list of characteristics, but for some cards, a particular characteristic is not existing. The JSON does not contain that characteristic at all (i.e. it does not say empty/unknow, it’s simply missing). Then my code drops an error.
Is there a way to skip the parsing of a characteristic in case it’s not existing in the JSON?

I have read about using @JsonIgnoreProperties(ignoreUnknown = true), but I don’t know how to implement it in my code (if it would be valid solution since it seems to be for declaring a class, which I have not done).

This is my code so far. It works well unless a characteristic of the JSON is missing. Normally it’s the .image_uris (image of card) which is missing for some cards.

NOTE: apiURL is a variable that contains the URL (JSON) with the info of all the cards of a particular Set.

const axios = require('axios')

async function getCardsMTG(){
     //I have stored the URL with all cards in "apiURL"
    await axios.get(apiURL).then((card)=>{

      //card.data (axios.data) gives me the raw output of the http
      //(w/the 2nd) .data I access the matrix "data" of the http
      for (let j = 0; j < card.data.data.length; j++) {
      const itCardObj = card.data.data[j] 

      //For each iteration through "card.data.data" I visit a different card  
      //For each card, I will store all info in an object called "CardObj"
      const CardObj={
        "apiID":itCardObj.id||"", //UUID
        "language":itCardObj.lang||"", //string
        "cmc": itCardObj.cmc ||null, //int
        "coloridentity": itCardObj.color_identity||"", //array of strings
        "defense": itCardObj.defense ||"", //string
        "imageURL": itCardObj.image_uris.normal , //string
        "manacost":itCardObj.mana_cost ||"", //string
        "name": itCardObj.name ||"", //string
        "power": itCardObj.power ||"", //string
        "toughness": itCardObj.toughness ||"", //string
        "finishes": itCardObj.finishes||"", //array of strings
        "promo": itCardObj.promo, //bool
        "promotypes":itCardObj.promo_types ||"", //array of strings
        "rarity": itCardObj.rarity ||"", //string
        "setcode":itCardObj.set ||"", //string
        "text": itCardObj.printed_text||"", //string
        "type":itCardObj.type_line ||"", //string
      }
      //I inform I have captured the card
      console.log(`Fetched CARD ${CardObj.name}.`)
      //I print a table view of all card-info for checking purposes (will be deleted later on)
      console.table(CardObj)
      
      //I add the CARD-OBJECT to the end (push) of the array containing all CARDS
      cardsArray.push(CardObj)
      }
    })
}

Comparing huge data from two different sides

I have 2 different data storages which have same data stored in them. I want to check if both of them are similar. The type of data is

const object1 = {
  "name": "John",
  "age": "30",
  "height": "180 cm",
  "standard": "10th"
}

it should consider the data same even if the order of the data in the object is changed.

I have tried to generate the hash of the data and in batches and then check for their equality. But still as the input data is large it is still not a feasible way.

I want a efficient solution for the problem.

How to push to an array in javascript async loop methods? [duplicate]

I’m trying to push to paths array but it console logs an empty array . Tried Promise.all but no success .

  const paths: Path[] = [];

  Promise.all([
    allCategories[0].forEach(async ({ id }) => {
      const eachCategoryProducts = await getProductsByCategory(id);

      const eachCategoryProductsCount = eachCategoryProducts[1];
      let categoryPages: any;

      const howManyCategoryProducts = eachCategoryProductsCount / limit;
      categoryPages = Math.ceil(howManyCategoryProducts / 1) * 1;

      for (var i = 0; i < categoryPages; i++) {
        paths.push({
          params: { page: `${i + 1}`, main: "category", id },
        });
      }
    }),
  ]).then(() => {
    console.log(paths);
  });

How can I push to paths constant correctly with an async forEach loop ?

How to Pre-Load SVG’s in React Select Drop Down Menu

Good morning,

I am currently trying to have the SVG’s pre-loaded in my React Select drop down menu, so when the user clicks on the menu they instantly see the SVG’s instead of – clicking into the menu and then the SVG’s loading down the list…

I am currently mapping options to the dropdown (in my util file) as so:

export const customOptions = countries.map(country => ({
    value: country.name,
    label: (
        <div>
            <img src={require(`../images/flags/${country.svg}`)} className="flag-image" />
            <span>
                {country.name} ({country.dialingCode})
            </span>
        </div>
    ),
}));

and trying to pre-load SVGs in my container file as so:

const preloadImages = images => {
        images.forEach((image) => {
        const img = new Image();
        img.src = image;
        });
    }

    const flagImageUrls = countries.map(country => (
        `../images/flags/${country.svg}`
    ));

    useEffect(() => {
        preloadImages(flagImageUrls);
    }, []);

yet the SVG’s still only load when I click into the dropdown menu…

Does anyone have any ideas?

Much appreciated,

Jake

So I am trying to get recaptcha token of a site

So this code is in the website

 $('#main-content').submit(function (event) {
        var sk = "6Le7HZQeAAAAANyVJZBpFKiWwDstptVGJ2aGbyMC";
        event.preventDefault();

        grecaptcha.ready(function () {
            grecaptcha.execute(sk, {action: "vote"}).then(function (token) {
                $("#main-content").prepend('<input type="hidden" name="sitekey" value="' + sk + '">');
                $("#main-content").prepend('<input type="hidden" name="action" value="vote">');
                $("#main-content").prepend('<input type="hidden" name="token" value="' + token + '">');
                $("#main-content").unbind('submit').submit();
            });
        });
    });

I tried doing this in the console when on the site
enter image description here

But it gave me an error, am stuck and idk if I can debug it and so something I need help if this is possible

I also tried copying and pasting the script that the site had
enter image description here
But there was no change in the form

cut or remove the PlaneGeometry through coordinates xy

I’m new in Three.js and I want to do like this:

const myPlaneGeometry = new THREE.PlaneGeometry(
    width,
    height,
    widthSegments,
    heightSegments
);

if(myPlaneGeometry.x > 2 && myPlaneGeometry.y > 3){
    myPlaneGeometry.cut(x , y) // remove
}

Performance is important for me in more complex shapes.
Thanks for any simple idea.