Other than children(), can I import and render multiple snippets in +layout.svelte that are defined in +page.svelte?

New to SvelteKit and trying to figure this part out…

Here’s a couple of ways I was trying to achieve this, but the sidebar either doesn’t load, or the navigation appears twice for some reason; with the snippet text only appearing in the second instance. I started searching Github to review examples via path:**/+layout.svelte /@render children/ and path:**/+layout.svelte /children: Snippet; *: Snippet, but there are no results that actually import and use duplicate renders; from what I’ve seen. I planned to use +layout.svelte to breakdown my site into Header, Sidebar, Main and Footer and dynamically change the content based on +page.svelte. The docs touch on this and I’ve seen it done with cards and +page.svelte, but not in +layout.svelte itself. Am I doing this wrong?

+layout.svelte

<script lang="ts">
    import "../app.css";
    import type { Snippet } from "svelte";
    import { sineIn } from "svelte/easing";
    import { Drawer, Sidebar } from "flowbite-svelte";

    // Destructure specific props from $props()
    interface Props {
        children?: Snippet;
        filterSidebar?: Snippet<[() => void]>;
    }
    let { 
        children, 
        filterSidebar
    }: Props = $props();

    const transitionParams = {
        x: -320,
        duration: 200,
        easing: sineIn
    };

    let hidden = $state(true);

    function toggleSidebar(): void {
        hidden = !hidden;
    }
</script>
<div class="header flex items-center justify-between p-5 border-b">
    <h1 class="text-xl">SvelteKit Render Test</h1>
    <button
        aria-label="Toggle Filters"
        onclick={toggleSidebar}
    >
        <svg
            class="w-6 h-6"
            xmlns="http://www.w3.org/2000/svg"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
        >
            <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M4 6h16M4 12h16m-7 6h7"
            />
        </svg>
    </button>
</div>
<Drawer transitionType="fly" {transitionParams} bind:hidden={hidden} id="sidebar">
    <Sidebar asideClass="w-full">
        {@render filterSidebar?.(toggleSidebar)}
    </Sidebar>
</Drawer>
<main>
    {@render children?.()}
</main>


+page.svelte v1

<script lang="ts">
    import Layout from "./+layout.svelte";
    import { CloseButton, SidebarGroup } from "flowbite-svelte";=
