Create multiple tabs under one tab?

I have multiple tabs on a website. See the image below:

enter image description here

I want to put multiple tabs under one tab so if a user hovers over a tab they can see multiple tabs below it and click on them. For example, I could hover over the home tab with my cursor and then I could see multiple other tabs like download, instructions, and troubleshoot instead of having them all separate.

Question: How to put multiple tabs under another tab?

Also, I want to have all of my tabs on one page. What I mean is if I had a page something like this:

Home Page

Hello and Welcome!

Downloads

Download a file

Instructions

This is how to use the file

I basically want the tabs to be hyperlinks. If the user hovers over Home and clicks on downloads I want it to go to the downloads section on the same page where it says “Download a file” instead of going to a different page.

Linking javascript file to html file does not work

I am starting to learn JavaScript at the moment. In a course on YouTube the Tutor gave an example for linking a .js file to a .html file. Unfortunately it is not working. Can anyone tell me why?

index.html File:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<h1>Mello</h1>
<script> "sandbox.js" </script>


</body>
</html>

sandbox.js File:

alert("HELLO");

How to send PHP post request on canvas click

I am trying to send post request to my SQL database via PHP when user clicks on canvas.
I am stuck on this for a few days and tried a lot of solutions from internet but none of the worked. There’s not much code that I have, but here’s my post request

$sendData = "send me";
$conn = new mysqli('localhost','root','','database');
    if($conn->connect_error){
        echo "$conn->connect_error";
        die("Connection Failed : ". $conn->connect_error);
    } else {
        $stmt = $conn->prepare("INSERT INTO table(data) values(?)");
        $stmt->bind_param("s", $sendData);
        $execval = $stmt->execute();
        echo $execval;
        echo "Nice";
        $stmt->close();
        $conn->close();
    }

I don’t want to do post request in JS (inside <script>) because as I am informed users can see code inside <script> and can’t see it inside <?php ?>

searching for an element inside Google Earth returns null

I am trying to copy the contents of an element. However Google Earth does not let me.
Entering document.getElementById() and trying to get anything on the site returns null. This only happens on Google Earth.
Here’s what I’m trying to do:

document.addEventListener("copy", (ev) => {
    navigator.clipboard.writeText(document.getElementById("pointer-coordinates").innerHTML.replace("/°|N|E/g", ""));
});

Even document.getElementsByClass(“body”) returns an empty array. It seems as though Google Earth is somehow blocking it. How could this be?

Encryption of files with CryptoJs and decryption in Python (AES CBC)

I’m trying to encrypt files (trying with png) in Javascript (ReactJs) and I want to be able to decrypt the files and restore their original state in Python.

I’ve tried multiple approaches but the below JS code was the only one I got working properly. With the JS code, I’m able to get back the png in its original form. However, I seem to be missing something with padding as I keep getting:

Traceback (most recent call last):
  File "***/encrypt_decrypt_using_aes.py", line 110, in <module>
    decrypted = decrypt(encData, key, iv)
  File "***/encrypt_decrypt_using_aes.py", line 103, in decrypt
    return unpad(cipher.decrypt(enc),16)
  File "/usr/local/lib/python3.9/site-packages/Crypto/Util/Padding.py", line 90, in unpad
    raise ValueError("Padding is incorrect.")
ValueError: Padding is incorrect.

I tried playing with ZeroPadding, NoPadding, PKCS7 but nothing worked.

Any ideas on what I am missing?

