Issue of overlapping section [closed]

I was just making a demo site but there is a problem. when i click on escape button the escape section overlaps with next section any solution?

Everything thing is OK but if i put any HTML code and escape HTML, the section overlaps with the next section

// Scroll event to change navbar background color
window.addEventListener('scroll', function() {
  const navbar = document.getElementById('navbar');
  if (window.scrollY > 50) {
    navbar.classList.add('scrolled');
  } else {
    navbar.classList.remove('scrolled');
  }
});

// Mobile menu toggle
const mobileMenu = document.getElementById('mobile-menu');
const navLinks = document.getElementById('nav-links');

mobileMenu.addEventListener('click', function() {
  navLinks.classList.toggle('active');
});

// Function to escape HTML and validate input
function validateHTML() {
  const htmlInputField = document.getElementById('html-input');
  const escapedHtmlOutput = document.getElementById('escaped-html');
  const escapedHtmlBox = document.getElementById('escaped-html-box');
  const errorMessage = document.getElementById('error-message');
  const htmlInput = htmlInputField.value;

  // Simple HTML validation (basic pattern to check for HTML tags)
  const validHTMLPattern = /</?[a-z][sS]*>/i;

  if (!validHTMLPattern.test(htmlInput)) {
    errorMessage.textContent = "Please enter valid HTML.";
    htmlInputField.classList.add('error');
    escapedHtmlBox.style.display = "none"; // Hide the escaped HTML box on error
  } else {
    errorMessage.textContent = "";

    // Escape HTML function
    function escapeHTML(html) {
      return html
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
    }

    const escapedHTML = escapeHTML(htmlInput);
    escapedHtmlOutput.value = escapedHTML; // Display escaped HTML in the text area
    htmlInputField.classList.remove('error');

    // Show the escaped HTML text area
    escapedHtmlBox.style.display = "block";

    // Scroll to escaped HTML area
    escapedHtmlBox.scrollIntoView({
      behavior: 'smooth'
    });
  }
}

// Add event listener to button to call validateHTML function
document.getElementById('escape-button').addEventListener('click', validateHTML);
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: Arial, sans-serif;
  background-color: #000;
  color: #fff;
  line-height: 1.6;
  position: relative;
}


/* Navbar styles */

.navbar {
  position: fixed;
  top: 0;
  width: 100%;
  padding: 15px 20px;
  background: transparent;
  transition: background-color 0.3s;
  z-index: 100;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.navbar.scrolled {
  background-color: rgba(0, 0, 0, 0.9);
}

.navbar .logo {
  font-size: 24px;
  font-weight: bold;
  color: white;
}

.navbar ul {
  list-style: none;
  display: flex;
}

.navbar ul li {
  margin: 0 20px;
}

.navbar ul li a {
  color: white;
  text-decoration: none;
  font-size: 18px;
  padding: 8px;
  transition: color 0.3s;
}

.navbar ul li a:hover {
  color: #ff5733;
}


/* Hamburger menu icon */

.menu-toggle {
  display: none;
  flex-direction: column;
  cursor: pointer;
}

.menu-toggle div {
  width: 30px;
  height: 3px;
  background-color: white;
  margin: 5px 0;
}


/* Responsive Navbar for smaller screens */

@media (max-width: 768px) {
  .navbar ul {
    position: absolute;
    top: 60px;
    right: 0;
    height: 0;
    overflow: hidden;
    flex-direction: column;
    width: 100%;
    background-color: rgba(0, 0, 0, 0.9);
    transition: height 0.3s ease;
  }
  .navbar ul.active {
    height: 200px;
    /* Adjust based on how many links you have */
  }
  .navbar ul li {
    margin: 10px 0;
    text-align: center;
  }
  .menu-toggle {
    display: flex;
  }
}


/* Main Section */

.main-section {
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: start;
  align-items: center;
  text-align: center;
  padding: 120px 20px 20px;
}

.main-section h1 {
  font-size: 48px;
  margin-bottom: 10px;
}

.main-section h2 {
  font-size: 24px;
  background: linear-gradient(90deg, #ff6f61, #ffcd2b);
  -webkit-background-clip: text;
  color: transparent;
}

.input-box {
  margin-top: 30px;
  width: 80%;
  max-width: 600px;
}

.input-box textarea {
  width: 100%;
  height: 200px;
  padding: 15px;
  border: none;
  border-radius: 8px;
  background-color: #333;
  color: #fff;
  font-size: 16px;
  resize: none;
}

.input-box textarea::placeholder {
  color: #888;
}

.input-box .error {
  border: 2px solid red;
}

.input-box button {
  margin-top: 15px;
  padding: 10px 20px;
  font-size: 16px;
  background-color: #ff5733;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.input-box button:hover {
  background-color: #ff6f61;
}


/* Escaped HTML Section */

#escaped-html-box {
  display: none;
  margin-top: 20px;
  width: 80%;
  max-width: 600px;
  position: relative;
}

#escaped-html-box textarea {
  width: 100%;
  height: 200px;
  padding: 15px;
  border: none;
  border-radius: 8px;
  background-color: #333;
  color: #fff;
  font-size: 16px;
  resize: none;
}


