Timer-based primary key for synching algorithm

This one produces collision:


(() => {
    const a = [];
    for (let i = 0; i < 20_000; ++i) {
        const pk = Date.now();
        a.push(pk);
    }
    const uniqueItems = new Set(a);
    console.log(a.length, uniqueItems.size); // 20000 3
    console.log(a.length === uniqueItems.size); // false
})();

Is there a possibility of collision of primary keys even if I multiply the now() (millisecond accurate) to 1,000?

(() => {
    const a = [];
    for (let i = 0; i < 20_000; ++i) {
        const pk = Date.now() * 1_000 + i;
        a.push(pk);
    }
    const uniqueItems = new Set(a);
    console.log(a.length, uniqueItems.size); // 20000 20000
    console.log(a.length === uniqueItems.size); true
})();

The timer-based primary key will be used for syncing data to multiple devices to ensure efficiency. Only the data from the last synced time and forward will be pulled from the server on the succeeding syncs.

get variable in callback (by axios) [duplicate]

I have script like this,

   for (var i = 0; i < 10;i++){   
          axios.get(url).then(res=>{
              console.log("product connection success",i);
                                        
          }).catch(res=>{
              console.log("product connection error",res);
         });
            
   }

Always i returns 10, because this callback is called after i loop finished.

However I want to get the i when axios.get is called.

Is it possible? or how can I passed the certain data to callback?

How to render components exported from mdx in Astrojs?

I got a mdx file like this and I want to render the foo component in somewhere else.

---
title: Hi, World!
---

export const title = 'My first MDX post'
export const foo = <h1>adsf</h1>

# {title}

by

---
const matches = await Astro.glob('../../content/blog/*.mdx');

const foo = matches[0].foo
---

I got

{
  'astro:jsx': true,
  type: 'h1',
  props: { children: "adsf" },
  [Symbol(astro:renderer)]: 'astro:jsx'
}

Is it possible to render it in .astro? both {foo} and <foo/> not works

Cannot render radial graph with phylotree.min.js

I have been trying for the past few weeks to get phylotree.min.js to render data as a radial phylogenetic circular tree, like here. So far I have tried writing it from scratch and everyone online says I should use phylotree. However, I cannot even initialize it properly without getting an error relating to the object not being callable.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Radial Circular Phylogenetic Tree</title>
    <script src="https://d3js.org/d3.v4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/phylotree.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #f9f9f9;
            height: 100vh;
        }

        #tree-container {
            width: 800px;
            height: 800px;
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <div id="tree-container"></div>
    <script>
        const newick = `((Grandchild1_1,Grandchild1_2)Child1,(Grandchild2_1,(GreatGrandchild2_2_1,GreatGrandchild2_2_2)Grandchild2_2)Child2)Root;`;

        const tree = new phylotree.phylotree(newick, {
            type: "circular"
        });

        tree.render({
            container: "#tree-container",
            width: 800,
            height: 800,
            layout: "radial", 
            "left-right-spacing": "fit-to-size",
            "top-bottom-spacing": "fit-to-size"
        });

        d3.selectAll(".node circle")
            .attr("r", 5)
            .style("fill", "#4285f4");

        d3.selectAll(".branch")
            .style("stroke", "#aaa")
            .style("stroke-width", "1.5px");

        d3.selectAll(".node text")
            .style("font-size", "10px")
            .style("fill", "#333");
    </script>
</body>
</html>

However, I cannot even get the graph to render. I’ve revised the code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Radial Circular Phylogenetic Tree</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/phylotree.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #f9f9f9;
            height: 100vh;
        }

        #tree-container {
            width: 800px;
            height: 800px;
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <div id="tree-container"></div>
    <script>
        // Define the Newick string
        const newick = `((Grandchild1_1,Grandchild1_2)Child1,(Grandchild2_1,(GreatGrandchild2_2_1,GreatGrandchild2_2_2)Grandchild2_2)Child2)Root;`;

        // Ensure compatibility between phylotree.js and D3.js v7
        // Replace extend with Object.assign if necessary
        if (typeof ___namespace !== 'undefined' && typeof ___namespace.extend === 'undefined') {
            ___namespace.extend = Object.assign; // Polyfill for extend
        }

        // Initialize the phylogenetic tree
        const tree = new phylotree.phylotree(newick, { type: "circular" });

        // Render the tree in the specified container
        tree.render({
            container: "#tree-container", // Match container ID
            layout: "radial",
            width: 800,
            height: 800,
        });

        // Style nodes and branches for better visibility
        d3.selectAll(".node circle").attr("r", 5).style("fill", "black");
        d3.selectAll(".branch").style("stroke", "black").style("stroke-width", "1px");
    </script>
