Why isn’t my JavaScript effects showing on web browser upon loading?

Hello I need help with fixing my personal portfolio site. It’s been a while since I used JavaScript and I am also trying to familiarize myself with some popular js libraries. I’m using the anime.js library to move the letters in the span tag nested in the h2 tag from my index.html file. Here is my code:

main.js

import anime from 'animejs/lib/anime.es.js';

const anime = require('animejs');

//Effect 14
// Wrap every letter in a span
var textWrapper = document.querySelector('.hello .letters');
textWrapper.innerHTML = textWrapper.textContent.replace(/S/g, "<span class='letter'>$&</span>");

anime.timeline({loop: false})
  .add({
    targets: '.hello .line',
    scaleX: [0,1],
    opacity: [0.5,1],
    easing: "easeInOutExpo",
    duration: 900
  }).add({
    targets: '.hello .letter',
    opacity: [0,1],
    translateX: [40,0],
    translateZ: 0,
    scaleX: [0.3, 1],
    easing: "easeOutExpo",
    duration: 800,
    offset: '-=600',
    delay: (el, i) => 150 + 25 * i
  }).add({
    targets: '.hello',
    opacity: 0,
    duration: 1000,
    easing: "easeOutExpo",
    delay: 1000
  });

styles.css

/*TODO: Make navbar sticky as you scroll down*/
.header{
    /*background-color: #F4C2C2; #FF8976; #FFCBA4;*/
    position: relative;
    width: 100%;
    justify-content: space-between;
    align-items: center;
    display: flex;
    padding: 0 25px;
    transition: 0.3s;
}

.logo a{
    display: block;
}