/* Information Section */

.info-section {
  padding: 50px 20px;
  background-color: #111;
  justify-content: start;
  display: flex;
  transition: margin 0.3s;
  /
}

.info-section h2 {
  text-align: center;
  margin-bottom: 20px;
}

.info-section p {
  max-width: 800px;
  margin: 0 auto;
  text-align: center;
  font-size: 18px;
  line-height: 1.8;
}


/* FAQ Section */

.faq-section {
  padding: 50px 20px;
}

.faq-section h2 {
  text-align: center;
  margin-bottom: 20px;
}

.faq-section .faq {
  max-width: 800px;
  margin: 0 auto;
}

.faq-section .faq-item {
  margin-bottom: 20px;
}

.faq-section .faq-item h3 {
  font-size: 20px;
  margin-bottom: 10px;
}

.faq-section .faq-item p {
  font-size: 16px;
  color: #ccc;
}


/* Footer */

footer {
  padding: 20px;
  text-align: center;
  background-color: #111;
  color: #888;
}
```

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<style type="text/css">
  /* Reset some default styles */
</style>
<!-- Navbar -->
<nav class="navbar" id="navbar">
  <div class="logo">Histolix</div>

  <ul id="nav-links">
    <li><a href="#">Home</a></li>
    <li><a href="#info">About</a></li>
    <li><a href="#faq">FAQ</a></li>
  </ul>

  <div class="menu-toggle" id="mobile-menu">
    <div>&nbsp;</div>

    <div>&nbsp;</div>

    <div>&nbsp;</div>
  </div>
</nav>
<!-- Main Section -->

<section class="main-section" id="home">
  <h1>WELCOME TO HISTOLIX</h1>

  <h2>THE BEST TOOL FOR <span>ESCAPING HTML</span></h2>

  <div class="input-box"><textarea id="html-input" placeholder="Enter your HTML here..."></textarea><button id="escape-button">Escape HTML</button>

    <p id="error-message" style="color: red;">&nbsp;</p>
  </div>

  <div id="escaped-html-box">
    <h3>ESCAPED HTML</h3><textarea id="escaped-html" readonly="readonly"></textarea></div>
</section>
<!-- Information Section -->

<section class="info-section" id="info">
  <h2>About the HTML Escape Tool</h2>

  <p>This tool helps you escape HTML by converting special characters into their corresponding HTML entities. It ensures your code is safe and properly rendered in the browser. Whether you&#39;re a developer or just getting started with HTML, Histolix makes
    your job easier.</p>
</section>
<!-- FAQ Section -->

<section class="faq-section" id="faq">
  <h2>Frequently Asked Questions</h2>

  <div class="faq">
    <div class="faq-item">
      <h3>What is HTML escaping?</h3>

      <p>HTML escaping is the process of converting special characters like &lt;, &gt;, &amp;, and &quot; into their corresponding HTML entities to ensure they are displayed correctly in the browser.</p>
    </div>

    <div class="faq-item">
      <h3>Why do I need to escape HTML?</h3>

      <p>Escaping HTML is essential to prevent code injection attacks and ensure your HTML is safely rendered, especially in dynamic applications or user-submitted content.</p>
    </div>
  </div>
</section>
<!-- Footer -->

<footer>
  <p>&copy; 2024 Histolix - All Rights Reserved.</p>
</footer>

How to disregard rows labeled for deletion when counting rows in IG Oracle Apex?

I have page item in my Interactive Grid (IG) that dynamically updates the row count using a model subscription. When a new row is added, the count increases, and if a row is marked for deletion, the count decreases by 1. However, if a row is only marked for deletion, it still exists in the IG and will be counted when adding a new row. If I have 2 rows and delete 1, the row count drops to 1. When adding a new row, it increases to 3. I want it to be 2, excluding rows marked for deletion. Is it feasible to omit rows chosen for deletion or find an alternate solution to achieve the required functionality?

Leaflet.js not showing properly

Some reason, leaflet.js is not displaying. I’m completely stumped.

I just want the map to show at full width and I have tried eliminating each file included but non seem to make it work.

any other help toward my code would be amazing as I’m purely learning as I go.

Thank you very much in advance.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Park Finder</title>
  <link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css" />
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-icons/1.5.0/font/bootstrap-icons.min.css">
  <style>
    body { height: 100vh; display: flex; flex-direction: column; }
    .navbar { background-color: #333; color: white; }
    .suggestions { position: absolute; top: 100%; left: 0; width: 100%; border-radius: 8px; background: white; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); z-index: 1000; max-height: 200px; overflow-y: auto; margin-top: 8px; }
    .suggestion-item { padding: 10px; cursor: pointer; border-bottom: 1px solid #ddd; }
    .suggestion-item:hover { background: #ff5722; color: white; }
    #map { flex: 1; width: 100%; display: block; height: 100%; }
    .nearby-parks { padding: 10px; background: #f8f8f8; border-top: 1px solid #ccc; height: 200px; overflow-y: auto; }
    .nearby-park { padding: 10px; cursor: pointer; border-bottom: 1px solid #ddd; }
    .nearby-park:hover { background: #007bff; color: white; }
  </style>
</head>
<body>
  <nav class="navbar navbar-expand-lg navbar-dark">
    <div class="container-fluid">
      <span class="navbar-brand">Park Finder</span>
      <div class="search-container ml-auto d-flex">
        <div class="search-bar position-relative">
          <input type="text" id="parkSearch" class="form-control" placeholder="Search for parks...">
          <div class="suggestions" id="suggestions"></div>
        </div>
        <button class="btn btn-primary ml-2" onclick="centerMap()">
          <i class="bi bi-geo-alt"></i> My Location
        </button>
      </div>
    </div>
  </nav>
  <div id="map"></div>
  <div class="nearby-parks container mt-3">
    <h3>Nearby Parks</h3>
    <div id="nearbyParks"></div>
  </div>

  <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" crossorigin="anonymous"></script>
  <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
  <script>
  document.addEventListener('DOMContentLoaded', () => {
  let parksData = [], userLocation = { lat: null, lon: null };
  var map = L.map('map');

  function centerMap() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        userLocation.lat = position.coords.latitude;
        userLocation.lon = position.coords.longitude;
        map.setView([userLocation.lat, userLocation.lon], 13);
        showNearbyParks();
      }, function(error) {
        console.error("Geolocation failed: " + error.message);
        alert("Geolocation is not supported by your browser or permission denied.");
      });
    } else {
      alert('Geolocation is not supported by your browser.');
    }
  }

  centerMap();

  fetch('fetch.php')
    .then(response => response.ok ? response.json() : Promise.reject('Network response was not ok'))
    .then(data => {
      parksData = data;
      parksData.forEach(park => {
        L.marker([park.latitude, park.longitude]).addTo(map)
          .bindPopup(`<b>${park.name}</b><br>${park.amenities}`);
      });
      document.querySelector('#parkSearch').addEventListener('input', function(e) {
        let query = e.target.value.toLowerCase();
        if (query) {
          let suggestions = parksData.filter(park => park.name.toLowerCase().includes(query));
          suggestions.sort((a, b) => getDistance(userLocation.lat, userLocation.lon, a.latitude, a.longitude) - getDistance(userLocation.lat, userLocation.lon, b.latitude, b.longitude));
          updateSuggestions(suggestions);
        } else {
          document.getElementById('suggestions').innerHTML = '';
        }
      });
      document.querySelector('#parkSearch').addEventListener('change', function(e) {
        let selectedPark = parksData.find(park => park.name.toLowerCase() === e.target.value.toLowerCase());
        if (selectedPark) {
          map.setView([selectedPark.latitude, selectedPark.longitude], 15);
          L.marker([selectedPark.latitude, selectedPark.longitude]).addTo(map)
            .bindPopup(`<b>${selectedPark.name}</b><br>${selectedPark.amenities}`).openPopup();
          document.getElementById('suggestions').innerHTML = '';
        }
      });
      showNearbyParks();
    })
    .catch(error => {
      console.error('Fetching park data failed:', error);
      alert('Failed to fetch park data. Please try again later.');
    });

  function updateSuggestions(parks) {
    let suggestionsContainer = document.getElementById('suggestions');
    suggestionsContainer.innerHTML = '';
    parks.forEach(park => {
      let suggestionItem = document.createElement('div');
      suggestionItem.textContent = park.name;
      suggestionItem.classList.add('suggestion-item');
      suggestionItem.addEventListener('click', () => {
        document.querySelector('#parkSearch').value = park.name;
        map.setView([park.latitude, park.longitude], 15);
        L.marker([park.latitude, park.longitude]).addTo(map)
          .bindPopup(`<b>${park.name}</b><br>${park.amenities}`).openPopup();
        suggestionsContainer.innerHTML = '';
      });
      suggestionsContainer.appendChild(suggestionItem);
    });
  }

  function showNearbyParks() {
    let nearbyParksContainer = document.getElementById('nearbyParks');
    nearbyParksContainer.innerHTML = '';
    let nearbyParks = parksData.filter(park => getDistance(userLocation.lat, userLocation.lon, park.latitude, park.longitude) <= 5);
    nearbyParks.sort((a, b) => getDistance(userLocation.lat, userLocation.lon, a.latitude, a.longitude) - getDistance(userLocation.lat, userLocation.lon, b.latitude, b.longitude));
    nearbyParks.forEach(park => {
      let nearbyParkItem = document.createElement('div');
      nearbyParkItem.textContent = `${park.name} (${getDistance(userLocation.lat, userLocation.lon, park.latitude, park.longitude).toFixed(2)} km)`;
      nearbyParkItem.classList.add('nearby-park');
      nearbyParkItem.addEventListener('click', () => {
        map.setView([park.latitude, park.longitude], 15);
        L.marker([park.latitude, park.longitude]).addTo(map)
          .bindPopup(`<b>${park.name}</b><br>${park.amenities}`).openPopup();
      });
      nearbyParksContainer.appendChild(nearbyParkItem);
    });
  }

  function getDistance(lat1, lon1, lat2, lon2) {
    const R = 6371, dLat = (lat2 - lat1) * Math.PI / 180, dLon = (lon2 - lon1) * Math.PI / 180;
    const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
    return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  }
});

  </script>
</body>
</html>

I’ve tried different display modes in css but with no luck, it must be something really simple.

Products Carousel not shifting

I have created a product carousel using Javascript, the idea is i have a row of 10 products and one product is focused means the product i click on it zooms in and show more information about it and it should be in the middle. now when i click on unfocused product whether right or left am expecting that all products shifts until the one i cliked takes the middle position here is the carousel photo:

enter image description here

and this is the Js code:

jQuery(document).ready(function($) {
    const carousel = $('.carousel-custom');
    const items = $('.carousel-item');
    let focusedIndex = 5; // Start with the fourth item focused

// Function to center the focused item
function centerItem(index) {
    const item = $(items[index]);
    const carouselWidth = carousel.width();
    const itemWidth = item.outerWidth(true);
    
    // Calculate the scroll position to center the item
    const scrollPosition = 135;
    // Debugging output
    console.log('Focused Index:', index);
    console.log('Item Position:', item.position().left);
    console.log('Carousel Width:', carouselWidth);
    console.log('Item Width:', itemWidth);
    console.log('Scroll Position:', scrollPosition);

    // Ensure scroll position is not negative or out of bounds
    if (scrollPosition < 0) {
        carousel.animate({ scrollLeft: 0 }, 300);
    } else if (scrollPosition + carouselWidth > carousel[0].scrollWidth) {
        carousel.animate({ scrollLeft: carousel[0].scrollWidth - carouselWidth }, 300);
    } else {
        // Animate the scroll to the calculated position
        carousel.animate({ scrollLeft: scrollPosition }, 300);
    }

    
    
}

// Function to set the focus on an item by index
function setFocus(index) {
    // Remove focused class from all items
    items.removeClass('focused');
    // Add focused class to the specified item
    $(items[index]).addClass('focused');
    // Center the focused item
    centerItem(index);
}

// Function to trigger a click on the focused item
function triggerClick(index) {
    items.eq(index).trigger('click');
}

// Set initial focus on the third item and trigger a click
setFocus(focusedIndex);
triggerClick(focusedIndex); // This simulates a click on the third item

// Click event for carousel items
items.on('click', function() {
    const clickedIndex = $(this).index();
    console.log('Clicked Index:', clickedIndex); // Debugging output
    setFocus(clickedIndex); // Focus on clicked item
});

});

The issue is the products are not shifting when i click on one they stay in the same place.

Products Carousel not shifting Js

I have created a product carousel using Javascript, the idea is i have a row of 10 products and one product is focused means the product i click on it zooms in and show more information about it and it should be in the middle. now when i click on unfocused product whether right or left am expecting that all products shifts until the one i cliked takes the middle position here is the carousel photo:

enter image description here

and this is the Js code:

jQuery(document).ready(function($) {
    const carousel = $('.carousel-custom');
    const items = $('.carousel-item');
    let focusedIndex = 5; // Start with the fourth item focused

// Function to center the focused item
function centerItem(index) {
    const item = $(items[index]);
    const carouselWidth = carousel.width();
    const itemWidth = item.outerWidth(true);
    
    // Calculate the scroll position to center the item
    const scrollPosition = 135;
    // Debugging output
    console.log('Focused Index:', index);
    console.log('Item Position:', item.position().left);
    console.log('Carousel Width:', carouselWidth);
    console.log('Item Width:', itemWidth);
    console.log('Scroll Position:', scrollPosition);

    // Ensure scroll position is not negative or out of bounds
    if (scrollPosition < 0) {
        carousel.animate({ scrollLeft: 0 }, 300);
    } else if (scrollPosition + carouselWidth > carousel[0].scrollWidth) {
        carousel.animate({ scrollLeft: carousel[0].scrollWidth - carouselWidth }, 300);
    } else {
        // Animate the scroll to the calculated position
        carousel.animate({ scrollLeft: scrollPosition }, 300);
    }

    
    
}

// Function to set the focus on an item by index
function setFocus(index) {
    // Remove focused class from all items
    items.removeClass('focused');
    // Add focused class to the specified item
    $(items[index]).addClass('focused');
    // Center the focused item
    centerItem(index);
}

// Function to trigger a click on the focused item
function triggerClick(index) {
    items.eq(index).trigger('click');
}

// Set initial focus on the third item and trigger a click
setFocus(focusedIndex);
triggerClick(focusedIndex); // This simulates a click on the third item

// Click event for carousel items
items.on('click', function() {
    const clickedIndex = $(this).index();
    console.log('Clicked Index:', clickedIndex); // Debugging output
    setFocus(clickedIndex); // Focus on clicked item
});

});

The issue is the products are not shifting when i click on one they stay in the same place.

Dependency issues with React components?

Today I had a discussion with my colleague about React dependencies. He thought that all the variables that the components depend on for side effects should be put into the dependency array, for example

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

export const Component = props => {
    const { someInfo } = props;

    const [info, setInfo] = useState(null);
    const { updateInfo } = useContext(someInfoContext);

    const initSomething = async publicId => {
        const res = await getPublicInfo(publicId);

        updateInfo(res);
        setInfo(res);
    };

    // Here only someInfo.publicId is used
    useEffect(() => {
        initSomething(someInfo.publicId);
    }, [someInfo.publicId]);

    return <div>hellp world</div>;
};

Here, the side effect in useEffect depends on the variable someInfo.publicId, so I put it in the dependency array to ensure that the side effect can be re-executed every time it changes. However, my colleague disagrees. He thinks that all the variables in useEffect are variable dependencies, so he thinks it should be written like this

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

export const Component = props => {
    const { someInfo } = props;

    const [info, setInfo] = useState(null);
    const { updateInfo } = useContext(someInfoContext);

    const initSomething = useCallback(
        async publicId => {
            const res = await getPublicInfo(publicId);

            updateInfo(res);
            setInfo(res);
        },
        [updateInfo]
    );

    // Here someInfo.publicId and initSomething are used
    useEffect(() => {
        initSomething(someInfo.publicId);
    }, [someInfo.publicId, initSomething]);

    return <div>hellp world</div>;
};


I think there is a disadvantage of writing like this, that is, the dependency is contagious. The reference of the function must be guaranteed to be unchanged, so the function must be wrapped with useCallback, and updateInfo in initSomething must also be processed with useCallback. This needs to be processed all the time, which brings a lot of mental burden, and the code is prone to problems and infinite loops. However, if it is like what I wrote first, initSomething will be re-declared when the component renders, but it can be guaranteed that there is no problem with the code execution logic.

I want to know which of the first and second ways of writing is correct?

Trying to return a found item from an actors inventory within foundry vtt

Hi i am trying to create a macro in foundry that looks for a health potion within an selected actor’s inventory, if its found i will do something to expend it as a use, if not found then return an error to foundry. The code i have below is how far i have got but it’s returning the error despite the item being in the actor’s inventory.

Can anyone point me in the correct direction?

main()

async function main() {

// Is a token selected? If not, error
    console.log("Tokens: ", canvas.tokens.controlled)
    if(canvas.tokens.controlled.length == 0 || canvas.tokens.controlled.length > 1){
        ui.notifications.error("Please select a single token")
        return;
    }
    let actor = canvas.tokens.controlled[0].actor
    console.log(actor)
// Does the token have a health potion?
    let healthpotion = actor.items.find(item => item.value == "Potion of Greater Healing")
console.log(healthpotion)
    if(healthpotion == null || healthpotion == undefined){
        ui.notifications.error("No Health Potions left");
        return;
    }

From the console i can see the potion in the array but my code isn’t finding it.

enter image description here

Trying to return a found item from an actors inventory within foundry vtt, using javascript

Hi i am trying to create a macro in foundry that looks for a health potion within an selected actor’s inventory, if its found i will do something to expend it as a use, if not found then return an error to foundry. The code i have below is how far i have got but it’s returning the error despite the item being in the actor’s inventory.

Can anyone point me in the correct direction?

main()

async function main() {

// Is a token selected? If not, error
    console.log("Tokens: ", canvas.tokens.controlled)
    if(canvas.tokens.controlled.length == 0 || canvas.tokens.controlled.length > 1){
        ui.notifications.error("Please select a single token")
        return;
    }
    let actor = canvas.tokens.controlled[0].actor
    console.log(actor)
// Does the token have a health potion?
    let healthpotion = actor.items.find(item => item.value == "Potion of Greater Healing")
console.log(healthpotion)
    if(healthpotion == null || healthpotion == undefined){
        ui.notifications.error("No Health Potions left");
        return;
    }

From the console i can see the potion in the array but my code isn’t finding it.

enter image description here

RxJs ‘take’ operator after ‘map’ operator doesn’t work

Is it possible to take only a certain number of elements of an http call after I modify the original response with a ‘map’ operator?

For example, let’s say I have this very simple http call for the Rick And Morty API:

Simple two interfaces:

export interface Character {
  id: number;
  name: string;
  status: string;
  species: string;
  type: string;
  gender: string;
  origin: Origin;
  location: Location;
  image: string;
  episode: string[];
  url: string;
  created: string;
}

export interface RickAndMortyResponse {
  info: Info;
  results: Character[];
}

Now if I do the call, it’s mandatory to do it with the ‘RickAndMortyResponse’, but in my final response I just care about the first two elements of the ‘results’ response, so the logic thing to do would be this:

export class RickAndMortyService {
  private http = inject(HttpClient);

  characters$ = this.http
    .get<RickAndMortyResponse>('https://rickandmortyapi.com/api/character')
    .pipe(
      map((response) => response.results),
      take(2)
    );
}

However, this stills retrieving all the data of ‘results’, I presumed It’s because the ‘take’ operator affects the ‘RickAndMortyResponse’ and not the ‘results’ array.

So to solve this, the only way I see is to do a slice on the map operator:

characters$ = this.http
    .get<RickAndMortyResponse>('https://rickandmortyapi.com/api/character')
    .pipe(map((response) => response.results.slice(0, 2)));

So, is there any way to actually use operators like ‘take’ after I modified the original stream of data using ‘map’?

Delete mapping is not working from UI but working through Postman

export default function Cart()
{  const username=localStorage.getItem("username");
    const [data,setdata]=useState([]);
    const [amount,setAmount]=useState(0);
    const items=data.map((item)=>{
        return(
            <div key={item.name}>
            <h1>{item.name}</h1>
            <h5>{item.price}&#8377;</h5>
            <h5>{item.quantity}</h5>
            <Button onClick={()=>handlepayment(item.price,item.name,item.username)}>Make payment</Button>
            </div>
        )
    })
    
    function handlepayment(price,name,username)
    {
      console.log(`price=${price}, name=${name} , username=${username}`)
      if(amount<price)
      {
        alert("insufficient balance");
        return;
      }
      const url=`http://localhost:8080/cartproducts/${username}/${name}}`;
      fetch(url, { method: 'DELETE' })
      .then((response) => {
        if (!response.ok) {
          alert("something is wrong");
          throw new Error("Invalid credentials");
        }
        return response.json();
      })
  .then((data) => {console.log(data);
    updateamount(price);
  })
  .catch(error => console.error(error));

    }

