‘RequestFactory::fromGlobals() cannot be called statically’ error on upgrading Nette

I’m currently doing a major upgrade on a Nette based website. We have multiple custom DI extensions, custom ORM and use the Nittro UI framework. So the upgrade is quite involved.
Going from PHP 7.2 -> 8.4 and Nette 2.2 -> 3.2. I have been able to solve tens of errors, but not this one.

I get Non-static method NetteHttpRequestFactory::fromGlobals() cannot be called statically error whenever I try to load a page. This error (according to Tracy) seems to be coming from the following segment of the auto-generated DI container:

public function createServiceHttp__request(): NetteHttpRequest
{
    return NetteHttpRequestFactory::fromGlobals();
}

The thing is, I don’t create the service anywhere, it’s Nette’s – and I guess, that it comes from NetteBridgesHttpDIHttpExtension line 56:

$request = $builder->addDefinition($this->prefix('request'))
            ->setFactory('@NetteHttpRequestFactory::fromGlobals');

I have tried going down ->setFactory – but I can’t even find it on the Definition class. More over I probably have misconfigured my debugger as it won’t stop on breakpoints in the cached container.

How do I fix this? Can I perhaps replace the http.request service with one of my own?

Thanks in advace!

This is part of my composer.json:

    "require": {
        "php": ">=8.4",
        "ext-pdo": "*",
        "ext-pdo_firebird": "*",
        "ext-curl": "*",
        "ext-json": "*",
        "ext-libxml": "*",
        "ext-simplexml": "*",
        "nette/application": "3.2.*",
        "nette/bootstrap": "3.2.*",
        "nette/forms": "3.2.*",
        "nette/http": "3.3.*",
        "nette/security": "3.2.*",
        "nette/di": ">=3.2",
        "nette/caching": "3.3.*",
        "nette/robot-loader": ">=4",
        "tracy/tracy": ">=3",
        "nittro/nette-bridges": "*",
        "symfony/console": ">=7.3",
        "latte/latte": ">=3",
        "jahudka/porm": "^0.1.0",
        "jahudka/component-events": "*"
    }

(some of the things are linked from forked repos, not the public versions)

How to Fetch Other Posts on Scroll Without AJAX(With Fetch API) and Jquery in WordPress? [closed]

I want to fetch other posts in WordPress. I can fetch next post on scroll. But when I go to latest post, it fetches nothing. When I go to the second latest post, on scroll it fetches only first post. When I go to the third latest post, it fetches only first and second latest posts. And so on. I want to fetch all posts on scroll, one by one.

<?php
$next_post = get_next_post();
  if ($next_post) :
    $next_post_url = get_permalink($next_post->ID);
?>
    <a id="next-post-link" href="<?php echo esc_url($next_post_url); ?>" 
       style="display: none;">
    </a>
<?php endif; ?>

JavaScript

document.addEventListener("DOMContentLoaded", function()
  {
  let loading = false;

  window.addEventListener("scroll", function()
    {
    let nextPostLink = document.getElementById("next-post-link");

    if (!nextPostLink || loading) return;

    let scrollPosition = window.innerHeight + window.scrollY;
    let documentHeight = document.documentElement.scrollHeight;

    if (scrollPosition >= documentHeight - 200) 
      {
      loading = true;
      let url = nextPostLink.href;

      fetch(url)
      .then(response => response.text())
      .then(data => 
        {
        let parser  = new DOMParser();
        let doc     = parser.parseFromString(data, "text/html");
        let newPost = doc.querySelector("#post-container .post");

        if (newPost) 
          {
          document.getElementById("post-container").appendChild(newPost);

          let newNextPostLink = doc.querySelector("#next-post-link");
          if (newNextPostLink) 
            {
            nextPostLink.href = newNextPostLink.href;
            } 
          else 
            {
            nextPostLink.remove(); // No more posts
            }

          // Update URL without reloading
          history.pushState(null, "", url);
          }

        loading = false;
        })
      .catch(error =>
        {
        console.error("Error fetching next post:", error);
        loading = false;
        });
      }
    });
  });

webserver is not working on systemd as a service [closed]

I have a php project and server , when i ran it through terminal by hitting
php -S 127.0.0.1:8000 it works fine but when i add it to systemd as a service , it guves me the following error :

