Can I extract performance by changing representation of GameStates from classes to TypedArrays in a Javascript solver?

Context :
I am making a solver for a board game in Javascript. The game is set on fixed sized grid with 5 robots and some of the cells marked as goals. The player has to find the minimum amount of moves to reach a set goal with one of the robots. My solver uses Breadth First Search because I want to find the best solution. The main loop is based a Queue to hold the GameStates that need to be looked at.

My issue :
As of right now, my solver can find solutions for a depth of up to around 9 moves (solving takes 4s at that depth). I’m trying to optimise my code to gain performance.

What I’ve already done :

  • I changed most of the Arrays into TypedArrays
  • I added a Map to memorise the GameStates that I have already seen (different orders of moves can lead to the exact same position which can be skipped)
  • I factored out some computaion outside the main loop for data that is needed very often like distances to walls.

What I want to try :

To better understand where performance was lost I took a look at the Chrome Performance Call Tree. From what I understand, it’s the GameState class that is very slow. To be fair I do create quite a lot of them but I feel I could gain from changing data structure here. Additionnaly, the main functions in my solver are quite fast in comparaison (solve which is the main loop, Move which computes a new GameState after playing a move and CheckWin which checks if a GameState is a valid solution)

My GameState class contains 2 fields :

  • robots which is a Uint8Array(10)
  • moves which is a Uint32Array(32)

I’m using low level datatypes like numbers and TypedArrays to represent positions, moves, robot colors and basically everything that I need to read/write while solving. The only things left that are a bit high level is the GameState class as well as the todoStates array used as the main Queue for BFS (see below).

My questions :

  • Will I gain performance by changing the GameState Queue into a single linearised TypeArray ?
  • Is there any better way to write a Queue in javascript ?
  • Are there any other optimisations I can make to improve performance ?
export function solve(board, startingState, goal, maxDepth){
    board = preComputeBoard(board);
    let seenStates = new Map();
    let todoStates = [startingState];
    let checks = 0;
    let stateId = -1;
    let numOfStates = 1;
    let startTime = Date.now();

    while(stateId + 1 < numOfStates){
        stateId++;
        let state = todoStates[stateId];
        
        if(state.moves[0] > maxDepth){continue;}

        let stateKey = EncodeRobots(state.robots);
        if(seenStates.has(stateKey)){continue;}
        seenStates.set(stateKey, true);

        checks++;
        if(state.CheckWin(board, goal)){
            console.log("checks", checks);
            console.log("loops", stateId);
            console.log("time", Date.now() - startTime);
            return state;
        }
        
        for(let move = 0; move < 20; move++){
            let newGameState = new GameState(state);
            newGameState.Move(board, 1 << move);
            todoStates.push(newGameState);
            numOfStates++;
        }

        todoStates[stateId] = null;
    }
    return false;
}

CORS Issues with Google OAuth Authentication in Production – React Frontend (Vercel) + Express Backend (Render)

I’ve built a full-stack CRM application with React frontend and Express backend. It uses Google OAuth for authentication:

Frontend: React app deployed on Vercel
Backend: Express.js REST API deployed on Render
Database: MongoDB Atlas
Authentication: Google OAuth 2.0
The application works perfectly in local development but fails in production with CORS errors and authentication login loops. After Google OAuth completes, it redirects back to my application, but the session cookie isn’t being maintained across redirects.
Error Messages
In the browser console:

xhr.js:139 Refused to set unsafe header "Origin"
xhr.js:139 Refused to set unsafe header "Origin"

Access to XMLHttpRequest at 'https://full-stack-crm-platform.onrender.com/api/customers?_t=1748716416363' from origin 'https://full-stack-crm-platform.vercel.app' has been blocked by CORS policy: Request header field pragma is not allowed by Access-Control-Allow-Headers in preflight response.

Access to XMLHttpRequest at 'https://full-stack-crm-platform.onrender.com/api/auth/current_user' from origin 'https://full-stack-crm-platform.vercel.app' has been blocked by CORS policy: Request header field pragma is not allowed by Access-Control-Allow-Headers in preflight response.

AuthContext.js:32 Authentication check failed