The above is my react code so simply clicking on makepayment button takes three values as arguments and in the delete method in the url username and name will be shown . Ignore console.log statements those were written for debugging just to make know whether correct values are passed or not.

Below is the controller ignore the print statements those are for debugging

@RestController
@RequestMapping("/")
@CrossOrigin

public class FoodItemController {
    @Autowired
    private FoodItemService service;
@DeleteMapping("/cartproducts/{username}/{name}")
 public ResponseEntity<Map<String,String>> deletefooditem(@PathVariable String username, @PathVariable String name)
 {
     System.out.println("inside deletefooditem"+"username="+username+" "+"name="+name);
     
     Map<String,String> response=new HashMap<>();
     if(service.deletefooditem(username,name))
     {
     response.put("successfully", "deleted");
     return new ResponseEntity<>(response,HttpStatus.OK);
     }
     else {
         response.put("something is wrong", "not deleted");
         return new ResponseEntity<>(response,HttpStatus.BAD_REQUEST);
     }
 }
}

Below is the service layer

public boolean deletefooditem(String username,String name)
{
    System.out.println("inside service"+"username="+username+" "+"name="+name);
    FoodItems masteritem=repo.findByUsernameAndName(username,name);
    if(masteritem!=null)
    {
    repo.delete(masteritem);
    return true;
    }
    return false;
}