</script>
{#snippet filterSidebar(toggleSidebar: () => void)}
    <SidebarGroup ulClass="flex items-center">
        <h1>Filters</h1>
        <CloseButton onclick={toggleSidebar} />
    </SidebarGroup>
{/snippet}
<h1>Test Element</h1>

Results +page.svelte v1

+page.svelte v1 - blank sidebar


+page.svelte v2

<script lang="ts">
    import Layout from "./+layout.svelte";
    import { CloseButton, SidebarGroup } from "flowbite-svelte";
    console.log("Page rendered");
</script>
<Layout>
    {#snippet filterSidebar(toggleSidebar: () => void)}
        <SidebarGroup ulClass="flex items-center">
            <h1>Filters</h1>
            <CloseButton onclick={toggleSidebar} />
        </SidebarGroup>
    {/snippet}
    <h1>Test Element</h1>
</Layout>

Results +page.svelte v2

+page.svelte v2 - duplicated content

cola.js and d3 latest version

cola is exactly what I need for a few things – mainly it does forced based graph layouts supporting grouping and constraints. I’m using it with d3.

However, I’ve noticed cola seems to tap out at d3 v4 – whereas d3 is now at version 7. Just wondering if there’s a version of cola that’s happy with the latest version of d3 – or if somehow d3 just supports everything in cola now so it’s not necessary?

confusing debug status that i do not understand

your text import fetch from ‘cross-fetch’;
import { Connection, Keypair, VersionedTransaction, PublicKey, Transaction } from ‘@solana/web3.js’;
import dotenv from ‘dotenv’;

dotenv.config();

const connection = new Connection('https://api.mainnet-beta.solana.com',   'confirmed');
const wallet = new     Keypair(Uint8Array.from(JSON.parse(process.env.PRIVATE_KEY)));

async function fetchWithRetry(url, options, maxRetries = 3) {
    for (let i = 0; i < maxRetries; i++) {
        try {
           const response = await fetch(url, options);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return await response.json();
        } catch (error) {
            console.log(`Retry attempt ${i + 1} due to error:`, error.message);
            await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
        }
    }
    throw new Error('Max retries reached. Could not fetch data.');
}

async function executeTrade() {
    try {
        const SOL_MINT = 'So11111111111111111111111111111111111111112'; // SOL mint address
        const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'; // USDC mint address
    
        const solAmount = 0.025; // 0.05 SOL for $5 if SOL price is $100
        const solInLamports = Math.floor(solAmount * 1e9); // Convert to lamports

        // Buy USDC with SOL
        const buyQuoteResponse = await fetchWithRetry(`https://quote-    api.jup.ag/v6/quote?    inputMint=${SOL_MINT}&outputMint=${USDC_MINT}&amount=${solInLamports}&slippageBps=50`);
        const buyQuote = buyQuoteResponse;
    
    console.log('Buy Quote:', JSON.stringify(buyQuote, null, 2));
    if (buyQuote.error) throw new Error('Error fetching buy quote: ' + JSON.stringify(buyQuote.error));

    const buySwapResponse = await fetchWithRetry('https://quote-api.jup.ag/v6/swap', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            quoteResponse: buyQuote,
            userPublicKey: wallet.publicKey.toString(),
            wrapAndUnwrapSol: true
        })
    });
    const buySwap = buySwapResponse;
    
    console.log('Buy Swap Response:', JSON.stringify(buySwap, null, 2));
    if (buySwap.error) throw new Error('Error in buy swap: ' + JSON.stringify(buySwap.error));

    // Enhanced error checking for swapTransaction
    if (!buySwap.swapTransaction) {
        console.log('Full Buy Swap Response:', JSON.stringify(buySwap, null, 2));
        throw new Error('Buy swap transaction is not available in the response');
    }

    try {
        // Check if the transaction can be deserialized as VersionedTransaction
        let buyTransaction;
        try {
            buyTransaction = VersionedTransaction.deserialize(Buffer.from(buySwap.swapTransaction, 'base64'));
        } catch (versionedError) {
            // If VersionedTransaction fails, try with regular Transaction
            console.log('Failed to deserialize as VersionedTransaction, trying as Transaction:', versionedError.message);
            buyTransaction = Transaction.from(Buffer.from(buySwap.swapTransaction, 'base64'));
        }

        // Check if the transaction has the '_bn' property or similar
        if (buyTransaction && buyTransaction._bn === undefined) {
            console.log('Transaction does not have _bn property:', JSON.stringify(buyTransaction, null, 2));
            throw new Error('Transaction object does not contain expected _bn property');
        }

        buyTransaction.sign([wallet]);
        const buySignature = await connection.sendTransaction(buyTransaction, [wallet]);
        await connection.confirmTransaction(buySignature);
        console.log('USDC Buy Transaction confirmed:', `https://explorer.solana.com/tx/${buySignature}`);
    } catch (deserializeError) {
        console.error('Error in deserializing or signing buy transaction:', deserializeError.message);
        throw deserializeError;
    }

    // Wait for 10 seconds
    await new Promise(resolve => setTimeout(resolve, 10000));

    // Convert USDC back to SOL
    const usdcAmount = buyQuote.outAmount;
    console.log('USDC Amount to sell:', usdcAmount);
    if (usdcAmount === undefined) throw new Error('USDC amount to sell is undefined');

    const sellQuoteResponse = await fetchWithRetry(`https://quote-api.jup.ag/v6/quote?inputMint=${USDC_MINT}&outputMint=${SOL_MINT}&amount=${usdcAmount}&slippageBps=50`);
    const sellQuote = sellQuoteResponse;
    
    console.log('Sell Quote:', JSON.stringify(sellQuote, null, 2));
    if (sellQuote.error) throw new Error('Error fetching sell quote: ' + JSON.stringify(sellQuote.error));

    const sellSwapResponse = await fetchWithRetry('https://quote-api.jup.ag/v6/swap', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            quoteResponse: sellQuote,
            userPublicKey: wallet.publicKey.toString(),
            wrapAndUnwrapSol: true
        })
    });
    const sellSwap = sellSwapResponse;
    
    console.log('Sell Swap Response:', JSON.stringify(sellSwap, null, 2));
    if (sellSwap.error) throw new Error('Error in sell swap: ' + JSON.stringify(sellSwap.error));

    // Enhanced error checking for swapTransaction
    if (!sellSwap.swapTransaction) {
        console.log('Full Sell Swap Response:', JSON.stringify(sellSwap, null, 2));
        throw new Error('Sell swap transaction is not available in the response');
    }

    try {
        // Check if the transaction can be deserialized as VersionedTransaction
        let sellTransaction;
        try {
            sellTransaction = VersionedTransaction.deserialize(Buffer.from(sellSwap.swapTransaction, 'base64'));
        } catch (versionedError) {
            // If VersionedTransaction fails, try with regular Transaction
            console.log('Failed to deserialize as VersionedTransaction, trying as Transaction:', versionedError.message);
            sellTransaction = Transaction.from(Buffer.from(sellSwap.swapTransaction, 'base64'));
        }

        // Check if the transaction has the '_bn' property or similar
        if (sellTransaction && sellTransaction._bn === undefined) {
            console.log('Transaction does not have _bn property:', JSON.stringify(sellTransaction, null, 2));
            throw new Error('Transaction object does not contain expected _bn property');
        }

        sellTransaction.sign([wallet]);
        const sellSignature = await connection.sendTransaction(sellTransaction, [wallet]);
        await connection.confirmTransaction(sellSignature);
        console.log('SOL Sell Transaction confirmed:', `https://explorer.solana.com/tx/${sellSignature}`);
    } catch (deserializeError) {
        console.error('Error in deserializing or signing sell transaction:', deserializeError.message);
        throw deserializeError;
    }

    console.log('Trade completed successfully.');

} catch (error) {
    console.error('Error in trade execution:', error.message);
}

}