What Happens

  1. I click “Sign in with Google”
  2. Google OAuth process completes
  3. Redirects back to my application
  4. Cannot establish session (CORS errors)
  5. Remains on login page in a loop

What I’ve Tried

  1. Updated OAuth Callback URLs

// Fixed in passport.js

const callbackURL = process.env.NODE_ENV === 'production'
  ? `${process.env.BACKEND_URL}/api/auth/google/callback`
  : 'http://localhost:5000/api/auth/google/callback';
  1. Configured Cross-Domain Cookies

// In server.js

app.use(session({
  name: 'xeno.session',
  secret: process.env.SESSION_SECRET || 'dev-secret-key',
  resave: false,
  saveUninitialized: false,
  store: process.env.NODE_ENV === 'production'
    ? new MongoStore({ mongoUrl: process.env.MONGO_URI })
    : new session.MemoryStore(),
  cookie: {
    maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
    secure: process.env.NODE_ENV === 'production', // true in production
    httpOnly: true,
    sameSite: process.env.NODE_ENV === 'production' ? 'none' : 'lax'
  }
}));
  1. Configured CORS with Credentials

// In server.js

app.use(cors({
  origin: function(origin, callback) {
    // Allow requests with no origin or from allowed origins
    if (!origin || allowedOrigins.indexOf(origin) !== -1) {
      callback(null, true);
    } else {
      console.log('Unknown origin allowed:', origin);
      callback(null, true); // Currently allowing any origin for debugging
    }
  },
  credentials: true,
  exposedHeaders: ['Set-Cookie'],
  allowedHeaders: [
    'Content-Type', 'Authorization', 'X-Requested-With',
    'Origin', 'Accept', 'Cache-Control', 'X-PINGOTHER',
    'pragma', 'access-control-request-headers'
  ],
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
  maxAge: 86400
}));
  1. Frontend Axios Configuration

// In apiService.js

const apiService = axios.create({
  baseURL: process.env.REACT_APP_API_URL || 'http://localhost:5000',
  withCredentials: true,
  timeout: 15000
});