.navigation{
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.menu{
    display: flex;
    justify-content: center;
    flex-direction: row;
    align-items: center;
    z-index: 1;
    transition: 0.5s;
}

.menu li{
    list-style-type: none!important;
}

.menu li a{
    display: block;
}

.menu li a:hover{
    color: red!important;
    box-shadow: 0 -5px 0px #F4C2C2 inset,
    500px 0 0 rgba(255,255,255,0.03) inset;
    padding: 35px 25px 45px 25px;
}

a:link, a:hover, a:visited{
    text-decoration:none!important;
}

a:link{
    color: white;
    width: 100px;
    height: 100px;
    margin-top: 30px; 
    display: inline-block;
}

a:visited {
    color: white!important;
}

.hamburger{
    position: relative;
    width: 30px;
    height: 4px;
    background: #fff;
    border-radius: 10px;
    cursor: pointer;
    z-index: 2;
    transition: 0.3s;
}

.hamburger:before,
.hamburger:after{
    content: "";
    position: absolute;
    height: 4px;
    right: 0;
    background: #fff;
    border-radius: 10px;
    transition: 0.3s;
}

.hamburger:before{
    top: -10px;
    width: 20px;
}

.hamburger:after{
    top: 10px;
    width: 20px;
}

.toggle-menu {
    position: absolute;
    width: 30px;
    height: 100%;
    z-index: 3;
    cursor: pointer;
    opacity: 0;
}

.hamburger, 
.toggle-menu {
    display: none;
}

.navigation input:checked ~ .hamburger{
    background: transparent;
}

.navigation input:checked ~ .hamburger:before {
    top: 0;
    transform: translateY(6px)
    rotateZ(-45deg);
    width: 30px;
}

.navigation input:checked ~ .hamburger:after {
    top: 0;
    transform: translateY(6px)
    rotateZ(45deg);
    width: 30px;
}

.navigation input:checked ~ .menu {
    right: 0;
    box-shadow: -20px 0 40px rgba(0,0,0,0.3);
}

@media screen and (max-width: 992px) {
    .hamburger,
    .toggle-menu {
        display: block;
    }
    .header {
        padding: 10px 20px;
    }
    .menu{
        justify-content: start;
        flex-direction: column;
        align-items: center;
        position: fixed;
        top: 0;
        right: 0;
        width: ;
        height: ;
        padding-top: ;
    }
    .menu li {
        width: 100%;
    }
    .menu li a{
        padding: 12px 0;
        font-size: 20px;
    }

    body {
        /*Chrome, Safari4+*/
        background: -webkit-gradient(linear, color-stop(5%,#FF8976), color-stop(#F4C2C2), color-stop(#C77398), color-stop(80%,purple), color-stop(90%,#1e1021));
        /*W3C*/
        background:linear-gradient(#FF8976 5%, #F4C2C2,#C77398, purple 80%,#1e1021 90%);
        /*Chrom10+, Safari5.1+*/
        background: -webkit-linear-gradient(#FF8976 5%, #F4C2C2,#C77398, purple 80%,#1e1021 90%); 
        /*FF3.6+*/
        background: -moz-linear-gradient(#FF8976 5%, #F4C2C2,#C77398, purple 80%,#1e1021 90%);
        height: 100vh;
    }
}

img {
    margin-left: auto;
    margin-right: auto;
    margin-top: 100px;
    width: 350px;
    height: 350px;
    border: 2px solid #0e0810;
    display: block;
}

.hello {
    color: purple;
    margin-top: 50px;
    font-weight: 500;
    font-size: 2.5em;
}

.hello .text-wrapper {
    position: relative;
    display: inline-block;
    padding-top: 0.1em;
    padding-right: 0.05em;
    padding-bottom: 0.15em;
}

/*TODO: Fix span line*/
.hello .line {
    opacity: 0;
    position: absolute;
    left: 0;
    height: 5px;
    width: 100%;
    background-color: #ff0000;
    transform-origin: 100% 100%;
    bottom: 0;
}
  
.hello .letter {
    display: inline-block;
    line-height: 1em;
}

index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        <title>Cecelia</title>
        <link rel="stylesheet" href="style.css">
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
        <script src="anime.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script>
        <!-- fav icon -->
        <link rel="stylesheet" href="favicon.css">
    </head>
    <body>
        <div class="container">
            <div class="row">
                <header class="header">
                    <!--Logo/SVG-->
                    <div class="logo">
                        <a></a>
                    </div>
                    <!--Navigation begins-->
                    <div class="navigation">
                        <input type="checkbox" class="toggle-menu">
                        <div class="hamburger"></div>
                        <ul class="menu">
                            <li class="nav-item">
                                <a class="nav-link disabled" href="/Users/cecelia/Documents/CeceliaPortfolio/index.html">Home</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link active" href="/Users/cecelia/Documents/CeceliaPortfolio/resume.html">Résumé</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link active" href="/Users/cecelia/Documents/CeceliaPortfolio/projects.html">Projects</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link active" href="/Users/cecelia/Documents/CeceliaPortfolio/contact.html">Contact</a>
                            </li>
                        </ul>
                    </div>
                </header>
            </div>
            <!--Adjusted padding of bootstrap row, distance of content from navigation-->
            <div class="row" style="padding-top: 50px;">
                <div class="col-12 col-lg-6">
                        <!--Adjusted padding of top of col so that it's height is bit above my headshot--> 
                        <div style="padding-top: 60px;">
                            <h2 class="hello">
                                <span class="text-wrapper">
                                    <span class="letters">Nice to meet you, I'm Cecelia!</span>
                                    <span class="line"></span>
                                </span>
                            </h2>

Can anyone please tell me what I can do to have the effects show upon the page loading on web browser? I referenced from https://tobiasahlin.com/moving-letters/ if it helps. Also if you have any other suggestions for parts of my code that I’m clearly struggling with, all is welcomed.

Incorrect Notification Badge Count on Android Devices with Expo React Native

Affected Versions:

Expo SDK: 50
React Native: 0.73
react-native-onesignal: 5.0.3
onesignal-expo-plugin: 2.0.2

Description:

Currently, there’s an issue with the OneSignal integration in Expo React Native applications specifically on Android devices. The problem arises when a notification is received on the device. Instead of accurately reflecting the number of notifications in the badge count, it displays a count that is one higher than the actual number of notifications present in the notification center.

Steps to Reproduce:

Set up an Expo React Native application.
Integrate OneSignal for push notifications.
Send a notification to the device.
Observe the badge count displayed on the app icon.

Expected Behavior:

The badge count on the app icon should accurately reflect the number of notifications present in the notification center. For example, if there is one notification in the notification center, the badge count should display as 1.

Current Behavior:

Upon receiving a single notification, the badge count on the app icon displays as 2 instead of 1.

Additional Information:

This issue is specific to Android devices.
The problem persists even after updating to the latest versions of Expo SDK, React Native, react-native-onesignal, and onesignal-expo-plugin.
This issue is not observed on iOS devices.

Note:

This issue was encountered in a production environment and significantly impacts user experience. Any assistance or guidance on resolving this issue would be greatly appreciated.

Checkbox symbol for a to do list in Javascript

I’m trying to create a to-do list application in JavaScript. Using HTML and CSS, I’ve created a checkmark button. The problem is that the checkmark button doesn’t display when adding a new task, but the task is added. Can someone explain to me what’s wrong and how it should be done?

I can not understand if my problem is from HTML or CSS or JavaScript.

Code Snippet

let userinput = [];

function task() {
  const inputText = document.getElementById("inputbutton").value;

  // Check if inputText already exists in userinput array
  if (userinput.includes(inputText)) {
    alert("Already added");
    return; // Exit function early if inputText already exists
  }


  userinput.push(inputText);

  let tasklist = document.getElementById("tasklist");
  let listItem = document.createElement("li");
  listItem.textContent = inputText;
  tasklist.appendChild(listItem);

}

/*
I also tried this:
   let checkmarks = document.querySelectorAll('.container .checkmark');
    checkmarks.forEach(checkmark => {
        checkmark.style.display = 'block';
    });
*/
* {
  box-sizing: border-box;
  margin: 0;
}

#inputbutton {
  color: hsl(210deg 100% 44%);
  ;
  border: 2px solid hsl(210deg 100% 44%);
  ;
  border-radius: 10px;
  padding: 10px 25px;
  background: transparent;
  max-width: 190px;
  margin-top: 4em;
  margin-left: 42em;
  display: inline-flex;
  position: relative;
}

ul li {
  list-style: none;
  font-size: 17px;
  padding: 12px 8px 50px;
  user-select: none;
  cursor: pointer;
}

.input:active {
  box-shadow: 2px 2px 15px #8707ff inset;
}

button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 40px;
  position: relative;
  padding: 0px 11px;
  font-size: 18px;
  text-transform: uppercase;
  border: 0;
  background-color: hsl(210deg 100% 44%);
  border-radius: 12px;
  overflow: hidden;
  transition: 31ms cubic-bezier(.5, .7, .4, 1);
}

button:before {
  content: attr(alt);
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  inset: 0;
  font-size: 15px;
  font-weight: bold;
  color: white;
  letter-spacing: 4px;
  opacity: 1;
}

button:active {
  box-shadow: none;
  transform: translateY(7px);
  transition: 35ms cubic-bezier(.5, .7, .4, 1);
}

button:hover:before {
  transition: all .0s;
  transform: translateY(100%);
  opacity: 0;
}

button i {
  color: white;
  font-size: 15px;
  font-weight: bold;
  letter-spacing: 4px;
  font-style: normal;
  transition: all 2s ease;
  transform: translateY(-20px);
  opacity: 0;
}

button:hover i {
  transition: all .2s ease;
  transform: translateY(0px);
  opacity: 1;
}

button:hover i:nth-child(1) {
  transition-delay: 0.045s;
}

button:hover i:nth-child(2) {
  transition-delay: calc(0.045s * 3);
}

button:hover i:nth-child(3) {
  transition-delay: calc(0.045s * 4);
}

button:hover i:nth-child(4) {
  transition-delay: calc(0.045s * 5);
}

button:hover i:nth-child(6) {
  transition-delay: calc(0.045s * 6);
}

button:hover i:nth-child(7) {
  transition-delay: calc(0.045s * 7);
}

button:hover i:nth-child(8) {
  transition-delay: calc(0.045s * 8);
}

button:hover i:nth-child(9) {
  transition-delay: calc(0.045s * 9);
}

button:hover i:nth-child(10) {
  transition-delay: calc(0.045s * 10);
}


/* Hide the default checkbox */

.container input {
  display: none;
}

.container {
  display: block;
  position: relative;
  cursor: pointer;
  font-size: 20px;
  user-select: none;
  -webkit-tap-highlight-color: transparent;
}


/* Create a custom checkbox */

.checkmark {
  position: relative;
  top: 0;
  left: 0;
  height: 1.3em;
  width: 1.3em;
  background-color: #2196F300;
  border-radius: 0.25em;
  transition: all 0.25s;
}


/* When the checkbox is checked, add a blue background */

.container input:checked~.checkmark {
  background-color: #2196F3;
}


/* Create the checkmark/indicator (hidden when not checked) */

.checkmark:after {
  content: "";
  position: absolute;
  transform: rotate(0deg);
  border: 0.1em solid black;
  left: 0;
  top: 0;
  width: 1.05em;
  height: 1.05em;
  border-radius: 0.25em;
  transition: all 0.25s, border-width 0.1s;
}


/* Show the checkmark when checked */

.container input:checked~.checkmark:after {
  left: 0.45em;
  top: 0.25em;
  width: 0.25em;
  height: 0.5em;
  border-color: #fff0 white white #fff0;
  border-width: 0 0.15em 0.15em 0;
  border-radius: 0em;
  transform: rotate(45deg);
}
<input tyoe="text" id="inputbutton"></input>
<button class="addtask" onclick="task()" alt="Add task">
        <i>A</i>
        <i>d</i>
        <i>d</i>
        <i>&nbsp;</i>
        <i>t</i>
        <i>a</i>
        <i>s</i>
        <i>k</i>
      </button>
<label class="container">
        <input type="checkbox"/>
        <div class="checkmark"></div>
      </label>
<ul id="tasklist"></ul>

Where can I run Nodejs code instead of on my local computer?

So I have the following skeleton code written in nodejs:

            function getData(){
                //some code to retrieve data
            }

            function processData(){
                let dataList = getData();
            
               dataList.forEach(e => {
                //perform some computation
               });
            }

            processData();    //processData is a very resource intense function call.

My question here is, is there a place where I can deploy this code to run instead of my local computer? This code may take hours if not days to complete.

How to store fetch headers in javacript from website I don’t own?

I am trying to save headers when a specific fetch is completed on a website I do not own. This is so I can complete a new fetch that requires variables inside the headers that are specific to different users. I found this:

window.fetch = new Proxy(window.fetch, {
    apply(actualFetch, that, args) {
        // Forward function call to the original fetch
        const result = Reflect.apply(actualFetch, that, args);

        // Do whatever you want with the resulting Promise
        result.then((response) => {
            console.log("fetch completed!", args, response);
        });

        return result;
    }
});

But it only seems to work in the browser console. I’m trying to get it working in a chrome extension.

Here’s what I’ve added to the code. Not none of the logs appear in the console. My version works in the browser console as well just not when used in an extension I’m writing.

window.fetch = new Proxy(window.fetch, {
            apply(actualFetch, that, args) {
                console.log('fetchingworking')
                // Forward function call to the original fetch
                const result = Reflect.apply(actualFetch, that, args);

                // Do whatever you want with the resulting Promise
                result.then((response) => {
                    if (args[0].includes('page%22%3A') && args[0].includes('nrte') == false) {
                        console.log('fetchinfoworking')
                        fetchinfo = {
                            urlstart: args[0].split('page%22%3A')[0] + 'page%22%3A',
                            urlend: '%7D%7D&extensions' + args[0].split('%7D%7D&extensions')[1],
                            fetchhead: args[1].headers,
                        }
                    }
                });

                return result;
            }
        })

Aligned Divs not aligning properly

Im building a 3D render for JavaScript and the first feature I need is a X , Y mouse display. This display is a paragraph tag which is in a div which should be aligned. right next to each other.

I’ve tried changing the div width, margin, padding, float, align but it just doesn’t seem to work.

let renArea = document.querySelector("#render");
let cc = renArea.getContext("2d"); //cc for canvas contenxt.

//Pre-Display
document.querySelector("#postion-display").innerHTML = "Put mouse on canvas.";

//Get mouse (X, Y) and siplay it for user refrence. 
function getMousePosition(canvas, event) {
    let rect = canvas.getBoundingClientRect();
    let x = event.clientX - rect.left;
    let y = event.clientY - rect.top;
    document.querySelector("#postion-display").innerHTML = "Coordinate x: " + Math.round(x) + " Coordinate y: " + Math.round(y);
}

renArea.addEventListener("mousemove", function (e) {
    getMousePosition(renArea, e);
}); 


cc.moveTo(0, 0);
cc.lineTo(200, 100);
cc.stroke();
html, body {
    margin: 0px;
    margin-top: 5vh;
}

.wrapper {
    margin: 0px;
}

.header {
    position: fixed;
    padding: 1px;
    width: 100%;
    top: 0;    
    padding-left: 12px;
    background: lightcoral;
}

.render-area {
    margin: 0px;
}

canvas {
    border: 2px solid black;
    float: right;
    margin-right: 10px;
}
<!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Render | Js</title>

        <link rel="stylesheet" href="media/global.css">
    </head>
    <body>
        <div class="wrapper">
            <div class="header">
                <h3>Render | Js</h3>
            </div>

            <div class="editor" style="width: 50%; float: left;">
                <p id="postion-display"></p>
            </div>
            <div class="render-area" style="float: left; width: 50%;">
                <canvas width="500" height="500" id="render"></canvas>
            </div>
        </div>

        <script src="./src/render.js"></script>
    </body>
</html>

I am coding a command that once ran would allow me to check the servers a user is in, however I am getting an error

const {
  InteractionType,
  GatewayIntentBits,
  EmbedBuilder,
} = require("discord.js");
const { Client } = require("discord.js");
const { SlashCommandBuilder } = require("@discordjs/builders");
const { REST } = require("@discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const { token, clientId, guildId } = require("../../config.json");

const client = new Client({
  intents: Object.keys(GatewayIntentBits).map((a) => {
    return GatewayIntentBits[a];
  }),
});

const commandData = new SlashCommandBuilder()
  .setName("checkuserguilds")
  .setDescription("Check the guilds a user is in")
  .addUserOption((option) =>
    option
      .setName("user")
      .setDescription("The user to check the guilds for")
      .setRequired(true)
  );

const allowedRoleName = "DOW Directors"; // Replace 'YOUR_ALLOWED_ROLE_NAME' with the name of the role allowed to run the command

client.once("ready", async () => {
  console.log(`Logged in as ${client.user.tag}!`);

  const rest = new REST({ version: "9" }).setToken(token);

  try {
    console.log("Started refreshing application (/) commands.");

    await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
      body: [commandData.toJSON()],
    });

    console.log("Successfully reloaded application (/) commands.");
  } catch (error) {
    console.error(error);
  }
});

const execute = async (interaction) => {
  if (interaction.type === InteractionType.ApplicationCommand) {
    if (interaction.commandName === "checkuserguilds") {
      if (!checkPermission(interaction.member)) {
        return interaction.reply({
          content: "You do not have permission to run this command.",
          ephemeral: true,
        });
      }

      const user = interaction.options.getUser("user");
      if (!user) {
        return interaction.reply({
          content: "Please specify a user.",
          ephemeral: true,
        });
      }

      try {
        const guilds = await getUserGuilds(user.id);
        const embed = new EmbedBuilder()
          .setColor("#0099ff")
          .setTitle("User Guilds")
          .setDescription(
            `User ${user.tag} is in the following guilds:n${guilds.join("n")}`
          );
        await interaction.reply({ embeds:  });
      } catch (error) {
        console.error("Error fetching user guilds:", error);
        await interaction.reply("Error fetching user guilds.");
      }
    }
  }
};

function checkPermission(member) {
  return member.roles.cache.some((role) => role.name === allowedRoleName);
}

async function getUserGuilds(userId) {
  try {
    const user = await client.users.fetch(userId);
    const userGuilds = client.guilds.cache.filter((guild) =>
      guild.members.cache.has(user.id)
    );
    return userGuilds.map((guild) => guild.name);
  } catch (error) {
    console.error("Error fetching user guilds:", error);
    return [];
  }
}

module.exports = {
  data: commandData,
  execute,
};

I have tried to reset my tokens, and I am still receiving the “Error fetching user guilds: Expected token to be set for this request, but none was present.” I have configured the code to where I am not just handing out the token in all the commands. so it is centrally located in the config.json file.

Ethereum: how to generate a valid address from the public key?

I am using this code to generate a private key, public key and address, acording to this:

The public key is generated from the private key using the Elliptic Curve Digital Signature Algorithm. You get a public address for your account by taking the last 20 bytes of the Keccak-256 hash of the public key and adding 0x to the beginning.

const { secp256k1 } = require("ethereum-cryptography/secp256k1");
const { keccak256 } = require("ethereum-cryptography/keccak");
const { toHex } = require("ethereum-cryptography/utils");

const privateKey = secp256k1.utils.randomPrivateKey();
console.log('private key :  ', toHex(privateKey));

const publicKey = secp256k1.getPublicKey(privateKey);
console.log('public key  :', toHex(publicKey));

const address = keccak256(publicKey.slice(1)).slice(-20);
console.log('address     :', '0x' + toHex(address));

However, I get a valid private and public key pair, but not the corresponding address (compared to some online converters like this and this).

Why is my AJAX form refreshing the page when I submit?

I am creating a simple Follow/Unfollow system, everything works fine in the sense that it inserts the row and deletes the row when I follow/unfollow, but for some reason it refreshes the page every time, even though I’m using e.preventDefault();, why is this? Thanks

<?php if ($is_following): ?>
   <form method="POST" action="">
     <input type="hidden" value="<?php echo $username; ?>" name="username">
     <input type="hidden" value="<?php echo $grabUser['username']; ?>" name="following">
     <input type="hidden" value="<?php echo date('Y/m/d H:i:s'); ?>" name="date">
     <button class="followBtn" type="button" value="unfollow" name="action">Unfollow</button>
   </form>
 <?php else: ?>
   <form method="POST" action="">
     <input type="hidden" value="<?php echo $username; ?>" name="username">
     <input type="hidden" value="<?php echo $grabUser['username']; ?>" name="following">
     <input type="hidden" value="<?php echo date('Y/m/d H:i:s'); ?>" name="date">
     <button class="followBtn" type="button" value="follow" name="action">Follow</button>
    </form>
 <?php endif; ?>

This is my script at the bottom of my webpage:

  <script type="text/javascript">
  //~~~~~~~~~~~~~~~~~~~~ SCRIPT FOR FOLLOWING A USER ~~~~~~~~~~~~~~~~~~~~//
  (function() {
    $(document).ready(function() {
    console.log("Follow function is working..");
    $(".followBtn").on("click", function(e) {

        if ($(this).hasClass('followBtn-signin')) {
            e.preventDefault(); // Prevent form submission
            $('#loginModal').modal('show'); // Show login modal
            return;
        }

        e.preventDefault();

        var followButton = $(this);
        var formDataFollow = {
            'FollowUser': true,
            'username': $(this).siblings('input[name="username"]').val(),
            'following': $(this).siblings('input[name="following"]').val(),
            'date': $(this).siblings('input[name="date"]').val(),
            'action': $(this).val()
        };
        console.log(formDataFollow);
        $.ajax({
            type: "POST",
            url: "/Blog/resources/PHP/FollowUserPHP.php",
            data: formDataFollow,
            dataType: 'json',
            success: function(response) {
                // Toggle the button text based on the response
                if (response.status === "followed") {
                    followButton.text("Unfollow");
                } else if (response.status === "unfollowed") {
                    followButton.text("Follow");
                }
                // Manually submit the form
                followButton.closest('form').submit();
            },
            error: function(xhr, status, error) {
                console.log(error);
            }
        });
      });
    });
   })();
 </script>

and this is my FollowUserPHP.php:

 <?php
  session_start();
  require_once '/var/www/vhosts/my-site.xyz/httpdocs/PHP/connect.php';

 if (isset($_POST['username']) && isset($_POST['following']) && isset($_POST['date']) && isset($_POST['action'])) {
  $username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
  $following = filter_var($_POST['following'], FILTER_SANITIZE_STRING);
  $date = filter_var($_POST['date'], FILTER_SANITIZE_STRING);
  $action = $_POST['action'];

if ($action == 'follow') {
    $stmt = $dbh->prepare("INSERT INTO `followers` (`username`, `following`, `date`) VALUES (:username, :following, :date)");
    $stmt->bindParam(':username', $username, PDO::PARAM_STR);
    $stmt->bindParam(':following', $following, PDO::PARAM_STR);
    $stmt->bindParam(':date', $date, PDO::PARAM_STR);
    $stmt->execute();
    $response = array('status' => 'followed');
} elseif ($action == 'unfollow') {
    $stmt = $dbh->prepare("DELETE FROM `followers` WHERE `username` = :username AND `following` = :following");
    $stmt->bindParam(':username', $username, PDO::PARAM_STR);
    $stmt->bindParam(':following', $following, PDO::PARAM_STR);
    $stmt->execute();
    $response = array('status' => 'unfollowed');
} else {
    // Invalid action value
    $response = array('error' => 'Invalid action');
}
} else {
// Missing parameters
$response = array('error' => 'Missing parameters');
}

// Output the response as JSON
header('Content-Type: application/json');
echo json_encode($response);
exit;
?>

How to display only cities names in Satellite view (google maps api)

I can’t control the lables display in satellite or hybrid view, but it work well when I not specific mapTypeId.

The styles not take effect if that mapTypeId is in satellite or hybrid.

Any help, thanks

  // Request needed libraries.
  const { Map, InfoWindow } = await google.maps.importLibrary("maps");
  const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary(
    "marker",
  );
  const map = new Map(document.getElementById("map"), {
    zoom: 12,
    center: { lat: 34.84555, lng: -111.8035 },
    mapTypeId: 'satellite',
    disableDefaultUI: true,
    mapId: "4504f8b37365c3d0",
    // Disable various map features to only show city names.
    styles: [
    
    
      {
        featureType: "all",
        elementType: "labels",
        stylers: [{ visibility: "off" }],
      },
      {
        featureType: "administrative",
        elementType: "labels",
        stylers: [{ visibility: "on" }],
      },
      {
        featureType: "administrative.locality",
        elementType: "labels",
        stylers: [{ visibility: "on" }],
      },
    ],
  });

I tried to add disableDefaultUI: true,
but it doesn’t work

How do I trigger onclick event with only one click?

It’s me again! I’ve been slaving to get an accordion menu to work properly and I managed to get it to work… the main problem is, it only triggers on the double click of a button.

I want to make this so the user only needs to click on the button once. I have other usages of buttons in my code that work with only one click and this one does follow their formats, but I don’t know whats making it trigger only on double click.

Here is the Javascript — I could only make it work if i put it in a function(), just leaving out the function would not allow the script to work.


function accordion() {

const acc = document.getElementsByClassName("levelTab");
var a;

for (a = 0; a < acc.length; a++) {
    acc[a].addEventListener('click', function() {
        this.classList.toggle('active');
        var levelContain = this.nextElementSibling;
        if (levelContain.style.maxHeight) {
            levelContain.style.maxHeight = null;
        } else {
            levelContain.style.maxHeight = levelContain.scrollHeight + "px";
        }
    });
};
}

And the HTML


<button onclick="accordion()" class="levelTab">Cantrips</button>
                <div class="levelContain">
                    <p>
                        insert Spells here.
                    </p>
                </div>

scrape a JS-Rendered, JSON using R

I want to get the info stored in some JQuery scripts

link <- "https://rod.pulse.gop.pk/details_page.html?I=740287512"
webpage <- xml2::read_html(link)

In the above link it only shows partial data but what I want to get is the json file with full data stored in some link inspect > network > _search

https://rodb.pulse.gop.pk/registry_index_2/_search

below is the data stored in the above link

{"took":1,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"registry_index_2","_id":"740287512","_score":1.0,"_source":{"Id":740287512,"UserId":13887,"VendorId":1,"UserWorkQueMasterId":740237089,"RegisteredNumber":"310","JildNumber":"1489","PropertyNumber":"واقع رقبہ  موضع سوہان دیہاتی  اندر حدود  میونسپل کارپوریشن راولپنڈی تحصیل و ضلع راولپنڈی ","IsApproved":true,"IsJildCompleted":false,"BahiNumber":null,"RegistryDate":"1993-01-25","IsActive":true,"CreatedDate":"2023-10-23T20:09:19.310000","ModifiedDate":null,"CreatedBy":13887,"ModifiedBy":null,"TehsilId":112,"MauzaId":0,"Address":"N/A","IsExported":null,"Area":"0-8-0-0","RegistryValue":128000.0,"RegistryExportImg":"cfe958064b6c79b71e03350b5394f32a","NonNullFCount":null,"NullFCount":null,"RegistryTypeId":5,"MauzaName":null,"RegistryParties":[{"Id":18595212,"Name":"محمد یسین ","SpouseName":"شمس الدین ","CNIC":"21134087515","RegistryPartiesTypeId":1,"CraetedDate":"2023-10-23T20:09:19.310000","ModifiedDate":null,"CreatedBy":13887,"ModifiedBy":null,"VendorId":1,"SequenceNumber":1,"RegistryExportImg":"b17f19516a4fc8742aa21ce8bf0340b4"},{"Id":18595213,"Name":"چوہدری رحمت ","SpouseName":"چوہدری الله دین ","CNIC":"0","RegistryPartiesTypeId":2,"CraetedDate":"2023-10-23T20:09:19.310000","ModifiedDate":null,"CreatedBy":13887,"ModifiedBy":null,"VendorId":1,"SequenceNumber":2,"RegistryExportImg":"89c79a6b93dde25904088ce129b1a22a"}],"RegistryType":"بیع","Tehsil":"راولپنڈی"}}]}}