// Execute the trade
executeTrade().catch(console.error);

im testing out jupiters v6 swap api and im tryng to make a small transaction just to test if it works and i keep getting this error “Error in trade execution: Cannot read properties of undefined (reading ‘_bn’)” i dont understand whys that happening please someone explain.

tabulator – how to insert tickCross using javascript

My table uses tickCross in one column – I am interested in having javascript turn on the tick mark – actively – using javascript to tick it, without manually pressing the box. I was able to insert it using javascript, however when I save the file to a cvs, it is not included in the file for that row. Right now I must manually click the checkmark “on” for it to save in the file. Is it possible to activate the tickCross checkmark using javascript (as though I clicked it) and still have it save with the file?

Side scrolling collisionbox system either has player falling through floor or running out of memory based on my methods

I had a system with checking, but as it scrolled, I basically sank into the floor. I had chatGPT comment my code for helping with this.
The main problems seem to be the ReassignCollisionBox(), which causes the memory error, and around the bottom of update(). I am unsure how to get this collision working, as all the sources i can find are for some game engine, not JavaScript.

//Reassign the collisions and clear the orginal.
    CollisonBoxes.length = 0;
    for(let i=0; level.length; i++) {
        for(let k=0; level[i].length; k++) {
            ReassignCollisionBox(i,k);
        }
    }

//Note these code is not actually next to each other, this is in the update ^

function ReassignCollisionBox(down,right) {
    let xmin = down * tilesize; //Upper Left Corner, X
    let ymin = down * tilesize; //Upper Left Corner, Y
    let xmax = xmin + tilesize; //Bottom Right corner, X
    let ymax = ymin + tilesize; //Bottom Right Corner, Y
    CollisonBoxes.push([[xmin,ymin],[xmax,ymax]])
    return(true);
}

I think it is pretty solid code for my level of experience, but collisions never come naturally to me.

This is the… mostly working code, without the CollisionBox functions, but still the issue where i fall through the floor.

const stage = document.getElementById("stage");
const ctx = stage.getContext("2d");

ctx.fillRect(0, 0, stage.width, stage.height);

let keys = {};

window.addEventListener('keydown', (event) => {
  keys[event.key] = true;
});

window.addEventListener('keyup', (event) => {
  keys[event.key] = false;
});