</body>
</html>

but I get the errors:

phylotree.js:4263 Uncaught TypeError: ___namespace.extend is not a function
    at phylotree.js:4263:16
    at phylotree.js:4:78
    at phylotree.js:5:2

test_newick.html:40 Uncaught TypeError: phylotree.phylotree is not a constructor
    at test_newick.html:40:22 

Customising Stockfish chess engine play

I have made a Stockfish-js engine web app but am adding an option to force the engine to play a user chosen move after the human user makes a first move (currently 1.e4 & where the user can choose 1…e5/1…e6/1…c6/1…d6 or Stiockfish book move) by clicking a btn. I am not an experienced webdev programmer or chess programmer & the code for this feature only works till move 3, when Stockfish chess engine stops & does not make a third move reply & ciontinue the game.Why? I feel like the comic Disney character Forky… I don’t know!? Can anyone help please find why stockish stops after move 3 & the game cannot continue. Most grateful for any helpful advice, thank you

import { Chess } from "https://cdnjs.cloudflare.com/ajax/libs/chess.js/0.13.4/chess.js";

var game = new Chess();
var board = null;
var firstMoveChosen = false; // Flag for user's choice of engine reply
var userHasMoved = false; // Flag for user move status

// Initialize Stockfish engine worker
var stockfish = new Worker("stockfish.js");

// Event listener for Stockfish's response
stockfish.addEventListener("message", function (e) {
  if (e.data.startsWith("bestmove")) {
    var bestMove = e.data.split(" ")[1];

    if (bestMove && (firstMoveChosen || userHasMoved)) {
      const move = {
        from: bestMove.slice(0, 2),
        to: bestMove.slice(2, 4),
        promotion: "q", // Assuming always promoting to a queen
      };

      // Apply the move and reset flags as needed
      game.move(move);
      board.position(game.fen());
      updateStatus();

      // Reset flags
      firstMoveChosen = false;
      userHasMoved = false;

      // Trigger the engine's next move if the game continues
      if (!game.game_over() && game.turn() === "b") {
        setTimeout(() => {
          stockfish.postMessage("position fen " + game.fen());
          stockfish.postMessage("go depth 15");
        }, 1000); // Added delay for realistic play pace
      }
    }
  }
});

// Handle user making a move
function onDrop(source, target) {
  var move = game.move({
    from: source,
    to: target,
    promotion: "q", // NOTE: always promote to a queen for simplicity
  });

  // Illegal move
  if (move === null) return "snapback";

  updateStatus();
  userHasMoved = true; // Set flag indicating the user has moved

  // Trigger engine to play after the user's move if the game is ongoing
  if (!game.game_over()) {
    setTimeout(() => {
      stockfish.postMessage("position fen " + game.fen());
      stockfish.postMessage("go depth 15");
    }, 1000); // Added delay for realistic play pace
  }
}

function onSnapEnd() {
  board.position(game.fen());
}

function updateStatus() {
  var status = "";
  var moveColor = "White";
  if (game.turn() === "b") {
    moveColor = "Black";
  }

  // Check game over conditions
  if (game.in_checkmate()) {
    status = "Game over, " + moveColor + " is in checkmate.";
  } else if (game.in_draw()) {
    status = "Game over, drawn position";
  } else {
    status = moveColor + " to move";
    if (game.in_check()) {
      status += ", " + moveColor + " is in check";
    }
  }

  // Update status, FEN, and PGN
  document.getElementById("status").innerText = status;
  document.getElementById("fen").innerText = game.fen();
  document.getElementById("pgn").innerText = game.pgn();
}

That’s it-engine function control-rather,lack of it, to achieve this engine forcing move customisation on move 1 with Stockfish as Black & after Wghite chooses Black’s reply game engine play should continue normally.I struggle to understand this level of coding & was pleased to get Stockfish working in my simple web app & this is pushed beyond my comfort level, although I know there are many good programmers who will have a good grasp of this & hope can answer this positively.

“Syntax error in textmermaid version 11.4.0” when using mermaid.render

Im getting this render error when using mermaid.render. Note that the render size is capped too.

The code:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script type="module" src="main.js"></script>
    
    <pre id="my-diagram" class="mermaid"></pre>