library(jsonlite)
lines <- readLines("_search.json")
lines[1] <- sub(".* = (.*)", "\1", lines[1])
lines[length(lines)] <- sub(";", "", lines[length(lines)])
json_data <- fromJSON(paste(lines, collapse="n"))
head(json_data[[4]][[3]])

The above data is publicly available data

Get SVG Path Point Position Relative to DOM (not parent SVG)

I am trying to do a motion path of an image, that will jump from 1 SVG to another, following all paths.
The image is a normal

What I want is to move the image to a specific point, on any svg I have in my document.
If I add my image inside a SVG (using svg image) and move it, it’s easy, I just use:

var temp_point=temp_path.getPointAtLength(temp_distance);
$('.handz').css("transform","translateX("+temp_point.x+"px) translateY("+temp_point.y+"px) rotate("+deg+"deg)");

But since I want to have my image outside the svg, and have 1 single image, that can be moved to any point on any path, from any svg from my document, I can’t seem to figure it out.

I tried using:

function getRelativeXY(x, y, svg, element){

  var xx=element.getBoundingClientRect().x+x;
  var yy=element.getBoundingClientRect().y+y;
  return {x:xx,y:yy}
}

But it does not give me the desired results, as it does not move precisely where it should move. I think (I am not sure) it has something to do if the original svg has scaling/transforms applied, or different view box details.