May 30 15:45:32 srv714079 php[1309201]: [Fri May 30 15:45:32 2025] 127.0.0.1:45940 [500]: GET /scp/login.php - Uncaught Error: Call to undefined function osTicketMail_S() in /var/www/html/osticket/include/class.mailer.php:635 
May 30 15:45:32 srv714079 php[1309201]: Stack trace: May 30 15:45:32 srv714079 php[1309201]: #0 /var/www/html/osticket/include/class.mailer.php(673): osTicketMailMailer->send() 
May 30 15:45:32 srv714079 php[1309201]: #1 /var/www/html/osticket/bootstrap.php(342): osTicketMailMailer::sendmail() 
May 30 15:45:32 srv714079 php[1309201]: #2 /var/www/html/osticket/bootstrap.php(228): Bootstrap::croak() 
May 30 15:45:32 srv714079 php[1309201]: #3 /var/www/html/osticket/main.inc.php(28): Bootstrap::connect() 
May 30 15:45:32 srv714079 php[1309201]: #4 /var/www/html/osticket/scp/login.php(16): require_once('...') 
May 30 15:45:32 srv714079 php[1309201]: #5 {main} 
May 30 15:45:32 srv714079 php[1309201]:   thrown in /var/www/html/osticket/include/class.mailer.php on line 635 
May 30 15:45:32 srv714079 php[1309201]: [Fri May 30 15:45:32 2025] 127.0.0.1:45940 Closing

here is my service file

[Unit]
Description=OS Ticket  Web Server
After=network.target
[Service]
Type=simple
Environment="PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
Environment="LANG=en_US.UTF-8"
Environment="LC_ALL=en_US.UTF-8"
# Replace with your PHP files directory path
WorkingDirectory=/var/www/html/osticket
ExecStart=php -S 127.0.0.1:8000
#ExecStart=/usr/bin/php -S 127.0.0.1:8080 -t /var/www/html/osticket
Restart=always
RestartSec=3
# User to run the service (recommended: non-root user)
User=www-data
Group=www-data
Environment=USER=www-data HOME=/home/www-data
# Important for PHP environment
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target

tbh i am not sure what i am doing wrong so your help is so much appreciated

i tried to change user or play with environment variable or something like that but with no success

Error invoking PHP class which extends another

In a php page i want to use a class that extend another class, but i can’t.
I got Abb.php page like this

<?php
namespace NormalPage;
use CommonClassesAaa;
require "Aaa.php";

$xxx=new Abb();
$xxx->SayHelloB();
class Abb extends Aaa
{
    public function SayHelloB()
    {
        echo "Hello B";
    }
}

In the same directory i got the Aaa.php file liek this

<?php
namespace CommonClasses;
class Aaa
{
    public function SayHello()
    {
        echo "<html>Hello!</html>";
    }
}

When i browse Abb.php i got “Error: Class “NormalPageAbb” not found in Abb.php on line 6″.
If i modify “Abb.php” like this (Abb doesn’t extend Aaa anymore)

<?php
namespace NormalPage;
use CommonClassesAaa;
require "Aaa.php";

$xxx=new Abb();
$xxx->SayHelloB();
class Abb //extends Aaa (Abb does't extends Aaa)
{  
    public function SayHelloB()
    {        
        echo "Hello B";
    }
}

The page work correctly. Where is the mistake? I’d like to have a base class to extends in every page. I know it isn’t the best way to implement oop page in php, but i need to convert an old procedural site in a “little bit modern” style and i need to do this without say to my customer “no more implementation for a year, we must rewrite evrything”. I would like to “migrate” the site page by page.

Why is ngDoCheck() called again after ngAfterContentChecked() for both the AppComponent and ChildComponent during App startup?

I am using Angular 19. I have created a simple project to better understand the lifecycle hooks. I noticed that ngDoCheck() is called again after ngAfterContentChecked() for both the AppComponent and ChildComponent. Why is that so? This behavior is seen in both development and production mode.

Here is the source code for what I have tried:

app.component.html:


  <button (click)="incrementCounter()">Click Me</button>
  <app-child [value]="counter"></app-child>

app.component.ts:


  import { AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, Component, DoCheck, OnChanges, OnDestroy, OnInit, SimpleChanges } from '@angular/core';
  import { ChildComponent } from './child/child.component';

  @Component({
    selector: 'app-root',
    imports: [ChildComponent],
    templateUrl: './app.component.html',
    styleUrl: './app.component.scss'
  })
  export class AppComponent implements OnInit, OnChanges, OnDestroy, DoCheck, AfterContentInit, 
  AfterContentChecked, AfterViewInit, AfterViewChecked {

    constructor() {
      console.log('Inside AppComponent constructor()');
    }
    
    ngOnInit(): void {
      console.log('Inside AppComponent ngOnInit()');
    }

    ngOnDestroy(): void {
      console.log('Inside AppComponent ngOnDestroy()');
    }

    ngOnChanges(changes: SimpleChanges): void {
      console.log('Inside AppComponent ngOnChanges()');
    }

    ngDoCheck(): void {
      console.log('Inside AppComponent ngDoCheck()');
    }

    ngAfterContentInit(): void {
      console.log('Inside AppComponent ngAfterContentInit()');
    }
    
    ngAfterContentChecked(): void {
      console.log('Inside AppComponent ngAfterContentChecked()');
    }

    ngAfterViewInit(): void {
      console.log('Inside AppComponent ngAfterViewInit()');
    }
    
    ngAfterViewChecked(): void {
      console.log('Inside AppComponent ngAfterViewChecked()');
    }

    counter = 0;

    incrementCounter() {
      this.counter++;
    }

  }