</body>
</html>

main.js

import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';

mermaid.initialize({ startOnLoad: false });

var target = document.getElementById('my-diagram')
const graphDefinition = 'graph TBna-->b';

mermaid.render('my-diagram', graphDefinition, target);

this is an error i encapsulated in this example, but i had it in a Angular Project and there i can render a diagram simply using a element, but it only renders using the inner html of it.

How do I open a dialog to select a file using Electron?

I’m trying to link a button to opening a dialog to select a file but I’m not succeeding, when I click on the button nothing happens…

I expected that clicking the button would open the OS’s native dialog to select a file.

My code:

<div class="tools-header">
    <h2>Tools</h2>
</div>
<div class="form-group">
    <label for="game-directory">Arquivo do Jogo</label>
    <div class="input-group">
        <input type="text" class="form-control" id="game-directory" readonly />
        <button class="btn btn-dark" id="explore-btn">Explorar...</button>
        <input type="file" id="file-selector" style="display: none;" />
    </div>
    <small id="file-path"></small>
</div>

<script>
    const gameDirectoryInput = document.getElementById('game-directory');
    const exploreButton = document.getElementById('explore-btn');
    const fileSelector = document.getElementById('file-selector');
    const filePath = document.getElementById('file-path');

    exploreButton.addEventListener('click', () => {
        fileSelector.click(); 
    });

    fileSelector.addEventListener('change', (event) => {
        if (event.target.files.length > 0) {
            const selectedFile = event.target.files[0];
            gameDirectoryInput.value = selectedFile.name; 
            filePath.textContent = `Arquivo selecionado: ${selectedFile.name}`; 
        } else {
            gameDirectoryInput.value = ''; 
            filePath.textContent = ''; 
        }
    });
</script>

mariadb npm package database keeps timing out even if it’s under no load

I have a query function that takes an sql and executes it, like this:

import mariadb, { QueryOptions } from "mariadb";

const pool = mariadb.createPool({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    acquireTimeout: 30000,
    connectTimeout: 10000,
    idleTimeout: 60000,
});

export async function query(sql: string | QueryOptions, values?: Array<unknown>) {
    let conn;
    try {
        console.log("Attempting to get a connection from the pool...");
        conn = await pool.getConnection();
        console.log(`Connection acquired. Active connections: ${pool.activeConnections()}, Idle connections: ${pool.idleConnections()}`);

        console.log("Executing query...");
        const rows = await conn.query(sql, values);

        console.log("Query executed successfully:", rows);
        return rows;
    } catch (e) {
        console.error("Error executing query:", e);
        throw e;
    } finally {
        if (conn) {
            console.log("Releasing connection back to the pool...");
            await conn.release();
            console.log(`Connection released. Active connections: ${pool.activeConnections()}, Idle connections: ${pool.idleConnections()}`);
        }
    }
}

process.on("SIGINT", async () => {
    console.log("Closing database pool...");
    await pool.end();
    process.exit(0);
});

However, it just kills itself and throws a timeout error every few minutes. Can anyone help me?

Conditional Rendering Issue in Expo Routing with AuthContext

Description:

I’m experiencing an issue with conditional rendering in my React Native application using Expo 52 and expo-router ~4.0.5. Specifically, I expect my app to show a DrawerLayout when the user variable has a value (indicating the user is logged in) and a Stack with login/registration screens when user is null or undefined. However, even when user is false or null, the app incorrectly renders the DrawerLayout.

Environment:

React Native: 0.76.2

Expo SDK version: 52.0.7

expo-router version: ~4.0.5

Project Structure:

App/
  (auth)/
    _layout.tsx
    login.tsx
    register.tsx
  (drawer)/
    _layout.tsx
    index.tsx
    user_profile.tsx
  _layout.tsx  <- Conditional rendering logic is here

Code for App/_layout.tsx:

export default function Layout() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [user, setUser] = useState(null);
  const [isInitialized, setIsInitialized] = useState(false);

  const tamaguiConfig = createTamagui(config);

  const [loaded] = useFonts({
    Inter: require('@tamagui/font-inter/otf/Inter-Medium.otf'),
    InterBold: require('@tamagui/font-inter/otf/Inter-Bold.otf'),
  });

  useEffect(() => {
    async function initializeApp() {
      try {
        console.log("Iniciando loadUser...");
        const userData = await loadUser();
        console.log("userData recibido:", userData);
        setUser(userData);
      } catch (e) {
        console.error("Error en loadUser:", e);
      } finally {
        setIsInitialized(true);
      }
    }

    initializeApp();
  }, []);

  if (!isInitialized || !loaded) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <ActivityIndicator size="large" />
      </View>
    );
  }

  return (
    <TamaguiProvider config={tamaguiConfig}>
      <Theme name="light">
        <AuthContext.Provider value={{ user, setUser }}>
          {isInitialized && (
            user ? (
              // Even when `user` is falsy, <DrawerLayout /> is rendered.
              <DrawerLayout />
            ) : (
              <Stack>
                <Stack.Screen
                  name="(auth)"
                  options={{ headerShown: false }}
                />
              </Stack>
            )
          )}
        </AuthContext.Provider>
      </Theme>
    </TamaguiProvider>
  );
}

App/(drawer)/_layout.tsx

const DrawerLayout = () => {
  const [newRecipeGenerated, setNewRecipeGenerated] = useState(false);

  return (
    <NewRecipeGenerationContext.Provider value={{ newRecipeGenerated, setNewRecipeGenerated }}>
      <Drawer>
        <Drawer.Screen name="index" options={{ title: "Home" }} />
        <Drawer.Screen name="recipeGeneration" options={{ title: "Generación Recetas" }} />
        <Drawer.Screen name="userRecipes" options={{ title: "Mis Recetas" }} />
      </Drawer>
    </NewRecipeGenerationContext.Provider>
  );
}

App/(auth)/_layout.tsx

export default function AuthLayout() {
  return (
    <Stack screenOptions={{
      headerShown: false
    }}>
      <Stack.Screen
        name="login"
        options={{
          title: 'Login'
        }}
      />
      <Stack.Screen
        name="register"
        options={{
          title: 'Register'
        }}
      />
    </Stack>
  );
}

AuthContext:

import { createContext } from "react";

const AuthContext = createContext({
  user: null,
  setUser: () => {},
});

export default AuthContext;

import statement in javascript

I have html code with javascript inside a django project:

<body>
<-- some html>
</body>
<script>
import fs from "fs"
// some javascript
</script>

Now I get the error import declarations may only appear at the top level of a module.

What am I doing wrong? And is there some reference that explains how the import works in javascript? I’m not used to javascript yet and in all other languages I never had an issue with import statements.

Vue Combobox Headless UI how to reset?

I have a component, I took it from the templates and did not change it in any way.
I am just trying to add a button to clear the selected element.

My clearSelection function does not work, although the values ​​in the variables are cleared
Unfortunately, chatgpt also could not help and did not find anything on the Internet, has anyone encountered this?

<script setup>
import { computed, ref } from 'vue'
import { CheckIcon, ChevronUpDownIcon } from '@heroicons/vue/20/solid'
import {
    Combobox,
    ComboboxButton,
    ComboboxInput,
    ComboboxLabel,
    ComboboxOption,
    ComboboxOptions,
} from '@headlessui/vue'

const props = defineProps({
    label: String,
    name: String,
    data: Object
});

const query = ref('')
const selectedItem = ref(null)
const filteredData = computed(() =>
    query.value === ''
        ? props.data
        : props.data.filter((item) => {
            return item.name.toLowerCase().includes(query.value.toLowerCase())
        })
)
const clearSelection = () => {
    query.value = '';
    selectedItem.value = null;
};
</script>

<template>
    <Combobox as="div" v-model="selectedItem" @update:modelValue="query = ''" nullable>
        <div class="flex justify-between">
            <ComboboxLabel class="block text-sm font-medium leading-6 text-gray-900">{{ props.label }}</ComboboxLabel>
            <span @click="clearSelection" class="cursor-pointer text-sm text-gray-900 translate-y-0.5px">Clear</span>
        </div>
        <div class="relative mt-2">
            <ComboboxInput :name="props.name" class="w-full rounded-md border-0 bg-white py-1.5 pl-3 pr-10 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-blue-600 sm:text-sm sm:leading-6"
                           @change="query = $event.target.value"
                           @blur="query = ''" :display-value="(item) => item?.name"
            />
            <ComboboxButton class="absolute inset-y-0 right-0 flex items-center rounded-r-md px-2 focus:outline-none">
                <ChevronUpDownIcon class="h-5 w-5 text-gray-400" aria-hidden="true" />
            </ComboboxButton>

            <ComboboxOptions v-if="filteredData.length > 0" class="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm">
                <ComboboxOption v-for="item in filteredData" :key="item.id" :value="item" as="template" v-slot="{ active, selected }">
                    <li :class="['relative cursor-default select-none py-2 pl-3 pr-9', active ? 'bg-blue-600 text-white' : 'text-gray-900']">
                        <span :class="['block truncate', selected && 'font-semibold']">
                          {{ item.name }}
                        </span>

                        <span v-if="selected" :class="['absolute inset-y-0 right-0 flex items-center pr-4', active ? 'text-white' : 'text-blue-600']">
                            <CheckIcon class="h-5 w-5" aria-hidden="true" />
                        </span>
                    </li>
                </ComboboxOption>
            </ComboboxOptions>
        </div>
    </Combobox>