enter image description here

Open random .html file when pressing Shuffle button

My problem is that i have already made implementation of java script Shuffle button but only working in specific url which i will put into line document.location.href i used for this example somefile.html.

    jQuery('body').on('click', '#shuffle-button', function() {
        gtag('event', 'Shuffle', {
            'click': 'true'
        });
        ga('send', 'event', 'Shuffle', 'click', 'true');
        document.location.href = '**/somefile.html**';
    }).on('click', '#station-share-toggle, #station-share-close', function() {
        $('#station-share-buttons').toggle();
    }).on('click', '.jp-share-button', function() {
        window.open($(this).attr('href'), "share", "width=500, height=500");
        return false;
    });

So into same folder where is located somefile.html there is 350+ other .html files which i would like to make it when Shuffle button is clicked to transfer to random of that 350+ .html files.
This example only work for somefile.html. What i have to do to or where is my mistake I would be glad if someone has option to make it functional.

Next.JS / Clerk.com and authentication with .net Web API

I’m new to react/next.js and I’m trying to setup my app to use a backend .NET 8 WEB API.

I have my WEB API set up via this Link.

This works great. When I start my WEB API in VS 2022, then it requires me to sign into Clerk.com and then displays my WEB API call.

Now I’m trying to call the same WEB API via my next.js app.