child.component.html:


  <p>Counter value: {{ counterValue }}</p>

child.component.ts:


  import { Component, Input, SimpleChanges } from '@angular/core';

  @Component({
    selector: 'app-child',
    templateUrl: './child.component.html',
    styleUrl: './child.component.scss'
  })
  export class ChildComponent {

    constructor() {
      console.log('Inside ChildComponent constructor()');
    }
    
    ngOnInit(): void {
      console.log('Inside ChildComponent ngOnInit()');
    }

    ngOnDestroy(): void {
      console.log('Inside ChildComponent ngOnDestroy()');
    }

    ngOnChanges(changes: SimpleChanges): void {
      console.log('Inside ChildComponent ngOnChanges()');
    }

    ngDoCheck(): void {
      console.log('Inside ChildComponent ngDoCheck()');
    }

    ngAfterContentInit(): void {
      console.log('Inside ChildComponent ngAfterContentInit()');
    }
    
    ngAfterContentChecked(): void {
      console.log('Inside ChildComponent ngAfterContentChecked()');
    }

    ngAfterViewInit(): void {
      console.log('Inside ChildComponent ngAfterViewInit()');
    }
    
    ngAfterViewChecked(): void {
      console.log('Inside ChildComponent ngAfterViewChecked()');
    }

    @Input({alias: 'value'}) counterValue:number = 0;

  }

image gets into background,cant change image in elementor

cant change image in elementor,it gets into background

i tried to change image in elementor,it gets into background of that image.i have installed nevetheme and elementor,now i want to customise my site with elementor,i click on edit container,i tried to change the image,it gets into background of that image which i want to replace.so what to do?im using one of the templates of neve theme.so how can i replace this image.i want to create woocommerce site,with woocommerce plugin.
so it will be nice if you solve my problem.
i cant see any option in elementor where i can replace image.

LinguiJS: React app renders blank page after implementing dynamic locale activation with react-router

I’m implementing internationalization in my React (Vite) application using LinguiJS and react-router-dom. I’ve set up dynamic loading for language catalogs based on a URL parameter (/:language/your-route).

When I navigate to a localized URL (e.g., /en/dashboard or /es/dashboard), the page appears blank. There are no errors in the browser console, and no errors on my backend server.

// App.tsx
import React, { useEffect, useState } from 'react';
import { Routes, Route, useParams, useLocation, Navigate, Outlet } from 'react-router-dom';
import { i18n } from "@lingui/core";
import { I18nProvider, useLingui } from "@lingui/react";

export const supportedLocales = ['en', 'es'];
export const defaultLocale = 'en';

import { Dashboard } from './pages/Dashboard';
import { FamilyHub } from './pages/FamilyHub';
import Editor from './components/ui/Editor/Editor';
import { LoadScript } from '@react-google-maps/api';
import { AuthProvider } from './hooks/useAuth';

export async function dynamicActivate(localeToActivate: string): Promise<string> {
    let effectiveLocale = localeToActivate;
    let catalogMessages;

    if (!supportedLocales.includes(effectiveLocale)) {
        console.warn(`LinguiJS: Requested locale "${effectiveLocale}" is not supported. Falling back to "${defaultLocale}".`);
        effectiveLocale = defaultLocale;
    }

    if (i18n.locale === effectiveLocale && i18n.messages[effectiveLocale]) {
        console.log(`LinguiJS: Locale "${effectiveLocale}" is already active and messages are loaded.`);
        return effectiveLocale;
    }
    if (i18n.messages[effectiveLocale] && i18n.locale !== effectiveLocale) {
        i18n.activate(effectiveLocale);
        console.log(`LinguiJS: Activated pre-loaded locale: "${effectiveLocale}"`);
        return effectiveLocale;
    }

    console.log(`LinguiJS: Attempting to load messages for locale: "${effectiveLocale}"`);
    try {
        const module = await import(`../locale/${effectiveLocale}/messages.js`);
        catalogMessages = module.messages;
    } catch (e) {
        console.error(`LinguiJS: Failed to load messages for locale: "${effectiveLocale}"`, e);
        if (effectiveLocale !== defaultLocale) {
            console.warn(`LinguiJS: Attempting to load fallback locale: "${defaultLocale}"`);
            try {
                const fallbackModule = await import(`../locale/${defaultLocale}/messages.js`);
                catalogMessages = fallbackModule.messages;
                effectiveLocale = defaultLocale;
            } catch (fallbackError) {
                console.error(`LinguiJS: Failed to load fallback messages for locale: "${defaultLocale}"`, fallbackError);
                throw fallbackError;
            }
        } else {
            throw e;
        }
    }

    if (catalogMessages) {
        i18n.load(effectiveLocale, catalogMessages);
        i18n.activate(effectiveLocale);
        console.log(`LinguiJS: Dynamically loaded and activated locale: "${effectiveLocale}"`);
        return effectiveLocale;
    } else {
        const errorMsg = `LinguiJS: No messages found for locale ${effectiveLocale} after attempting load.`;
        console.error(errorMsg);
        throw new Error(errorMsg);
    }
}