JS code:

    function decrypt(input) {
      var file = input;
      var reader = new FileReader();
      reader.onload = () => {
          var key = "1234567887654321";  
    
          var decrypted = CryptoJS.AES.decrypt(reader.result, key, {mode: CryptoJS.mode.CBC});               // Decryption: I: Base64 encoded string (OpenSSL-format) -> O: WordArray
          var typedArray = convertWordArrayToUint8Array(decrypted);               // Convert: WordArray -> typed array
    
          var fileDec = new Blob([typedArray]);                                   // Create blob from typed array
    
          var a = document.createElement("a");
          var url = window.URL.createObjectURL(fileDec);
          var filename = file.name.substr(0, file.name.length - 4);
          a.href = url;
          a.download = filename;
          a.click();
          window.URL.revokeObjectURL(url);
      };
      reader.readAsText(file);
    }

    function encrypt(input) {
      var file = input
      console.log("In Encrypt")
      console.log(file)
      var reader = new FileReader();
      var iv = CryptoJS.enc.Utf8.parse('53509bee-8207-11');
      reader.onload = () => {
          var key = "1234567887654321";
          var wordArray = CryptoJS.lib.WordArray.create(reader.result);           // Convert: ArrayBuffer -> WordArray
          var encrypted = CryptoJS.AES.encrypt(wordArray, key, {iv: iv, mode: CryptoJS.mode.CBC}).toString();        // Encryption: I: WordArray -> O: -> Base64 encoded string (OpenSSL-format)
  
          var fileEnc = new Blob([encrypted]);                                    // Create blob from string
  
          // var a = document.createElement("a");
          // var url = window.URL.createObjectURL(fileEnc);
          var filename = input.name + ".enc";
          console.log(filename)
          var file = new File([fileEnc], filename);
          // a.href = url;
          // a.download = filename;
          // a.click();
          // window.URL.revokeObjectURL(url);
          setFiles2State(files2State => ({
            fileList2: [...files2State.fileList2, file],
          }));
          console.log("OUT LIST")
          console.log(files2State)
      };


      reader.readAsArrayBuffer(file);

  }

Python code (Not working):

import base64 
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad,unpad

def encrypt(data,key,iv):
        data= pad(data.encode(),16)
        cipher = AES.new(key.encode('utf-8'),AES.MODE_CBC,iv)
        return base64.b64encode(cipher.encrypt(data))

def decrypt(enc,key,iv=None):
        enc = base64.b64decode(enc)
        # enc = enc.encode('utf-8')
        if iv == None:
            cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC)
        else:
            cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv)
        return unpad(cipher.decrypt(enc),16)


with open("demo_file.png.enc", "r+") as fileIn:
    encData = fileIn.read()
    key = "1234567887654321"
    iv = "53509bee-8207-11".encode('utf-8')
    decrypted = decrypt(encData, key, iv)
    

with open("demo_file.png", "wb") as fileOut:
    fileOut.write(decrypted)

Rotate the array by d elements in JavaScript [duplicate]

I have written a code for rotating a 1-D array by d elements but I just wondering if there is any shorter way to write this code?
for instance:

arr = [1,2,3,4,5,6,7] , d = 3
newArr = [4,5,6,7,1,2,3]
const arrayRotation=(arr,d)=>{
    var k = arr.slice(d) 
    var m = new Set(k)
    var diff = ([...arr].filter(x=>!m.has(x)))
    return k.concat(diff)
}

I had to use Set so I can filter the difference between 2 arrays. Is there any better way ( complexity wise) to solve this problem?

Uncaught TypeError: Cannot read properties of undefined (reading ‘Marker’)

I’m making a restaurant review website and am not sure why Marker isn’t working in this case.
The restaurant information are stored in mySQL database but it shouldn’t be related to this error.

The error is on this line