Below is the repo layer

public interface FoodItemrepo extends JpaRepository<FoodItems, Integer> {
    List<FoodItems> findAllByUsername(String username);
    FoodItems findByUsernameAndName(String username,String name);
}

Below is the model class

@Entity
public class FoodItems {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int Id;
    private String name;
    private String username;
   private int price;
   private int quantity;

I have applied all the annotations required which I didnot mention here like @Autowired,@RestController,@Service,@Repository.

The problem is coming at the service layer. It’s not able to find the data from database using findBy method mentioned. But using postman i’m not facing any problem like the data is getting deleted. If i use the findByUsernameAndName in another method name additem which I have mentioned below there it’s working as expected when I have hit from UI.

@Transactional
public void additem(FoodItems item)
{
    String username=item.getUsername();
    String name=item.getName();
    FoodItems fooditem=repo.findByUsernameAndName(username,name);
    System.out.println(fooditem);
    if(fooditem!=null)
    {
        
        item.setQuantity(item.getQuantity()+fooditem.getQuantity());
        item.setPrice(item.getQuantity()*item.getPrice());
        repo.save(item);
        repo.delete(fooditem);
    }
    repo.save(item);
}

This is where I was stuck like the username and name fields sent were correct and I have checked them in the service layer too. But the object which is going to get created is null everytime. Could someone please help me with this.

What is a simple way to test for equality in class instances?

I’m looking for a simple way to find equality of class instances where valueOf is a string.

Consider the code below. (codepen link) Some surprising results.