game = {
  cameraX: 0,
  cameraY: 0,
  pause: false,
  pausedelay: 0,
  fontSize: 16,
  font: function() {
    return this.fontSize.toString() + "px Arial";
  }
};
player = {
  x: 0, // Starting position for the player
  y: 48,
  width: 16,
  height: 16,
  dx: 0, // Change in x (velocity)
  dy: 0, // Change in y (velocity for gravity)
  speed: 2, // Player movement speed
  gravity: 0.5, // Gravity force
  jumpPower: -10, // Jump force (upward)
  grounded: false // Check if the player is on the ground
};

level = [
  [
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0]
  ],
  [
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0]
  ],
  [
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0]
  ],
  [
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0],
    [0, 0]
  ],
  [
    [1, 8],
    [1, 0],
    [1, 8],
    [1, 0],
    [1, 8],
    [1, 0],
    [1, 8],
    [1, 0],
    [1, 8],
    [1, 0],
    [1, 8],
    [1, 0],
    [1, 8],
    [1, 0],
    [1, 8],
    [1, 0],
    [1, 8],
    [1, 0],
    [1, 8],
    [1, 0]
  ],
  [
    [1, 0],
    [1, 8],
    [1, 0],
    [1, 8],
    [1, 0],
    [1, 8],
    [1, 0],
    [1, 8],
    [1, 0],
    [1, 8],
    [1, 0],
    [1, 8],
    [1, 0],
    [1, 8],
    [1, 0],
    [1, 8],
    [1, 0],
    [1, 8],
    [1, 0],
    [1, 8]
  ],
  [
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0]
  ],
  [
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0]
  ],
  [
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0]
  ],
  [
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 0],
    [1, 8],
    [1, 0],
    [1, 0]
  ]
];
//Game CollisonBox
CollisonBoxes = [];

colors = [
  "rgb(0, 0, 0)", // 0 - Black
  "rgb(255, 255, 255)", // 1 - White
  "rgb(255, 0, 0)", // 2 - Red
  "rgb(0, 255, 0)", // 3 - Green
  "rgb(0, 0, 255)", // 4 - Blue
  "rgb(255, 255, 0)", // 5 - Yellow
  "rgb(0, 255, 255)", // 6 - Cyan
  "rgb(255, 0, 255)", // 7 - Magenta
  "rgb(128, 128, 128)", // 8 - Gray
  "rgb(255, 165, 0)" // 9 - Orange
];

const tilesize = 16;

window.onload = function() {
  GameLoop();
}

function update() {

  game.pausedelay -= 1;
  if (keys['p'] && game.pausedelay <= 0) {
    console.log("pause");
    if (game.pause == false) {
      game.pause = true;
    } else {
      game.pause = false;
    }
    game.pausedelay = 50;
  }
  if (game.pause == true) {
    return;
  }

  //Reassign the collisions and clear the orginal.
  // CollisonBoxes.length = 0;
  // for(let i=0; level.length; i++) {
  // for(let k=0; level[i].length; k++) {
  // ReassignCollisionBox(i,k);
  // }
  // }
  // Horizontal movement
  if (keys['ArrowLeft'] || keys['a']) {
    player.dx = -player.speed;

  } else if (keys['ArrowRight'] || keys['d']) {
    player.dx = player.speed;

  } else {
    player.dx = 0;
  }

  // Jumping: If the player presses the jump key (up or 'w') and is grounded, jump
  if ((keys['ArrowUp'] || keys['w']) && player.grounded) {
    player.dy = player.jumpPower;
    player.grounded = false; // No longer grounded after jumping
  }

  // Apply gravity (downward force)
  player.dy += player.gravity;

  // Update the player's position based on their velocity
  player.x += player.dx;
  player.y += player.dy;

  // Check for collisions with the ground
  player.grounded = false; // Reset grounded state every update
  for (let i = 0; i < level.length; i++) {
    for (let k = 0; k < level[i].length; k++) {
      // Check if the tile is solid (1 = solid)
      if (level[i][k][0] !== 0) {
        let tileX = k * tilesize - game.cameraX;
        let tileY = i * tilesize + game.cameraY;

        // Collision detection with the ground (player's bottom edge)
        if (
          player.x + player.width > tileX &&
          player.x < tileX + tilesize &&
          player.y + player.height > tileY &&
          player.y + player.height <= tileY + player.dy
        ) {
          player.y = tileY - player.height; // Stop the player at the tile
          player.dy = 0; // Stop falling
          player.grounded = true; // Player is on the ground
        }
      }
    }
  }

  // Prevent the player from falling below the screen
  if (player.y + player.height > stage.height) {
    player.y = stage.height - player.height;
    player.dy = 0;
    player.grounded = true;
  }

  //Camera fix
  if (player.x >= 80 || player.dx <= 0) {
    game.cameraX += player.dx;
  }
  if (player.x < 0) {
    player.x = 0;
  }
  if (game.cameraX < 0) {
    game.cameraX = 0;
  }
}