marker = new google.map.Marker({

I have multiple lines using Marker so I really don’t know what is the next step.
Tried troubleshooting but can’t seem to find anything wrong.

Can anybody lend a helping hand?

Here is my code:

function showMap(element) {
    var item = element.getAttribute("item");
    currentIndex = item;
    var locations = [restaurant_array[item].address, restaurant_array[item].lat, restaurant_array[item].lng];
    map = new google.maps.Map(document.getElementById("map"), { center: { lat: 1.8, lng: 110.9 }, zoom: 4 });
    var infowindow = new google.maps.InfoWindow();
    var marker, i;
    var markers = [];

    marker = new google.map.Marker({
        position: new google.map.LatLng(locations[1], locations[2]),
        map: map,
        icon: {
            url: "http://maps.google.com/mapfiles/ms/icons/restaurant.png"
        }
    });

    markers.push(marker);
    google.maps.event.addListener(marker, 'click', (function (marker, i) {
        return function () {
            infowindow.setContent(locations[0]);
            infowindow.open(map.marker);
        }
    })(marker, i));

    navigator.geolocation.getCurrentPosition(
        (position) => {
            const pos = {
                lat: position.coords.latitude,
                lng: position.coords.latitude
            }
            map.setCenter(pos);
            map.setZoom(15);
            marker = new google.maps.Marker({
                position: new google.map.LatLng(locations[1], locations[2]),
                map: map,
                icon: {
                    url: "http://maps.google.com/mapfiles/ms/icons/red-dot.png"
                }
            })

            markers.push(marker);
            google.maps.event.addListener(marker, 'click', (function (marker, i) {
                return function () {
                    infowindow.setContent("Your current Location");
                    infowindow.open(map, marker);
                }
            })(marker, i));
        }
    )
}

Nuxt configuration: How to user process.env or similiar in the “auth” section of nuxt.config.js

I am new to Nuxt (using Nuxt 2.15.3 + Vue2 + Javascript).

I am having some difficulties with an AUTH_PROVIDER_URL environment variable which is set to be different on my local setup, on my staging servers and in the production environment. I am 100% sure that the environment variable is set correctly in each environment.

The issue I have is in the nuxt.config.js file and under the “auth” section where I need to point to a different URL for each environment (local, staging, production).

https://auth.nuxtjs.org/schemes/oauth2#options

In my nuxt.config.js I have:

authorization: process.env.AUTH_PROVIDER_URL + '/auth',
userInfo: process.env.AUTH_PROVIDER_URL + '/userinfo',
logout: process.env.AUTH_PROVIDER_URL + '/logout',

This works fine locally on my computer when I start the application in development (npm run dev) and production mode (npm run build, npm run start). The variables(authorization, userInfo and logout) for the urls get set correctly based on the process.env.AUTH_PROVIDER_URL statements.

But when I deploy and run it to the staging and production servers process.env.AUTH_PROVIDER_URL returns UNDEFINED. It seems “process.env” doesnt find the AUTH_PROVIDER_URL environment variable in the “auth” context in the nuxt.config.js file on the staging and production servers.

Using process.env like shown below in the nuxt.config.js files work both locally, on staging servers and on the production servers and the variables gets set correct.

export default {
  auth_provider_url: process.env.AUTH_PROVIDER_URL,

  publicRuntimeConfig: {
    auth_provider_url: process.env.AUTH_PROVIDER_URL,
  },

}

How come process.env works fine in this context in the nuxt.config.js file but not under the “auth” context in the nuxt.config.js?
Is it possible for me to access these variables under the “auth” section of the nuxt.config.js file?

What is the preferred/correct way to handle(use) environment variables under the “auth” section in the nuxt.config.js file?

Puppeteer – ProtocolError: Protocol error (Page.printToPDF): Printing is not available

I get the below error when trying to print PDF with Puppetter. I’ve not been able to find much information about this error online. Does this mean this particular page just doesn’t support PDF or is there a setting in my code that could ammend this? Any help would be appreciated.

enter image description here

export const create = async (dev: boolean = true) => {
        
        const username = process.env.USERNAME;
        const password = process.env.PASSWORD;
    
        const options = dev
            ? {
                    headless: false,
                    slowMo: 25, 
              }
            : {};
    
        const browser = await Puppeteer.launch(options);
        const page = await browser.newPage();
    
        await page.goto(LOGIN_URL, {
            waitUntil: "networkidle2",
        });
    
        await page.type(USERNAME_INPUT_ID, username);
        
        const passwordInputHandle = await page.$(PASSWORD_INPUT_ID);
        await passwordInputHandle.type(password);
        await passwordInputHandle.press("Enter");
    
        await page.pdf({ path: path.join(TEMP_FOLDER, "hn.pdf"), format: "a4" });
    
        await browser.close();
    };

Heroku hits Express API more than localhost does

I have an React/Express application that is deployed on Heroku. The issue that I’m having is that when I work on localhost, a basic login API call is called once as expected by the way React component was done.

  const [searchParams, setSearchParams] = useSearchParams();
  let code = searchParams.get("code");
  const [state, setState] = useState({ data: null, loading: true });

  useEffect(() => {
    setState((state) => ({
      data: state.data,
      loading: true,
    }));
    const getData = async () => {
      console.log("helloeoeoeoeo");
      try {
        await fetch("https://statifyme.herokuapp.com/login", {
          method: "POST",
          credentials: "include",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ code }),
        })
          .then((res) => {
            if (res.ok) {
              return res.json();
            } else {
              throw new Error("Failed");
            }
          })
          .then((resJson) => {
            let data = JSON.parse(resJson.response);
            setState({ data: data, loading: false });
          });
      } catch (error) {
        console.log(error);
      }
    };
    getData();
  }, []);

  if (!state.loading) {
    return { loading: state.loading, access_token: state.data.access_token };
  }
}