const ActivateLanguage: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const { language: langFromParams } = useParams<{ language?: string }>();
    const location = useLocation(); // Re-trigger effect on any navigation
    const [activationState, setActivationState] = useState<'pending' | 'activating' | 'activated' | 'failed'>('pending');

    const { i18n: i18nContext } = useLingui(); 

    useEffect(() => {
        let isMounted = true;
        const targetLocale = (langFromParams && supportedLocales.includes(langFromParams)) 
                           ? langFromParams 
                           : defaultLocale;

        console.log(`[ActivateLanguage Effect] Target: ${targetLocale}, Current Context Locale: ${i18nContext.locale}, Param: ${langFromParams}`);

        if (i18nContext.locale === targetLocale && i18nContext.messages[targetLocale]) {
            console.log(`[ActivateLanguage Effect] Locale ${targetLocale} already active and loaded in context.`);
            if (isMounted) {
                setActivationState('activated');
            }
            return;
        }
        
        if (isMounted) {
            setActivationState('activating');
            setCurrentDisplayLocale(targetLocale);
        }

        dynamicActivate(targetLocale)
            .then((activatedLocale) => {
                if (isMounted) {
                    console.log(`[ActivateLanguage Effect] Dynamic activation successful for "${activatedLocale}". Global i18n.locale is now: ${i18n.locale}`);
                    setActivationState('activated');
                }
            })
            .catch((error) => {
                if (isMounted) {
                    console.error("[ActivateLanguage Effect] dynamicActivate failed.", error);
                    setActivationState('failed');
                }
            });
            
        return () => {
            isMounted = false;
        };
    }, [langFromParams, location.pathname, i18nContext.locale]); 

    const [currentDisplayLocale, setCurrentDisplayLocale] = useState(defaultLocale);
    useEffect(() => {
        setCurrentDisplayLocale((langFromParams && supportedLocales.includes(langFromParams)) ? langFromParams : defaultLocale);
    }, [langFromParams]);


    if (activationState === 'pending' || activationState === 'activating') {
        return <div>Loading translations for {currentDisplayLocale}...</div>;
    }

    if (activationState === 'failed') {
        return <div>Error loading translations. Please check console and refresh.</div>;
    }
    
    if (!i18nContext.locale || !i18nContext.messages[i18nContext.locale]) {
        console.error("ActivateLanguage Render: Critical - Context i18n.locale not set or messages not loaded despite 'activated' state. Current context locale:", i18nContext.locale);
        return <div>Language initialization incomplete after loading. Please refresh.</div>;
    }
    
    console.log(`[ActivateLanguage Render] Rendering children for locale: ${i18nContext.locale}`);
    return <>{children}</>;
};

const NavigateToLocalizedHub = () => {
    const { hubId } = useParams<{ hubId: string }>();
    return <Navigate to={`/${defaultLocale}/family-hub/${hubId}`} replace />;
};

function App() {
  return (
    <LoadScript 
      googleMapsApiKey="..."
      libraries={['places']}
      loadingElement={<div>Loading Google Maps...</div>}
    >
      <I18nProvider i18n={i18n}> {/* Provide the global i18n instance */}
        <Routes>
          <Route path="/:language" element={<ActivateLanguage><Outlet /></ActivateLanguage>}>
            <Route path="dashboard" element={<Dashboard />} />
            <Route path="family-hub/:hubId" element={
              <AuthProvider><FamilyHub /></AuthProvider>
            }/>
            <Route path="test" element={<Editor excludeButtons={["ol"]} />} />
          </Route>

          <Route path="/dashboard" element={<Navigate to={`/${defaultLocale}/dashboard`} replace />} />
          <Route path="/family-hub/:hubId" element={<NavigateToLocalizedHub />} />
          <Route path="/test" element={<Navigate to={`/${defaultLocale}/test`} replace />} />

          <Route path="/" element={<Navigate to={`/${defaultLocale}/dashboard`} replace />} />
          
          <Route path="*" element={
            <ActivateLanguage>
              <div>
                <h1>404 - Page Not Found</h1>
                <p>The page you are looking for does not exist. (This text should be translated)</p>
                <a href={`/${defaultLocale}/dashboard`}>Go to Homepage</a>
              </div>
            </ActivateLanguage>
          } />
        </Routes>
      </I18nProvider>
    </LoadScript>
  );
}