function draw() {
  //Draw Tile
  ctx.clearRect(0, 0, stage.width, stage.height);
  ctx.fillStyle = "rgb(173,216,230)";
  ctx.fillRect(0, 0, stage.width, stage.height);
  ctx.fillStyle = "black";
  for (let i = 0; i < level.length; i++) {
    for (let k = 0; k < level[i].length; k++) {
      if (level[i][k][0] != 0) {
        ctx.fillStyle = colors[level[i][k][1]];
        ctx.fillRect(k * tilesize - game.cameraX, i * tilesize + game.cameraY, tilesize, tilesize);
      }
    }
  }
  //Draw Player
  ctx.fillStyle = "green";
  ctx.fillRect(player.x - game.cameraX, player.y + game.cameraY, player.width, player.height);

  //Pause Screen if Paused.
  if (game.pause == true) {
    ctx.fillStyle = "rgba(128,128,128,0.75)";
    ctx.fillRect(0, 0, stage.width, stage.height);
    ctx.fillStyle = "yellow";
    let textpos = centerText("Paused", 16, "Arial");
    ctx.fillText("Paused", textpos.x, textpos.y);
  }



}


function GameLoop() {
  update();
  draw();
  requestAnimationFrame(GameLoop);
};
//Lag Stopper
window.addEventListener('blur', function() {
  // Code to execute when the user clicks off the page
  game.pause = true;
  console.log('User clicked off the page');
});


function centerText(message, fontsize, font) {
  ctx.font = `${fontsize}px ${font}`;
  let textwidth = ctx.measureText(message).width;
  let textheight = fontsize; // For simplicity, this assumes single line text, but line height could be used for multi-line text.

  // Calculate X and Y coordinates to center the text
  let textX = (stage.width - textwidth) / 2;

  // Calculate Y position considering text's baseline (font size is usually height of the text)
  let textY = (stage.height + textheight / 2) / 2; // Adjusted to center properly based on the baseline
  ctx.draw
  return {
    x: textX,
    y: textY
  };
}

// function ReassignCollisionBox(down,right) {
// let xmin = down * tilesize; //Upper Left Corner, X
// let ymin = down * tilesize; //Upper Left Corner, Y
// let xmax = xmin + tilesize; //Bottom Right corner, X
// let ymax = ymin + tilesize; //Bottom Right Corner, Y
// CollisonBoxes.push([[xmin,ymin],[xmax,ymax]])
// return(true);
// }
<html>

<head>
  <title>Tile-Scroll</title>
</head>

<body>
  <canvas id="stage" width="160" height="160">TileScroller</canvas>
  <script src="tilescroll.js"></script>
</body>

</html>

Could anyone help me with this problem, or am I just a idiot who needs to read up on more documentation. Thanks for any help.

Mapbox GL JS Heatmap: Issues with Color Coding and Opacity Across Zoom Levels

I’m developing an interactive map using Mapbox GL JS to visualize snowfall data across various ski resorts. Each resort’s data includes its name, latitude, longitude, and snowfall amount (in inches). The goal is to represent snowfall intensity using a heatmap with specific color coding and maintain consistent opacity across different zoom levels.

Request for Assistance: I’m seeking guidance on:

Correctly configuring the heatmap to reflect accurate color coding based on snowfall data.
Ensuring consistent opacity and color representation across various zoom levels.
Any insights, suggestions, or examples to resolve these issues would be greatly appreciated.

Additional Information:

Mapbox GL JS Version: 2.15.0
Browser: Google Chrome Version 131.0.6778.264
Data Sample: Provided below
Relevant Code: Provided below
Thank you in advance for your assistance.

Issues Encountered:

Color Coding:

Resorts with higher snowfall (e.g., 17 inches) are displayed in colors intended for lower snowfall ranges.
The color representation doesn’t align with the defined heatmap-weight and heatmap-color settings.

Opacity and Zoom Levels:

As I zoom in or out, the heatmap colors fade or disappear, leading to inconsistent visualization.
Desired behavior is to maintain consistent opacity and color representation across all zoom levels.

Troubleshooting Attempts:

Data Verification: Confirmed that snowfall values are correctly parsed as integers.
Configuration Adjustments: Experimented with different heatmap-weight, heatmap-color, heatmap-radius, and heatmap-opacity settings without achieving the desired outcome.
Documentation

Review: Consulted the Mapbox GL JS Heatmap Tutorial and related resources.

Current Implementation:

  • Data Source: resorts_with_snowfall.json containing:
    [
      {
        "resortName": "Alyeska",
        "latitude": "63.588753",
        "longitude": "-154.4930619",
        "snowfall": "23in"
      },
      {
        "resortName": "Arctic Valley",
        "latitude": "61.2391787",
        "longitude": "-149.6337609",
        "snowfall": "9in"
      }
      // Additional resort data...
    ]
    
    

Heatmap Layer Configuration:
map.addLayer({
id: ‘resort-heatmap’,
type: ‘heatmap’,
source: ‘resorts’,
paint: {
‘heatmap-weight’: [
‘interpolate’,
[‘linear’],
[‘get’, ‘snowfall’],
0, 0,
1, 0.1,
5, 0.3,
12, 1
],
‘heatmap-color’: [
‘interpolate’,
[‘linear’],
[‘heatmap-density’],
0, ‘rgba(0, 0, 0, 0.8)’, // Black for Low (1–5 inches)
0.2, ‘rgba(35, 238, 255, 0.5)’, // Light Blue for Medium (5–12 inches)
0.5, ‘rgba(255, 255, 255, 0.8)’, // White for High (>12 inches)
1, ‘rgba(255, 255, 255, 1)’ // Solid White for the highest intensity
],
‘heatmap-radius’: [
‘interpolate’,
[‘linear’],
[‘zoom’],
0, 20,
9, 50,
15, 100
],
‘heatmap-opacity’: 0.8
}
});

D3 linkHorizontal Argument is not assignable to parameter