</template>

I want the field with the selected element to be cleared after clicking the button. I found the nullable property, but it allows you to simply erase the text. You can’t clear it through the button.

how to create a downloadable link which loads the file from a backend server only when clicked in Angular

I have a situation where I have a list of items each represent a file. All these files can be fetched from a backend as blobs. I want to have links in the frontend when user clicks should be able to download the file for him/her.
The solution I have pre downloads the file and creates a SafeResourceUrl.

But, my problem is since I now have to show a list of links pre downloading all of them initially is a waste. I need to make it such that when I click the link the network call will go and fetch the file and then the download popup should be opened.

here is the code I have for predownloading

component

import { Component, OnInit } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { AppService } from './app.service';
import { HttpResponse } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
  url?: SafeResourceUrl;
  stream: ArrayBuffer | null = null;
  fileName: string = 'test.pdf';

  constructor(
    private appService: AppService,
    private sanitizer: DomSanitizer
  ) {}

  ngOnInit(): void {
    this.appService.fetchPdf().subscribe((response: HttpResponse<Blob>) => {
      const blob = response.body!;
      blob.arrayBuffer().then((res) => {
        this.stream = res;
      });
      this.createLink(blob);
    });
  }

  async createLink(blob: Blob): Promise<void> {
    const buffer = await blob.arrayBuffer();
    if (buffer.byteLength) {
      const uint = new Uint8Array(buffer);
      let bin = '';
      for (let i = 0; i < uint.byteLength; i++) {
        bin += String.fromCharCode(uint[i]);
      }
      const base64 = window.btoa(bin);
      const url = `data:${blob.type};base64,${base64}`;
      this.url = this.sanitizer.bypassSecurityTrustResourceUrl(url);
    }
  }
}

service

import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class AppService {
  private pdfUrl =
    'https://s28.q4cdn.com/392171258/files/doc_downloads/test.pdf';

  constructor(private http: HttpClient) {}

  fetchPdf(): Observable<HttpResponse<Blob>> {
    return this.http.get(this.pdfUrl, {
      observe: 'response',
      responseType: 'blob',
    });
  }
}

html

<h1>download test</h1>
<div *ngIf="url">
  <a [href]="url" [download]="fileName">{{ fileName }}</a>
</div>

here is demo

React Native with Expo error when loading the main layout on the personal dashboard or login

I have a problem with the main logic of my application made in react native, using the router “Expo Router”, what happens is that apparently, it does not work well a conditional evaluation, which shows the Drawer with the user panel, or a Stack with the login and registration, found in the layout root of the application.

I am using Expo 52.0.7 together with expo-router version ~4.0.5.

This is my configuration.

package.json

"main": "expo-router/entry",

My file directory is this one:

    App/
      (auth)
        _layout.tsx
        login.tsx
        register.tsx
      (drawer)
        _layout.tsx
        index.tsx
        user_profile.tsx

The starting point is in App/_layout.tsx, here you should check if there is user logged in or not, if there is user logged in, show a With user panel, if not, show the Stack where eta the log-in and registration.

App/(auth)/_layout.tsx

export default function AuthLayout() {
  return (
    <Stack screenOptions={{
      headerShown: false
    }}>
      <Stack.Screen
        name="login"
        options={{
          title: 'Login'
        }}
      />
      <Stack.Screen
        name="register"
        options={{
          title: 'Register'
        }}
      />
    </Stack>
    // <Text>Auth Layout</Text>
  );
}

And the main

App/_layout.tsx