export default App;
  1. I’ve placed console.log(".."); statements at the very top of my App.tsx function, and at the top of my ActivateLanguage function.

  2. I initially tried statically importing all locales in App.tsx and then moved to a dynamic import() approach within dynamicActivate

How do I make my local storage preserve on reloads?

Whenever I click onto a new page on my website with my crt filter turned off, it says it saves the state and displays it in the ‘application space’ on the Dev Tools Page. But the visual of the page doesn’t show the correct state, rather it goes back to presenting the initial state “true” but doesn’t seem to update in the ‘application space’.

I have begun to learn Javascript and have gotten assistance with roughing out the code for this functionality in the past and while it kind of works, I require it to save it’s state and persist that state across webpages and reloads so the user doesn’t have to manually turn it off every time.

Here is a link to my site I’m trying to make this work on for reference:

https://the-rat-king-comic.neocities.org

Below is the raw code:

const targetElement = document.querySelector('body');

// set the toggle in localStorage when the button is clicked
document.querySelector('#class-toggle-button').addEventListener('click', e => {
  const hasClass = targetElement.classList.toggle("crt");
  localStorage.setItem('classApplied', hasClass);
})

// retrieve the toggle from localStorage when the page loads
if (localStorage.getItem('classApplied')) {
  targetElement.classList.add('crt');
}
@keyframes flicker {
  0% {
    opacity: 0.27861;
  }
  5% {
    opacity: 0.34769;
  }
  10% {
    opacity: 0.23604;
  }
  15% {
    opacity: 0.90626;
  }
  20% {
    opacity: 0.18128;
  }
  25% {
    opacity: 0.83891;
  }
  30% {
    opacity: 0.65583;
  }
  35% {
    opacity: 0.67807;
  }
  40% {
    opacity: 0.26559;
  }
  45% {
    opacity: 0.84693;
  }
  50% {
    opacity: 0.96019;
  }
  55% {
    opacity: 0.08594;
  }
  60% {
    opacity: 0.20313;
  }
  65% {
    opacity: 0.71988;
  }
  70% {
    opacity: 0.53455;
  }
  75% {
    opacity: 0.37288;
  }
  80% {
    opacity: 0.71428;
  }
  85% {
    opacity: 0.70419;
  }
  90% {
    opacity: 0.7003;
  }
  95% {
    opacity: 0.36108;
  }
  100% {
    opacity: 0.24387;
  }
}
  .crt::after {
  content: " ";
  display: block;
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background: rgba(18, 16, 16, 0.1);
  opacity: 0;
  z-index: 5;
  pointer-events: none;
  animation: flicker 0.15s infinite;
}
  .crt::before {
  content: " ";
  display: block;
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background: linear-gradient(rgba(18, 16, 16, 0) 50%, rgba(0, 0, 0, 0.25) 50%),
    linear-gradient(
      90deg,
      rgba(255, 0, 0, 0.06),
      rgba(0, 255, 0, 0.02),
      rgba(0, 0, 255, 0.06)
    );
  z-index: 5;
  background-size: 100% 2px, 3px 100%;
  pointer-events: none;
}
  .crt {
  animation: textShadow 1.6s infinite;
}
<body class="crt">

<button id="class-toggle-button">Crt Filter</button>

Thank you in advance for the help 🙂

How can I get an angle measurement between 2 user drawn line regardless of direction

I’ve been agonizing over this and can’t seem to figure it out. Not gonna lie I’m pretty new to programming and AI wrote most of this program. I am trying to measure the angle between sets of user drawn lines for an Ergo assessment. The goal is to measure the angle between key body points like spine, upper leg, lower arm etc, in relation to other lines. The user will take a picture of a person and then trace lines over their body and it will do some math and give them a score. All lines will be drawn by the user and each line has a specific reference line it uses. Now I’m able to get it to work, but only if the line is drawn in a specific way. But I have a feelings users will not read the instructions and break the app and they will get a inaccurate score which would be bad.

One of the hurdles is that I need to get a specific angle and that changes depending on how they draw the line. The number I get isn’t incorrect per say, just the wrong part of the measurement if that makes since(complimentary angles, etc.).