I’m trying to create a simpler version of the D3 Tidy Tree (https://observablehq.com/@d3/tree/2). Here is the full JS file:

const width = 800;
const height = 600;

const svg = d3
  .select('svg')
  .attr('width', width)
  .attr('height', height)
  .append('g')
  .attr('transform', 'translate(50,50)');

const tree = d3.tree().size([height - 100, width - 200]);

const data = {
  name: 'Root',
  children: [
    {
      name: 'Child 1',
      children: [{ name: 'Grandchild 1' }, { name: 'Grandchild 2' }],
    },
    {
      name: 'Child 2',
      children: [{ name: 'Grandchild 3' }, { name: 'Grandchild 4' }],
    },
  ],
};

const root: d3.HierarchyNode<{
  name: string;
  children: { name: string; children: { name: string }[] }[];
}> = d3.hierarchy(data);

tree(root as d3.HierarchyPointNode<unknown>);

svg
  .selectAll('.link')
  .data(root.links())
  .enter()
  .append('path')
  .attr('class', 'link')
  .attr(
    'd',
    d3
      .linkHorizontal()
      .x((d) => d.y)
      .y((d) => d.x),
  );

I’m getting this error in attr('d', ...):

Argument of type ‘Link<any, DefaultLinkObject, [number, number]>’ is
not assignable to parameter of type ‘string | number | boolean |
readonly (string | number)[] | ValueFn<SVGPathElement, HierarchyLink<{
name: string; children: { name: string; children: { name: string; }[];
}[]; }>, string | … 3 more … | null> | null’. Type ‘Link<any,
DefaultLinkObject, [number, number]>’ is not assignable to type
‘ValueFn<SVGPathElement, HierarchyLink<{ name: string; children: {
name: string; children: { name: string; }[]; }[]; }>, string | number
| boolean | readonly (string | number)[] | null>’.
Types of parameters ‘d’ and ‘datum’ are incompatible.
Type ‘HierarchyLink<{ name: string; children: { name: string; children: { name: string; }[]; }[]; }>’ is not assignable to type
‘DefaultLinkObject’.
Types of property ‘source’ are incompatible.
Type ‘HierarchyNode<{ name: string; children: { name: string; children: { name: string; }[]; }[]; }>’ is not assignable to
type ‘[number, number]’.

Why does my code affect the imageData.data at times correctly and at other (random) times, in an unexpected way?

I have a code that should affect an image by applying a laplace filter to the top left quarter and to the bottom left quarter separately. But when doing so, sometimes the second application of the filter affects the bottom right instead and sometimes misses a channel. I cannot for the life of me understand why it is apparently nondeterministic when doing so.

var canvas;
var canvasImageData;
var canvasContext;
main()

let kernel = [
  [0.25, 0.5, 0.25],
  [0.5, -3, 0.5],
  [0.25, 0.5, 0.25]
]

async function main() {
  var api = await fetch('https://dog.ceo/api/breeds/image/random')
    .then(response => response.json())

  var image = await fetch(api.message)
    .then(response => response.blob())

  const imageBitmap = await createImageBitmap(image);

  var canvas = document.createElement('canvas');
  canvas.width = imageBitmap.width;
  canvas.height = imageBitmap.height;
  canvas.id = 'image-canvas';

  canvasContext = canvas.getContext('2d')
  canvasContext.drawImage(imageBitmap, 0, 0);

  document.body.appendChild(canvas);

  canvasImageData = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
  canvasImageData = applyLaplace(canvasImageData, 0, canvas.height / 2, 0, canvas.width / 2, canvas.width, canvas.height, kernel);
  canvasImageData = applyLaplace(canvasImageData, canvas.height / 2, canvas.height, 0, canvas.width / 2, canvas.width, canvas.height, kernel);

  canvasContext.putImageData(canvasImageData, 0, 0);
}

//applyLaplace(canvasImageData)
function applyLaplace(canvas, height_start, height_end, width_start, width_end, canvasWidth, canvasHeight, kernel) {
  let data = new Uint8ClampedArray(canvas.data);

  function pos(h, l) {
    return h * canvasWidth * 4 + l * 4;
  }

  for (let height = height_start + 1; height < height_end - 1; height++) {
    for (let width = width_start + 1; width < width_end - 1; width++) {

      let sum1 = 0;
      let sum2 = 0;
      let sum3 = 0;

      for (let kernel_height = -1; kernel_height <= 1; kernel_height++) {
        for (let kernel_width = -1; kernel_width <= 1; kernel_width++) {
          sum1 = sum1 + data[pos(height + kernel_height, width + kernel_width) + 0] * kernel[kernel_height + 1][kernel_width + 1];
          sum2 = sum2 + data[pos(height + kernel_height, width + kernel_width) + 1] * kernel[kernel_height + 1][kernel_width + 1];
          sum3 = sum3 + data[pos(height + kernel_height, width + kernel_width) + 2] * kernel[kernel_height + 1][kernel_width + 1];
        }
      }

      canvas.data[pos(height, width) + 0] = 255 - sum1;
      canvas.data[pos(height, width) + 1] = 255 - sum2;
      canvas.data[pos(height, width) + 2] = 255 - sum3;
    }

  }
  return canvas;
}
<div id="api-response"></div>

and example of incorrect:

enter image description here

and an example of correct image:

enter image description here

Cannot mock hashSync function

I have a problem with Vitest (in TS). Namely the mocking of hash functions is not working properly. I have two methods that handle hashing and compare:

hash.ts:

import * as bcrypt from 'bcrypt';

const SALT_ROUNDS = 10;

export const hashPassword = (password: string) =>
  bcrypt.hashSync(password, bcrypt.genSaltSync(SALT_ROUNDS));

export const verifyPassword = (
  password: string,
  hashedPassword: string,
) => bcrypt.compareSync(password, hashedPassword);

I wanted to prepare for this unit test in Vitest:

hash-password.spec.ts:

import { hashPassword } from '../../src/services/hash.js';
import * as bcrypt from 'bcrypt';

vi.mock('bcrypt', () => ({
  genSaltSync: vi.fn(() => 10),
  hashSync: vi.fn(() => 'mockHashedPassword'),
}));
describe('hashPassword', () => {
  it('should hash the password correctly', () => {
    const hashedPassword = hashPassword('password123');

    expect(bcrypt.genSaltSync).toHaveBeenCalledWith(10);
    expect(bcrypt.hashSync).toHaveBeenCalledWith('password123', 10);

    expect(hashedPassword).toBe('mockHashedPassword');
  });
});

However, there is some problem with the mock function hashSync.

I thought it was an import problem. I replaced the import with

import bcrypt from 'bcrypt';

to

import * as bcrypt from 'bcrypt';

because I suspected some problems with the export from this library. However, the trail is blind.

However, I get this error all the time:

 FAIL test/ut/hash-password.spec.ts [ test/ut/hash-password.spec.ts ].
TypeError: unable to read undefined property (read ‘hashSync’)
 ❯ Module.hashPassword src/services/hash.js:141:20
    139| var SALT_ROUNDS = 10;
    140| var hashPassword = (password) =>
    141| bcrypt_1.default.hashSync(
       | ^
    142| password,
    143| bcrypt_1.default.genSaltSync(SALT_ROUNDS),
 ❯ test/ut/hash-password.spec.ts:10:13

What could be causing this?

Layouts Create Accessibility Issues

What To Do When Data Center Layouts Create Accessibility Issue

Just like about the existing setup and products in use, as well as temporary solutions that have been tried

whether through photos, videos, a virtual tour or an onsite visit

Analyzing.

Assistance Needed – Hybrid 1:1 Pomodoro Timer App – Kotlin/TypeScript Builds

my name is v3i1ix, i’m a beginner programmer. im working on a unique pomodoro inspired stopwatch/timer combination that enforces a perfect 1:1 work-rest ratio with custom audio cues. i initially made the program just using html, css and js, as that’s what i’ve learned so far through freecodecamp.

ive since attempted builds in kotlin and typescript, but need help with background time consistency and finalising the app.

ive made a github repo that has all of my current attempts, along with all of the basic assets needed for the project.

you can find the repo here:
https://github.com/disbelief2389/hybrid-time/tree/main

feel free to pick up any version or reach out if you’re interested in contributing!

there is no concern on my end about ownership, as i mainly am aiming to make this for the benefits i believe it could have in my personal life. so, as long as someone makes it, i don’t really care who, i just want the app made you know.

if you have any questions or want to collaborate, feel free to comment or dm me. thanks in advance for your help!

Unmatched route problem using react native expo, using clerk for the OAuth authentication

I’m kinda new to react native,
the app that i have, has a OAuth authentication (docs from 07/01/2025) and every time i sign in with google and finish the last step, the app just shows this screen.screen when trying to get back to the home page
i think this happens in the SocialLoginButton.tsx component in this part of the code that acts after signing in, this part doesn’t redirect the user to the homepage, it just shows “Unmatched Router”

      const { createdSessionId, setActive } = await startOAuthFlow({
        redirectUrl: Linking.createURL("/Home", { scheme: "myapp" }),
      });

and also, after the whole process of signing in, i’m still signed out and can’t access the home, it redirects my again to the sign in page.
the code is this github repository, if someone can help i’ll be glad

i tried to use different routes in Linking.createURL("/Home", { scheme: "myapp" }) and change the name in the tabs/_layout.jsx file for the index file that contains the homepage.
the whole app (so far) is in this git repo. https://github.com/poliso2/carapp

In javascript, is there a way to get the exact timing of when the user taps the keyboard?

I’m using the keydown event to see when the user taps the space bar on their keyboard. This is for a precise game so I need to know exactly when the event happened. To test this I’m tapping in a constant rhythm and I see the timing that is reported varies by 30 to 50 milliseconds.

I’m not sure where the slop is – perhaps it is a physical thing with the switch on the keyboard, perhaps it has to do with the OS not getting around to handling it, perhaps it has to do with the browser not calling the event handler in a timely manner. I don’t know.

From other tests – for instance with a piano keyboard, I think I can be accurate within less than 10 milliseconds so I don’t think it is me.

I don’t know if this is possible, but I know there are lots of games that depend on timing of the keyboard, so I hope there’s a trick.

I’m planning on distributing this, so it will have to work on many different systems – Windows, Mac, and Linux; and Safari, Chrome, and Firefox.

Thanks.