export default function Layout() {
  const [isLoggedIn, setIsLoggedIn] = useState(false)
  const [user, setUser] = useState(null);
  const [isInitialized, setIsInitialized] = useState(false);

  const tamaguiConfig = createTamagui(config)

  const [loaded] = useFonts({
    Inter: require('@tamagui/font-inter/otf/Inter-Medium.otf'),
    InterBold: require('@tamagui/font-inter/otf/Inter-Bold.otf'),
  });

  useEffect(() => {
    async function initializeApp() {
      try {
        console.log("Iniciando loadUser...");
        const userData = await loadUser();
        console.log("userData recibido:", userData);
        setUser(userData);
      } catch (e) {
        console.error("Error en loadUser:", e);
        setUser(null);
      } finally {
        setIsInitialized(true);
      }
    }

    initializeApp();
  }, []);

  if (!isInitialized || !loaded) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <ActivityIndicator size="large" />
      </View>
    );
  }

  return (
    <TamaguiProvider config={tamaguiConfig}>
      <Theme name="light">
        <AuthContext.Provider value={{ user, setUser }}>
          {isInitialized && (
            user ? ( Here user is null or false, since he is not logged in, but still, instead of entering the ":", he enters the <drawer>....</drawer>.                  <DrawerLayout />
            ) : (
              <Stack>
                <Stack.Screen
                  name="(auth)"
                  options={{ headerShown: false }}
                />
              </Stack>
            )
          )}
        </AuthContext.Provider>
      </Theme>
    </TamaguiProvider>
  );

}

I don’t know what the problem is, but before this with SDK51, I didn’t have any problems :/

**This is my AuthContext.

import {createContext} from "react";

const AuthContext = createContext({
  user: null,
  setUser: () => {}
});

export default AuthContext;

Import folder from one project to another in node.js

I have a projectA on github which contains folder, called template in which there’re 3 files:

  • test1.hbs
  • helper.js
  • properties.js

I also have another project which is a node.js project. In one of the files(test.js), I have the code:

// test.js
initialization({
   templates: 'path-to-template-folder`
})

As you can see, I need to be passing the folder path to the templates, but it lives on another repo. So what’s the best way to achieve this ?

I thought about:

  • Way 1: making a curl request inside test.js, get the template folder and wherever it downloads to, i will specify that path instead of path-to-template-folder. What’s important is I need this to be sync and not async request.
  • Way 2: Even if I publish projectA to npm, it’s still hard, because how would I import the folder and specify its path ?

Looking for the right, best-practice way if there’s such.

Chrome Extension: Cannot change tab icon with my Chrome extension

Below is a simplistic Chrome extension that changes the tab icon for every site that is opened. However, the icon does not seem to change when the page finishes loading.

manifest.json:

{
  "manifest_version": 3,
  "name": "Tab Icon",
  "description": "This extension changes the tab icon for any site.",
  "version": "1.0",
  "permissions": [
    "tabs",
    "activeTab"
  ],
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_popup": "popup.html"
  },
  "icons": {
    "16": "icons/icon-16.png",
    "32": "icons/icon-32.png"
  },
  "host_permissions": [
    "http://*/*",
    "https://*/*"
  ]
}

background.js:

// Debug log to check if the service worker is running
console.log("Background service worker is running.");

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  // Log when a tab is updated
  console.log("Tab updated:", tabId, changeInfo, tab.url);

  if (changeInfo.status === 'complete' && tab.url) {
    // Set the tab icon to the grayscale version when the page is fully loaded
    chrome.action.setIcon({ path: 'icons/icon-grayscale-16.png', tabId: tabId });
  }
});

What I’ve Tried:

  1. The background script (background.js) is set up as a service worker.
  2. The service worker listens for the chrome.tabs.onUpdated event and changes the tab icon once the page finishes loading (changeInfo.status === ‘complete’).
  3. The chrome.action.setIcon API is used to update the tab icon to a grayscale version (icon-grayscale-16.png).
  4. I checked for any errors in the service worker’s console (via chrome://extensions/), and the service worker seems to be running without issues.
  5. I confirmed that the icon (icon-grayscale-16.png) exists and is in the correct location.

Problem: When I visit any website (e.g., https://google.com), the tab icon does not change to the grayscale version as expected.

Questions:

  1. Is there something wrong with my manifest.json or background.js setup for this behavior?

  2. Why is the chrome.action.setIcon() method not working for my extension’s icon change in Manifest V3?

  3. How can I ensure the icon change works reliably for any page loaded in Chrome?

    I would appreciate any insights or suggestions to help resolve this issue.