// Added request interceptor
apiService.interceptors.request.use(
  config => {
    // Set explicit origin header
    config.headers['Origin'] = window.location.origin;
    console.log('Making request to:', config.url, 'with headers:', config.headers);
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
  1. Enhanced OAuth Callback Handling

// In authRoutes.js

app.get('/api/auth/google/callback', 
  passport.authenticate('google', { failureRedirect: '/login' }),
  (req, res) => {
    // Force session save before redirect
    req.session.save(err => {
      if (err) {
        console.error('Session save error:', err);
      }
      console.log('Session saved, redirecting to frontend with logged in user:', 
        req.user ? req.user.email : 'unknown');
        
      // Add CORS headers to redirect response
      res.header('Access-Control-Allow-Origin', process.env.FRONTEND_URL);
      res.header('Access-Control-Allow-Credentials', 'true');
      
      res.redirect(`${process.env.FRONTEND_URL}?auth=success&user=${req.user?.email}`);
    });
  }
);
  1. Added Frontend Session Establishment Logic

// In DashboardPage.js

const location = useLocation();
const [authProcessing, setAuthProcessing] = useState(false);

// Handle OAuth redirect with query parameters
useEffect(() => {
  const query = new URLSearchParams(location.search);
  const authSuccess = query.get('auth') === 'success';
  
  if (authSuccess && !authProcessing) {
    setAuthProcessing(true);
    console.log('OAuth redirect detected, establishing session...');
    
    // Call backend to establish session cookie
    apiService.get('/api/auth/current_user')
      .then(response => {
        console.log('Session established:', response.data);
        // Clear URL parameters
        window.history.replaceState({}, document.title, window.location.pathname);
        setAuthProcessing(false);
      })
      .catch(error => {
        console.error('Failed to establish session:', error);
        setAuthProcessing(false);
      });
  }
}, [location, authProcessing]);
  1. Added CORS Proxy for External API Calls

// In server.js

app.get('/proxy', async (req, res) => {
  try {
    const targetUrl = req.query.url;
    if (!targetUrl) {
      return res.status(400).json({ error: 'Missing URL parameter' });
    }
    
    // Forward request to target URL with CORS headers
    // ... rest of proxy implementation
  } catch (error) {
    console.error('CORS Proxy error:', error);
    res.status(500).json({ error: 'CORS Proxy error' });
  }
});

Environment Variables (Backend – Render)

NODE_ENV=production
BACKEND_URL=https://full-stack-crm-platform.onrender.com
FRONTEND_URL=https://full-stack-crm-platform.vercel.app
MONGO_URI=mongodb+srv://...
SESSION_SECRET=...
GOOGLE_CLIENT_ID=...
GOOGLE_CLIENT_SECRET=...

Questions:

  1. Why is the session cookie not persisting after the Google OAuth redirect in production?
  2. What is causing the CORS “pragma” header issue and how can I properly fix it?
  3. Is there anything specific to Vercel + Render deployments that I’m missing?
  4. Could there be issues with my cookie configuration for cross-domain usage?
    Any help would be greatly appreciated as I’ve been stuck on this for days!

Browser Console and login page

Render Logs 1

Render logs 2

simulate hover with tap in mobile browser, click with second tap (no jquery)

I’m using raw javascript to switch classes for a hover effect for linked elements on a website but I need to modify that to also have a tap simulate the hover effect on touch-enabled devices, and then have the second tap fire the link

There have been many solutions for this using jquery, but I’m trying to avoid jquery to keep things light and simple, but so far my feeble attempts to modify the non-touch script have failed.

Here’s my current script, which adds/removes the class “on” to linked elements with the class “homepage-nav”. I basically need to do the same thing for touch-enabled devices, adding the class “on” with the first tap but preventing the link from firing until the second tap.

window.addEventListener("load", () => {
  let items = document.querySelectorAll(
    ".change-background .container .homepage-nav"
  );

  items.forEach((item) => {
    item.addEventListener("mouseover", () => {
      items.forEach((item) => {
        item.classList.remove("on");
      });
      item.classList.add("on");
    });
  });
});

Is it a case of simply wrapping it in the event listener “touchstart” and then using “preventdefault” to stop click propagation after the first tap? Something like this:

  items.forEach((item) => {
    item.addEventListener("touchstart", () => {
      items.forEach((item) => {
        item.classList.remove("on");
      });
      item.classList.add("on");
      item.preventDefault();
      return false;
    });
  });

How to create a functioning “tab” element in HTML Text Editor (e.g. TinyMCE)

I’m attempting to create a tab-like element in a React TinyMCE Text Editor that doesn’t glitch. Ideally it works like a tab does in Microsoft Word, as I’m using the editor to edit transcriptions into reports.

There is a nonbreaking plugin but it glitches (particularly when having the text selected for whatever editing purpose). So I’m bashing my way around to create a custom tab element that doesn’t break the flow of typing when it happens to be selected.

So far I have done the following which kind of works but it’s glitchy. When the typist comes across it, it may get grab the focus of the cursor and not allow many keys to work normally. Or it may just work as it should. Anyway, it’s not as smooth as one gets in Microsoft Word which is annoying.

.mce-tab {
   display: inline-block;
   width: 3ch;
   min-width: 3ch;
   white-space: nowrap;
   user-select: none;
   font: inherit;
   color: inherit;
   background: none;
   pointer-events: auto;
}
export const HTML_TAB = `
<span style="font-family: inherit;">
   <span 
      class="mce-tab"
      contenteditable="false"
   >
      &nbsp;
   </span>
</span>
`;

const handleTab = (editor) => {
   editor.on("keydown", (event) => {
      const { key } = event;
      if (key === 'Tab') {
         // Entering in the custom 'tab'-like element
         event.preventDefault();
         editor.insertContent(HTML_TAB);
      } else {
         // Check if the 'tab' is in the selection and write over it as applicable
         const sel = editor.selection;
         const node = sel.getNode();
         if (node) {
            const tabSpan = node.closest?.('.mce-tab');
            if (tabSpan) {
               const isPrintableKey = event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey;
               if (isPrintableKey) {
                  // Replace content and set cursor to appropriate point
                  event.preventDefault();
                  const charNode = document.createTextNode(key);
                  tabSpan.replaceWith(charNode);
                  const range = document.createRange();
                  range.setStartAfter(charNode);
                  range.collapse(true);
                  editor.selection.setRng(range);
               }
            }
         }
      }
   });
}

Any help or advice on creating an actually working ‘tab’ like feature will be appreciated.

Is inheritance of HTML attributes being updated when using the setAttribute() method?

I’m currently working on a semi-automatic multilingual system for websites created with Publii.
Now I wanted to update the lang attribute of the site’s html element according to a variable I’ve saved in LocalStorage.

I’ve put this <script> block at the end of the site’s body:

<script type="text/javascript" defer>
//<![CDATA[
    const currentLang = localStorage.getItem("currentLang") || "de";
    localStorage.setItem("currentLang", currentLang);
    document.getElementsByTagName("html")[0].setAttribute("lang", currentLang);
    langChange(currentLang);
//]]>
</script>

(the langChange() method changes the language of the site’s content).

I already confirmed that this successfully updates the lang attribute of the html element. But now I’m wondering if this actually does something, because even though the lang attribute gets inherited by every element on the site, I cannot verify if it actually works or if in the end just the html element has an updated lang tag and every other element persists with the old/default one.

Lastly I’m not quite sure if it makes a difference if there already is a lang tag or if the setAttribute() method needs to create a new one.

Protected Routes from Log In Page (React Native)

I am currently developing a mobile application with the backend using Appwrite. The issue I am facing is that, after successfully logging in and pressing the pressable “Log In”, I need to reload the app to be redirected into the main pages of the app, is it because when the screen is rendered the user state has not been updated yet? If so how can I fix it. Any help is greatly appreciated.

This is my GuestOnly component which I am wrapping all the files of the main pages in.

import { useRouter } from "expo-router"
import { useUser } from "../../hooks/useUser"
import { useEffect } from "react"
import ThemedLoader from "../ThemedLoader"

const GuestOnly = ({ children }) => {
    const { user, authChecked } = useUser()
    const router = useRouter()

    useEffect(() => {
    if (authChecked && user !== null) {
        router.replace('/profilepage');
    }
    }, [user, authChecked])

    if (!authChecked || user) {
        return (
            <ThemedLoader/>
        )
    }
    
    return children
}

export default GuestOnly

This is my UserContext file where I created the log in function

import { createContext, useState, useEffect } from "react";
import { account } from "../lib/appwrite"
import { ID } from "react-native-appwrite"

export const UserContext = createContext();

export function UserProvider({ children }) {
    const [user, setUser] = useState(null)
    const [authChecked, setAuthChecked] = useState(false)

    
    async function login(email, password) {
        try {
          await account.createEmailPasswordSession(email, password)
          //const response = await account.get()
          //setUser(response)
          await getInitialUserValue()
        } catch (error) {
          throw Error(error.message)
        }
    }

    async function register(email, password) {
      try {
      // Check if user is already logged in
        const current = await account.get();
      
      if (current) {
        throw new Error("You are already logged in. Please log out before registering a new account.");
      }
    } catch (error) {
      // If not logged in, Appwrite throws error with code 401 (unauthorized)
      if (error.code !== 401) {
        throw new Error(error.message);
      }
    }

    try {
      await account.create(ID.unique(), email, password);
      await login(email, password);
    } catch (error) {
      if (error.code === 409) {  // 409 is usually "Conflict" for duplicate
      throw new Error("This email is already registered. Please log in or use another email.");
      }
      throw new Error(error.message);
    }
  }

    async function logout() {
      await account.deleteSession("current")
      setUser(null)
    }

    async function getInitialUserValue() {
    try {
      const res = await account.get()
      setUser(res)
    } catch (error) {
      setUser(null)
    } finally {
      setAuthChecked(true)
    }
  }

  
  useEffect(() => {
    getInitialUserValue()
  }, [])

    return (
        <UserContext.Provider value ={{ user, login, register, logout, authChecked }}>
          {children}
        </UserContext.Provider>
    )
}

This is my login page file

import { View, Text, TextInput, Pressable, StyleSheet, Keyboard, TouchableWithoutFeedback } from 'react-native';
import { useRouter } from 'expo-router';
import { useState, useEffect } from 'react';
import { useUser } from '../../hooks/useUser';

export default function LoginPage() {
  const router = useRouter();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState(null);

  const { user, login } = useUser();

  const handleSubmit = async () => {
    setError(null);
    const emailRegex = /^[^s@]+@[^s@]+.[^s@]+$/;
    if (!emailRegex.test(email)) {
      setError('Please enter a valid email address.');
      return;
    }

    try {
      await login(email, password);
    } catch (error) {
      setError(error.message);
    }
  };

  return (
    <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
      <View style={styles.overlay}>
        <Text style={styles.title}>Welcome Back</Text>

        <TextInput 
          placeholder="Email" 
          placeholderTextColor="#999"
          style={styles.input} 
          onChangeText={setEmail}
          value={email} 
        />

        <TextInput 
          placeholder="Password"
          placeholderTextColor="#999"
          onChangeText={setPassword}
          value={password}
          secureTextEntry 
          style={styles.input}
        />

        <Pressable style={styles.button} onPress={handleSubmit}>
          <Text style={styles.buttonText}>Log In</Text>
        </Pressable>

        <View style={{ width: '100%', height: 60 }}>
          {error && <Text style={styles.error}>{error}</Text>}
        </View>

        <Pressable style={styles.registerButton} onPress={() => router.push('/')}>
          <Text style={styles.registerText}>← Back To Start</Text>
        </Pressable>

        <Pressable style={styles.registerButton} onPress={() => router.push('/signuppage')}>
          <Text style={styles.registerText}>Register Instead</Text>
        </Pressable>
      </View>
    </TouchableWithoutFeedback>
  );
}

const styles = StyleSheet.create({
  overlay: {
    flex: 1,
    backgroundColor: '#FAF3DD',
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 24,
  },
  title: {
    fontSize: 32,
    fontWeight: '700',
    color: '#333',
    marginBottom: 28,
  },
  input: {
    width: '100%',
    borderWidth: 1,
    borderColor: '#ccc',
    backgroundColor: '#fff',
    color: '#333',
    padding: 14,
    borderRadius: 10,
    marginBottom: 16,
    fontSize: 16,
  },
  button: {
    backgroundColor: '#FF8C42',
    padding: 14,
    borderRadius: 10,
    alignItems: 'center',
    width: '100%',
    shadowColor: '#000',
    shadowOpacity: 0.15,
    shadowOffset: { width: 0, height: 2 },
    shadowRadius: 3,
    marginBottom: 16,
  },
  buttonText: {
    color: '#fff',
    fontWeight: '600',
    fontSize: 16,
  },
  error: {
    color: '#fff',
    backgroundColor: '#D9534F',
    padding: 10,
    borderRadius: 6,
    textAlign: 'center',
  },
  registerButton: {
    marginTop: 8,
    paddingVertical: 10,
    paddingHorizontal: 20,
    borderColor: '#FF8C42',
    borderWidth: 1,
    borderRadius: 8,
    backgroundColor: '#fff8f1',
  },
  registerText: {
    color: '#FF8C42',
    fontSize: 14,
    fontWeight: '600',
    textAlign: 'center',
  },
});

Trouble Scraping Codeur.com — Are JavaScript or Anti-Bot Measures Blocking My Script?

I’ve been trying to scrape the project listings from Codeur.com using Python, but I’m hitting a wall — I just can’t seem to extract the project links or titles.

Here’s what I’m after: links like this one (with the title inside):

Acquisition de leads

Pretty straightforward, right? But nothing I try seems to work.

So what’s going on?
At this point, I have a few theories:

JavaScript rendering: maybe the content is injected after the page loads, and I’m not waiting long enough or triggering the right actions.

Bot protection: maybe the site is hiding parts of the page if it suspects you’re a bot (headless browser, no mouse movement, etc.).

Something Colab-related: could running this from Google Colab be causing issues with rendering or network behavior?

Missing headers/cookies: maybe there’s some session or token-based check that I’m not replicating properly.

What I’d love help with
Has anyone successfully scraped Codeur.com before?

Is there an API or some network request I can replicate instead of going through the DOM?

Would using Playwright or requests-html help in this case?

Any idea how to figure out if the content is blocked by JavaScript or hidden because of bot detection?

If you have any tips, or even just want to quickly try scraping the page and see what you get, I’d really appreciate it.

What I’ve tested so far

  1. requests + BeautifulSoup
    I used the usual combo, along with a user-agent header to mimic a browser. I get a 200 OK response and the HTML seems to load fine. But when I try to select the links:

soup.select(‘a[href^=”/projects/”]’)

I either get zero results or just a few irrelevant ones. The HTML I see in response.text even includes the structure I want… it’s just not extractable via BeautifulSoup.

  1. Selenium (in Google Colab)
    I figured JavaScript might be involved, so I switched to Selenium with headless Chrome. Same result: the page loads, but the links I need just aren’t there in the DOM when I inspect it with Selenium.

Even something like:

driver.find_elements(By.CSS_SELECTOR, ‘a[href^=”/projects/”]’)

returns nothing useful.

How to Prevent Session Conflicts in a Node.js Backend with SQL Server and Multiple Users? [closed]

I have a Node.js backend running for an Angular application hosted on IIS, where each user logs in using their own SQL Server credentials. When multiple users are logged in simultaneously, I found an issue: users are receiving data meant for other users, as if the database connection is being shared or overwritten. We’re currently using the mssql package to manage connections. Is there any way to prevent this kind of cross-user conflict?

I initially tried using express-session to manage sessions, but it led to domain-related issues where cookies couldn’t be saved or accessed properly—likely due to CORS restrictions between the Angular frontend hosted on IIS and the Node.js backend.
Next, I implemented custom session handling using headers that included a session ID. This required reconnecting to the SQL Server database on every API call, which I did not want because I don’t store user passwords for security reasons. Therefore, reconnecting is not possible.

whatsapp and tawk buttons positioning in tablet

whatsapp tablet

Hello,

We have a website that tawk and whatsapp buttons are available on the right corner. Tawk icon is placed automatically by its auto-code and we just position the whatsapp button manually using Google Tag Manager however in tablet version the positioning of the WhatsApp button are ruined even though on desktop and vertical mobile version it is smooth and work as how it should be.

I would be very happy if you can kindly help how we can fix this issue ?

You can have a look at the site on following address:
https://meletiorient.myikas.com

Thank you very much.

react-navigation error: viewmanagerresolver returned null for either RNSScreenContentWrapper or RCTRNSScreenContentWrapper

I am Trying to Add Navigation in My React Native App and I am Getting this Error?

This is My Navigation Code:-

const Stack = createNativeStackNavigator()

function App(): React.JSX.Element {
  // return(
  //   <MainScreen />
  // )
  return(
      <NavigationContainer>
        <Stack.Navigator initialRouteName='Main'>
          <Stack.Screen name='Main' component={MainScreen} />
          <Stack.Screen name='Detail' component={DetailScreen} />
        </Stack.Navigator>
      </NavigationContainer>
  )
}


export default App;

even I Add Dependencies that Needed for Navigation. here is My Dependencies:-

"dependencies": {
    "@react-navigation/native": "^7.1.9",
    "@react-navigation/native-stack": "^7.3.13",
    "@types/react-native-vector-icons": "^6.4.18",
    "react": "19.0.0",
    "react-native": "0.79.2",
    "react-native-reanimated": "^3.18.0",
    "react-native-safe-area-context": "^5.4.1",
    "react-native-screens": "^4.11.1",
    "react-native-vector-icons": "^10.2.0"
  },

This is the link of same question you can Look for What Error I am getting but I didn’t Find the Solution Link

When I Return and Run <MainScreen /> Instead of <NavigationContainer /> then it Works Fine?

even I Run App Again even I clean the .gradlew clean even I Start the Node Server with --reset-cache but Still getting the Same Error.

I Also Added This in android/app/src/main/java/com/firstreactnativeproject/MainActivity.kt :-

import android.os.bundle

override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(null)
}

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.