In the end, I would want the user to sign into my next.js app, then use that sign in validation to pass to my .NET 8 WEB API to log into that and then be able to talk properly to the WEB API.

Right now, I have to make sure I am signed out of the WEB API, then sign into next.js via Clerk.com. Then click the button that calls the WEB API and it requires me to sign in AGAIN to Clerk.com.

After this is done it receives a 302 found. Seems like it isn’t passing across the necessary items to do the authentication?

enter image description here

Any thoughts?

Here is my next.js code:

"use client"

import { useEffect, useState } from 'react';
import { WeatherForecast } from '../interfaces/WeatherForecastModel'; // Adjust the import path as necessary

import { enableRipple } from '@syncfusion/ej2-base';
import { ButtonComponent } from '@syncfusion/ej2-react-buttons'
import { useAuth, useClerk } from '@clerk/clerk-react'
enableRipple(true);

const Index = () => {
  const { getToken } = useAuth()
  const [token, setToken] = useState(''); // Manage token with useState
  const [clerkOther, setclerkOther] = useState(''); // Manage token with useState
  const [data, setData] = useState<WeatherForecast[]>([]);

  const { user } = useClerk();

  const fetchData = async (url: string) => {
    const token = await getToken();
    const clerkOther = user?.publicMetadata.clerk_token as string;
    setToken(token ?? ''); // Update the token state
    setclerkOther(clerkOther); // Update the token state

    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
      mode: 'no-cors',
    });

    if (!response.ok) {
      throw new Error('Network response was not ok');
    }

    return response.json();
  };

  const clickEventHandlerWeather = async () => {
    try {
      const jsonData = await fetchData('https://localhost:7160/WeatherForecast');
      setData(jsonData);
    } catch (error) {
      console.error('Failed to fetch weather data:', error);
    }
  };

  const clickEventHandlerLogin = async () => {
    try {
      await fetchData('https://localhost:7160/Login');
      // For login, assuming you might not want to set any specific data
    } catch (error) {
      console.error('Failed to login:', error);
    }
  };

  return (
    <div className="row">
      <div className='col-md-6'>
        <ButtonComponent cssClass='e-danger' onClick={clickEventHandlerLogin}>Login</ButtonComponent>
      </div>
      <br></br><br></br>
      <div className='col-md-6'>
        <ButtonComponent cssClass='e-danger' onClick={clickEventHandlerWeather}>Weather</ButtonComponent>
      </div>
      {/* Display token. Ensure you handle displaying sensitive information securely */}
      <div style={{ width: '200px' }}>{token}</div>
      <br></br>
      <div style={{ width: '200px' }}>clerkOther: {token}</div>
    </div>
  );
};

export default Index;

Note: Another issue is CORS. I know I don’t need to do this, but that was causing other errors too. So I plan to research that once I’m about to hit the WEB API.