In contrast, after I switch to Heroku, the login API call is called three times which ends up in an error overall (the OAuth2 authorization code expires after the first call, therefore the next two calls return a fail).

This is how the Express API call looks like:

app.post("/login", function (req, res) {
  var code = req.body.code || null;
  var state = req.body.state || null;

  console.log({ code });

  var options = {
    method: "POST",
    url: "https://accounts.spotify.com/api/token",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    form: {
      grant_type: "authorization_code",
      redirect_uri,
      code,
      client_id,
      client_secret,
    },
  };
  request.post(options, function (error, response, body) {
    if (error) throw new Error(error);
    let data = JSON.parse(body);
    console.log(data.refresh_token);
    res.cookie("refresh_token", data.refresh_token, {
      maxAge: 30 * 24 * 3600 * 1000,
    });
    // res.cookie("access_token", data.access_token, {
    //   maxAge: data.expires_in * 1000,
    // });
    res.json({
      response: response.body,
    });
  });
});

I need the /login call only once since I will work with refresh tokens afterwards, is there a way to stop Heroku from this behaviour or a method by which I can restrict the call to only one instance and block it afterwards?

Thanks.

API response not updating after x seconds reactJS

I’m trying to automatically update a table – In my testing I log the output every 10 seconds however the response stays the same from the initial component render

componentDidMount() {       
    this.interval = setInterval(this.getData, 10000);
    this.getData()        
}

getData = () => {
    axios.get(`myApiUrl`)
        .then(response => {
            this.setState({ data: response.data.entries })
            console.log(response.data.entries)
        })
        .catch(error => {
            console.log(error)
        })
}

componentWillUnmount() {
    clearInterval(this.interval)
}

If I manually try to grab the data from postman every 10 seconds, the updated changes works fine.

Why does the animate.css animation flicker after fade in

If an animation is triggered while the element’s opacity is set to 0, it fades in, but briefly flickers after completion. This occurs even when the opacity is set to 1 directly afterwards.

Here is a jsfiddle that illustrates the problem.


Just for context: I use this function to add animations classes (found on the animate.css website):

const animateCSS = (element, animation, prefix = 'animate__') =>
  // We create a Promise and return it
  new Promise((resolve, reject) => {
    const animationName = `${prefix}${animation}`;
    const node = document.querySelector(element);

    node.classList.add(`${prefix}animated`, animationName);

    // When the animation ends, we clean the classes and resolve the Promise
    function handleAnimationEnd(event) {
      event.stopPropagation();
      node.classList.remove(`${prefix}animated`, animationName);
      resolve('Animation ended');
    }

    node.addEventListener('animationend', handleAnimationEnd, {once: true});
  });


  • First I thought the flickering is caused by any animation delay.
    test1.style.setProperty('--animate-delay', '0s');

  • Since it returns a promise, I thought it should be enough to set the opacity in a .then() statement.
let test1 = document.getElementById("test1");

animateCSS("#test1", "flipInX")        // flickers
    .then(()=>{
      test1.style.opacity = 1;
    });

...

animateCSS("#test1", "flipOutX")
    .then(()=>{
      test1.style.opacity = 0;
    });

  • Setting the value immediately doesn’t work either.
let test1 = document.getElementById("test1");


animateCSS("#test1", "flipInX")
test1.style.opacity = 1;

...

animateCSS("#test1", "flipOutX")       // flickers
test1.style.opacity = 0;

What is the correct way to achieve this effect?


I use animate.css 4.1.1.