  • The class is a simple container holding a string. I’m comparing classes created from identical strings.
  • The less-than tests (1, 2) work great. It knows a is not less then b, and that a IS less than or equal to b.
  • Test 3 fails, but it does not call valueOf(). Okay.
  • Test 4 does call valueOf(), but still somehow does not see the two strings as equal.
  • Test 5 passes because I’m explicitly grabbing valueOf().

For test 3, I wish === called valueOf but okay. For test 4 I’m confounded. And test 1 and 2 show that it knows the values are equal. I’d like a simple way to test for equality here. Thoughts welcome.

class Container {
  #name;
  
  constructor(a) {
    this.#name = a;
  }

  valueOf() {
    console.log("valueOf() => "+this.#name);
    return this.#name;
  }
}

main();

function main() {
  const a = new Container("XYZ");
  const b = new Container("XYZ");
  test(1, a<b, false);                 // 1. PASS, a<b is false, (calls valueOf)
  test(2, a<=b, true);                 // 2. PASS, a<=b is true, (calls valueOf)
  test(3, a===b, true);                // 3. FAIL, a===b is false, (does *not* call valueOf)
  test(4, +a===+b, true);              // 4. FAIL, +a===+b is false, (*does* call valueOf ?!?)
  test(5, a.valueOf()===b.valueOf(), true); // 5. PASS, a.valueOf()===b.valueOf() is true
}

function test(n, a, x) {
  if (a === x) console.log(n + ". PASS");
  else console.log(n + ". FAIL: expected " + x);
  console.log("");
}

Problem with nested For Loops and If Statement/Loop when reading JSON array object data

I am writing code in javaScript to display a table containing JSON array object data. However, I need to verify that the data in one particular object matches the next object. For example, I have listed my code below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Table Example</title>
</head>
<body>
    <div id="table-container"></div>