Say I make 2 lines and I need to get the angle between them, and if I do it in the right order I get the number I want; 60 degrees. But if I draw one or both of the lines “wrong” or not in the way I programmed for; I could get 130 degrees, -60, or -130 degrees. The assessment is strict on what kind of measurement it’s looking for. Let’s say any angle above 50 degrees gives you a value of 1, below 50 a value of 0. That measurement is above 50 degrees, but the program records -130 degrees so now it’s inaccurate. And this is a safety concern. In the code below this show the trunk angle, the spine, and the neck angle(which references the trunk). With a person standing straight up the trunk angle will be zero, any forward bending is a positive angle and backward bending is a negative angle. Which is why I have the user answer whether the subject facing forward or not, janky work around I know. The neck references the trunk and same thing applies; forward= + and backward = -.

function calculateAngle(point1, point2, toolType) {
// Create vector from point1 to point2 (in the order user drew them)
const vector = {
    x: point2.x - point1.x,
    y: point2.y - point1.y
};

// For trunk angle (reference is vertical)
if (toolType === 'trunk') {
    // Calculate trunk's absolute angle from vertical
    const trunkAngle = Math.atan2(vector.x, vector.y) * (180 / Math.PI);
    
    // We need to measure from North position (use complementary angle)
    let northAngle = 180 - Math.abs(trunkAngle);
    
    // Preserve original sign for direction
    if (trunkAngle < 0) northAngle = -northAngle;
    
    // Adjust based on subject facing direction
    if (subjectFacingDirection === 'right') {
        return northAngle; 
    } else { // 'left'
        return -northAngle; 
    }
}

// For neck angle
if (toolType === 'neck') {
    const trunkPoints = lines['trunk'];
    if (!trunkPoints || trunkPoints.length < 2) {
        console.error("Trunk must be drawn before neck");
        return 0;
    }
    
    // Trunk vector from tailbone to neck
    const trunkVector = {
        x: trunkPoints[1].x - trunkPoints[0].x,
        y: trunkPoints[1].y - trunkPoints[0].y
    };
    
    // Calculate dot product
    const dotProduct = vector.x * trunkVector.x + vector.y * trunkVector.y;
    
    // Calculate magnitudes
    const vectorMag = Math.sqrt(vector.x * vector.x + vector.y * vector.y);
    const trunkMag = Math.sqrt(trunkVector.x * trunkVector.x + trunkVector.y * trunkVector.y);
    
    // Calculate angle between vectors (0-180 degrees)
    let angle = Math.acos(dotProduct / (vectorMag * trunkMag)) * (180 / Math.PI);
    
    // Use cross product to determine direction
    const crossProduct = trunkVector.x * vector.y - trunkVector.y * vector.x;
    
    if (subjectFacingDirection === 'right') {
        angle = crossProduct < 0 ? angle : -angle;
    } else { // 'left'
        angle = crossProduct > 0 ? angle : -angle;
    }
    
    return -angle; // Negate the angle
}

So how can I make sure I can get the right angle number regardless of the order in which points are made or how the line is drawn.

Why did targets.some not return true and prevent repeat of coordinates generated?

Console output was as follows:

Targetting Pattern:  Random About Target
Grid Coordinates:  [ 20 , 10 ]
Salvo Coordinates:
21,12,
21,11,
17,8,
19,7,
21,12,  <<== duplicate
20,12,
20,7,
18,12,
21,8,
22,11   <<== duplicate

Code Extract (1st approach):
(using ‘some’ method)

function firePattern_onTargRand( col, row ){
    var firePattern = 'Random About Target' ;
    var target = [] ;
    var targets = [] ;
    var munitionsCost = 10 ;
    var alreadyTargetted = false ;

    for( i=1 ; i <= munitionsCost ; i++ ){
        do {
            target = [ 
                col + getRandomInteger( 0, 6 ) -3 ,
                row + getRandomInteger( 0, 6 ) -3
            ] ;
        } while( targets.some(element => element === target ) ) ;

        targets.push( target ) ;
    } ;

    console.log( "Targetting Pattern:  " + `${firePattern}` + "nGrid Coordinates:  [" + ` ${col} , ${row} ` + "]nSalvo Coordinates:n" + targets ) ;
    return targets ;
} ;

Code Extract (2nd approach):
(direct comparison of array elements in loop)

function firePattern_onTargRand( col, row ){
    var firePattern = 'Random About Target' ;
    var target = [] ;
    var targets = [] ;
    var munitionsCost = 10 ;
    var alreadyTargetted = false ;

    for( i=1 ; i <= munitionsCost ; i++ ){
        do {
            target = [ 
                col + getRandomInteger( 0, 6 ) -3 ,
                row + getRandomInteger( 0, 6 ) -3
            ] ;
            isDuplicate = false ;
            for( let i = 0 ; i < targets.length ; i++ ){
                    if( targets[i] == target ) {
                    isDuplicate = true ;
                } ;
            } ; 
        } while( isDuplicate === true ) ;

        targets.push( target ) ;
        } ;

    console.log( "Targetting Pattern:  " + `${firePattern}` + "nGrid Coordinates:  [" + ` ${col} , ${row} ` + "]nSalvo Coordinates:n" + targets ) ;
    return targets ;
} ;

Anyone know why I keep getting duplicates, when every pair of coordinates should be unique?

PS – I am very much a JavaScript novice.

Why is the error thrown with setTimeout not passed up to the parent try/catch block?

const fn2 = async (delay) => {
    return new Promise(resolve => setTimeout(() => { throw new Error("error") }, delay));
}

try {
  await fn2(1000);
} catch (err) {
  console.log("Rejected", err);
}
console.log("Finished.");

Please note, I am running this as a module (.mjs).

The only output I get (after 1000ms) is an error:

Error: error
at Timeout._onTimeout (file:///HelloWorld.mjs:2:60)
at listOnTimeout (node:internal/timers:581:17)
at process.processTimers (node:internal/timers:519:7)

If I am awaiting the promise, how come the try/catch block still isn’t catching the error?

It even seems to fail if I use .then .catch chaining:

fn2(1000).then(result => {
  console.log("Success", result);
})
.catch(error => {
  console.log("Rejected", error);
})

Error: error
at Timeout._onTimeout (file:///HelloWorld.mjs:2:60)
at listOnTimeout (node:internal/timers:581:17)
at process.processTimers (node:internal/timers:519:7)

This seems to be a nuance of setTimeout because if I change the code, the error is properly handled.

const fn2 = async (delay) => {
  // return new Promise(resolve => setTimeout(() => { throw new Error("error") }, delay));
  return new Promise(resolve => { throw new Error("error") });
}

Output:

Rejected Error: error
at file:///HelloWorld.mjs:3:41
at new Promise ()
at fn2 (file:///HelloWorld.mjs:3:10)
at file:///HelloWorld.mjs:7:9
at ModuleJob.run (node:internal/modules/esm/module_job:234:25)
at async ModuleLoader.import (node:internal/modules/esm/loader:473:24)
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:123:5) Finished.

Why doesn’t the try/catch block catch the rejected promise even when using await?

Ok, there’s a lot of questions and answers on this, but they don’t seem to jive with the following code:

const fn2 = async (delay) => {
    return new Promise(resolve => setTimeout(() => { throw new Error("error") }, delay));
}

try {
  await fn2(1000);
} catch (err) {
  console.log("Rejected", err);
}
console.log("Finished.");

Please note, I am running this as a module (.mjs).

The only output I get (after 1000ms) is an error:

Error: error
at Timeout._onTimeout (file:///HelloWorld.mjs:2:60)
at listOnTimeout (node:internal/timers:581:17)
at process.processTimers (node:internal/timers:519:7)

If I am awaiting the promise, how come the try/catch block still isn’t catching the error? And how is it that the program can be terminated at that point and never reach console.log("Finished.");?

I’m trying really hard to understand the behavior of unhandled exceptions within an asynchronous function and am expecting the top level try/catch to save me.

It even seems to fail if I use .then .catch chaining:

fn2(1000).then(result => {
  console.log("Success", result);
})
.catch(error => {
  console.log("Rejected", error);
})

Error: error
at Timeout._onTimeout (file:///HelloWorld.mjs:2:60)
at listOnTimeout (node:internal/timers:581:17)
at process.processTimers (node:internal/timers:519:7)

Why do I keep getting errors when attempting to get current position in JavaScript?

I have an html, css, js project with a map using leaflet. Sometimes location works but most of the time I get errors. Here is my JS code:

onst map = L.map('map').setView([30, 0], 3);
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'}).addTo(map);
const err = document.querySelector("#error");
const moodIcons = document.querySelectorAll(".mood-icon");
let currentLocation = null;

function getLocation() {
  
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(success, error, { maximumAge: 5000, timeout: 10000, enableHighAccuracy: true });
  }
  else {
    err.innerHTML = "Geolocation is not supported by this browser.";
  }

  return location;
}

function success(position) {
  
  currentLocation = [position.coords.latitude, position.coords.longitude]
  map.setView(currentLocation, 17);
}
  
function error(error) {
  console.log(error)
  err.innerHTML = "Please allow location permission to add a marker to the mood map";
}

// ---------------------------------------------------------------------------------------------

getLocation();

On Firefox I get this error:

Firefox error

On Chrome I get this error:

Chrome error example

When I open my html page in the browser I get prompted to allow location. When I click on allow Iocation permission the console immediately shows the error. have tried setting options for the getCurrentPosition method like a timeout but issue persists. The weird thing is that sometimes it will work. Without me even changing the code. Additionally, I get this error on Chrome only 127.0.0.1/:1 Network location provider at 'https://www.googleapis.com/' : Returned error code 429.

Why can I access objects that weren’t declared in the file? Only the classes were exported

So, I’m currently learning ESM and I was doing some practicing by exporting and importing two classes. In the file where I created the classes I also created two objects that are instances of those classes. In a second file, I imported both classes but NOT the instances,I then copied and pasted code from the first file into the second to test if the classes had imported and I forgot that I hadn’t exported the instances, but it still worked. Here is the first file.

//tests.js (file one)


export class Person{
    #age;
    constructor(name, age){
        this._name = name;
        this.#age = age;
    }
    

    get name(){
        return this._name;
    }

    intro(){
        console.log(`My name is ${this._name} and I am ${this.#age} years old`);
    }

    set changeName(newName){
        if(newName.length < 3 && typeof newName === 'string'){
            console.log('ERROR: Name cannot be less than 3 characters (Name remains unchanged)');
            return;
        }
        this._name = newName;
    }

    get age(){
        return this.#age;
    }

    birthday(){
        this.#age++;
    }
    

};

export default class Safe{
    #owner;
    #secret;
    #code;
    constructor(secret, code, owner){
        this.#secret = secret;
        this.#code = code;
        this.#owner = owner;
    }

    getSecret(code){
        if(code !== this.#code){
            console.log('!INCORRECT CODE!');
            return;
        }

        console.log(this.#secret);
    }

    get ownerHint(){
        return `Owner first two letters -> ${this.#owner[0]}${this.#owner[1]}`
    }

    changeCode(newCode, owner){
        if(owner[0] !== this.#owner[0]){
            console.log(`ERROR: OWNER VERIFICATION FAILED`);
            return;
        } 

        this.#code = newCode;


    }

}

const secret = new Safe('I have a cat!', 2818, 'Sam');

console.log(secret.ownerHint);
secret.getSecret(2818);
secret.changeCode(2817, 'Sam');
secret.getSecret(2817);


const sam = new Person('Sam', 21);
console.log(sam.age);
console.log(sam.name);
sam.intro();
sam.changeName= 'Sammy';
sam.birthday();
console.log(sam.age);
sam.intro();

Here is the second file (the file I imported both classes):

//test2.js

import Safe, { Person } from "./tests.js"

const newSafe = new Safe('I have a cat!', 2818, 'Sam');
const newPerson = new Person('Sam', 17);

//here is where the error is made, but for some reason IT WORKS? 
//the sam and secret instances are only declared in the tests.js file 

console.log(secret.ownerHint);
secret.getSecret(2818);
secret.changeCode(2817, 'Sam');
secret.getSecret(2817);



console.log(sam.age);
console.log(sam.name);
sam.intro();
sam.changeName = 'Sammy';
sam.birthday();
console.log(sam.age);
sam.intro();

How does the second file know of the existence of the “sam” and “secret” instance? Now, even more confusing than this, is that when I run the second file (node test2.js), the code runs fine until it reaches a point and then it just throws a reference error, “secret is not defined” here is the output

Owner first two letters -> Sa
I have a cat!
I have a cat!
21
Sam
My name is Sam and I am 21 years old
22
My name is Sammy and I am 22 years old
file:///home/javascript-projects/test2.js:8
console.log(secret.ownerHint);
            ^

ReferenceError: secret is not defined

How the hell does it go from outputting everything fine in both the “secret” and “sam” instances to then suddenly changing its mind and throwing an error. Why not just throw an error in the first place? Oh, and as I’m typing this I tried to test by removing all the code except for the import syntax, AND IT STILL WORKED except it didn’t throw a reference error.

How to set the field if changed in using TypeScript keyof?

I want to set the field if changed. I tried:

interface Foo {
  id: string;
  bar?: number
}
function setIfChanged(newProduct: Foo, existingProduct: Foo, key: keyof Foo): boolean {


  if (newProduct[key] !== existingProduct[key]) {
    existingProduct[key] = newProduct[key]; // error here
    console.log(`Product ${key} updated:`, newProduct);
    return true;
  }
  return false;
}
Type 'string | number | undefined' is not assignable to type 'never'. 
Type 'undefined' is not assignable to type 'never'

I don’t want to use // @ts-ignore or type assertion (as).