    <script type="module">

import finnhub from 'https://cdn.skypack.dev/finnhub'

const api_key = finnhub.ApiClient.instance.authentications['api_key'];
api_key.apiKey = "cp3lm91r01qs3665m6p0cp3lm91r01qs3665m6pg"
const finnhubClient = new finnhub.DefaultApi()


finnhubClient.financialsReported({"symbol": "TSLA"}, (error, data, response) => {
console.log(data)

let d = 0
let b = 0
let s = []
let h = 0

window.d1 = data.data.length
window.b1 = data.data[b].report.bs.length

for (let d = 0; d < window.d1; d = d + 1) {

    console.log("d = " + d)
    //console.log("Data.data.length = " + data.data.length)

    window.b1 = data.data[d].report.bs.length


    for (let b = 0; b < window.b1; b = b + 1) {
        console.log("b = " + b)
        //console.log(data.data[d].report.bs[b].label + " = " + data.data[d].report.bs[b].value)
        
       
    // The code below as is lists matching '.label' parameters, but presumably encounters an error when there are more data.data.report.bs values in 'd' than there are in 'd+1'
    // I need to code a way to prevent the second part of the if statement's expression from checking for a data.data value that does not exist as I am reading an Uncaught Typeerror:Cannot read...undefined
        
        if (data.data[d].report.bs[b].label = data.data[d+1].report.bs[b].label){
           console.log(data.data[d].report.bs[b].label)
           console.log(data.data[d+1].report.bs[b].label)
        } else {
        console.log("Algorithm mismatch")
        }
    }  
    
}    


        // Function to create a table
        function createTable(rows, cols) {
            // Create a table element
            let table = document.createElement('table');
            table.border = '1';

            // Loop through rows
            for (let i = 0; i < rows; i++) {
                // Create a table row
                let tr = document.createElement('tr');

                // Loop through columns
                for (let j = 0; j < cols; j++) {
                    // Create a table cell
                    
                    if (j == 0){
                    let td = document.createElement('td');
                    td.textContent = data.data[0].report.bs[i].label;
                    td.style = "width:300px"
                    tr.appendChild(td);
                    } else if (j == 1){
                    let td = document.createElement('td');
                    td.textContent = data.data[0].report.bs[i].value;
                    td.style = "width:150px"
                    tr.appendChild(td);    
                    } else if (j == 2){
                    let td = document.createElement('td');
                    td.textContent = ``;
                    td.style = "width:25px"
                    tr.appendChild(td);
                    }
                }

                // Append the row to the table
                table.appendChild(tr);
            }

            // Append the table to the container
            document.getElementById('table-container').appendChild(table);
        }

    

        // Call the function to create a table with 5 rows and 3 columns
        createTable(data.data[0].report.bs.length, 3);
    
    
})
;
    
</script>
</body>
</html>

My problem occurs within the if statement/loop. Whereupon the second part of the if statement’s expression (… = data.data[d+1].report.bs[b].label). Specifically, as glancing at the JSON of console log of the data will show, some of the balance-sheet(“bs”) JSON hierarchy contain less array values than others; which means that not all of the labels will match up entirely.

To help explain, if you glance at the table I have constructed, you will see white boxes next to the number values of the financial data. I am planning on creating color coded fillings for the boxes to gauge their prospect value. However, to do that, I need to match the …bs[b].label values to ensure that they are the same description.

I apologize if I have not been 100% clear on this and will be more than happy to explain further.

I have tried a number of loops including while loops, for loops, etc. I expected to create a solution that stepped step-by-step to systematically reduce the number of times the second expression in the IF statement is checked in order to prevent the error code of ‘Cannot Read Undefined’. What resulted was a mixture of program breaks and error codes all conveying that either the data was not defined or that the loop structure was not completely finished.

Do DOM events create new functions in memory or just store a reference to an event

These buttons have the same event, do 2 of these functions get created separately in memory or event just points to a static function

I am not sure how to tell if the functions that get attached are the same objects or not.

<div style="padding: 5px">
   <button id="playerOne" onclick="onClick(event)"> One </button>
   <button id="playerTwo" onclick="onClick(event)"> Two </button>
</div>

Dynamic declared prototypes props in typescript

I want typescript to reconize the dynamicly added prototyps.

Here is my code so you would know What i mean.

class Test {
name: string= "";
lastName: string = "";

}

Then I have a Method that generate props dynamicly

const public_m = (...Items: any[]) => {
  try {
    Items.forEach(Item => {
      let keys = (
        Item.tb
          ? Item.tb().props // if there is a db Mapped Keys takes then otherwise Object.Keys
          : Object.keys(new Item())
      ).map(x => x.columnName || x);
      // create statis "n" methods that return new objects eg Test.n()
      Item["n"] = (...args: any[]) =>
        new Item(...args);
      // create clone Method that clone the object
      Item.prototype.clone = function () {
        let item = Item.n();
        for (let k in this) item[k] = this[k];
        return item;
      };
      // generate public set methods eg for name => Name() => Object(Test)
      keys.forEach(x => {
        let n =
          x[0].toUpperCase() + x.substring(1);
        if (!Item.prototype[n])
          Item.prototype[n] = function (v: any) {
            if (!this)
              throw "this is null " + Item;
            this[x] = v;
            return this;
          };
      });
    });
  } catch (e) {
    console.error(e, Items);
  }
};

public_m(Test);

export default Test;

Lastly I am using it as fellow

let test = Test.n().Name("test").LastName("test");

The issue is that typescript wont see those methods Name() and LastName()etc.. as those are create dynamicly

Position electron Menu

I am trying to find a way to position a native Menu (spawned from the main-process in an electron app).

Consider the following scenario:

I have a button [B] in a top-right position. Upon clicking it I want to show a Menu but align the topright corner of the menu with the bottomright corner of the button.

 _____________________
|               __|_B_|
|              |_menu_|
|              |______|
|              |______|
|              |______|
|                     |
|_____________________|

There is x and y which can be set in the Menu.popup function, but since there is no information about the width/height or any ability to set the menu anchor-position. I see no way to achieve this.

An alternative would be to use a renderer-side menu, but that would require extra effort to make it accessible for assistive technology etc.. So I was hoping I could find a way to make this work.

I would love to know any idea’s or workarounds for this.