How to rearrange object properties to the bottom of the property list?

This is a way to rearrange object properties to the top of the property list:

const raw = {
  a: 1,
  b: 2,
  // ...the rest
  y: 3,
  z: 4,
};

const templateTop = {
  y: null,
  z: null,
}

const rearrangedTop = Object.assign(templateTop, raw);
// {
//   y: 3,
//   z: 4,
//   a: 1,
//   b: 2,
//   ...the rest
// };

However, is there a way to rearrange some properties to the bottom? I.e.

const rearrangedBottom =  {
  // ...the rest
  y: 3,
  z: 4,
  a: 1,
  b: 2,
};

SvelteKitError: Not found: /@id/__x00__virtual:__sveltekit/path

I encounter an error when i run npm run dev with my project…

This error appeared overnight, i’ve tried to rollback my code with old good version, change my nodejs version, run it vm but nothing change.

Error that showed is :

SvelteKitError: Not found: /@id/__x00__virtual:__sveltekit/paths
    at resolve (C:[email protected]:530:13)
    at resolve (C:[email protected]:330:5)
    at passedHandle (file:///C:/wamp64/www/blog/node_modules/svelte-kit-cookie-session/handle.js:2:85)
    at Object.handle (file:///C:/wamp64/www/blog/node_modules/svelte-kit-cookie-session/handle.js:7:32)
    at async Module.respond (C:[email protected]:327:20)
    at async file:///C:/wamp64/www/blog/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js:524:22 {
  status: 404,
  text: 'Not Found'
}
SvelteKitError: Not found: /@id/__x00__virtual:__sveltekit/environment
    at resolve (C:[email protected]:530:13)
    at resolve (C:[email protected]:330:5)
    at passedHandle (file:///C:/wamp64/www/blog/node_modules/svelte-kit-cookie-session/handle.js:2:85)
    at Object.handle (file:///C:/wamp64/www/blog/node_modules/svelte-kit-cookie-session/handle.js:7:32)
    at async Module.respond (C:[email protected]:327:20)
    at async file:///C:/wamp64/www/blog/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js:524:22 {
  status: 404,
  text: 'Not Found'
}

You can find my code here : https://github.com/LRoffic/Sveltekit-errors

Don’t forget forget to init database (look the README on github)

I don’t know where this error from, i litteraly changed nothing before that it comes

Can an HTML form generator be deployed along with the functionality to create and serve the generated HTML forms? [closed]

Hello first time asking questions about this site I have a project called LMS where I create a virtual classroom that can be seen by both student and professor just like a Google Classroom. My problem was when I try to input the created html in my repository It is not giving me access error, I try to copy what the reference said in media platforms but I don’t know how use the terminal for coding. Can anyone give me a procedure step by step on how to make my project happens and also name the application that I needed to download because I don’t know what they called. Much Appreciated to anyone who share their knowledge and advance thank you to all.

I expected to give me a step by step procedure on what to do on my problem and additional information I use Github for deploying my website

Setting persistent, but conditional dark mode in Angular/JavaScript

I’m trying to allow the user to set a preferred theme using localStorage. This theme should apply to all pages the user visits, except for the login page which should always be set to light mode. Hence, if the user logs out, the website will redirect to the login page in light made. If the user enters any other page after logging in, their saved setting should apply.

I’ve set up a flag for this in the changeTheme() function, which does not save the current theme to localStorage if the flag is set as false. While this flag works as intended, the theme still changes to light mode after the user logs in.

app.topbar.component.ts

set saveTheme(val: boolean) {
        this.layoutService.config.update((config) => ({
            ...config,
            saveTheme: val,
        }));
    }

    get saveTheme(): boolean {
        return this.layoutService.config().saveTheme;
    }

    changeTheme(theme: string, colorScheme: string, saveTheme: boolean = true) {
        if (colorScheme == 'light') {
            this.colorMode = 'dark';
            this.colorTheme = 'lara-dark-teal';
        }
        else {
            this.colorMode = 'light';
            this.colorTheme = 'lara-light-teal';
        }

        this.theme = this.colorTheme;
        this.colorScheme = this.colorMode;
        this.saveTheme = saveTheme;

        // console.log(this.theme)
        // console.log(this.colorScheme)
    }

    //code in logout function
    this.changeTheme('lara-light-teal', "dark", false);

app.layout.service.ts

import { Injectable, effect, signal } from '@angular/core';
import { Router } from '@angular/router';
import { Subject } from 'rxjs';

export interface AppConfig {
    inputStyle: string;
    colorScheme: string;
    theme: string;
    ripple: boolean;
    menuMode: string;
    scale: number;
    saveTheme: boolean;
}

interface LayoutState {
    staticMenuDesktopInactive: boolean;
    overlayMenuActive: boolean;
    profileSidebarVisible: boolean;
    configSidebarVisible: boolean;
    staticMenuMobileActive: boolean;
    menuHoverActive: boolean;
}

@Injectable({
    providedIn: 'root',
})
export class LayoutService {
    _config: AppConfig = {
        ripple: false,
        inputStyle: 'outlined',
        menuMode: 'static',
        colorScheme: 'light',
        theme: 'lara-light-teal',
        saveTheme: true,
        scale: 12,
    };

    config = signal<AppConfig>(this._config);

    state: LayoutState = {
        staticMenuDesktopInactive: false,
        overlayMenuActive: false,
        profileSidebarVisible: false,
        configSidebarVisible: false,
        staticMenuMobileActive: false,
        menuHoverActive: false,
    };

    private configUpdate = new Subject<AppConfig>();

    private overlayOpen = new Subject<any>();

    configUpdate$ = this.configUpdate.asObservable();

    overlayOpen$ = this.overlayOpen.asObservable();

    constructor(
        private router: Router
    ) {
        const savedTheme = localStorage.getItem('theme');
        const savedColorScheme = localStorage.getItem('colorScheme');
    
        if (savedTheme && savedColorScheme) {
            this.config.update((config) => ({
                ...config,
                theme: savedTheme,
                colorScheme: savedColorScheme,
            }));
        }
    
        effect(() => {
            const config = this.config();
            if (this.updateStyle(config)) {
                this.changeTheme();
            }
            this.changeScale(config.scale);
            this.onConfigUpdate();
        });
    }
    
    updateStyle(config: AppConfig) {
        return (
            config.theme !== this._config.theme ||
            config.colorScheme !== this._config.colorScheme ||
            config.saveTheme !== this._config.saveTheme
        );
    }

    onConfigUpdate() {
        this._config = { ...this.config() };
        this.configUpdate.next(this.config());
    }

    changeTheme() {
        const config = this.config();

        if (config.saveTheme) {
            localStorage.setItem('theme', config.theme);
            localStorage.setItem('colorScheme', config.colorScheme);
        }

        const themeLink = <HTMLLinkElement>document.getElementById('theme-css');
        const themeLinkHref = themeLink.getAttribute('href')!;
        const newHref = themeLinkHref
            .split('/')
            .map((el) =>
                el == this._config.theme
                    ? (el = config.theme)
                    : el == `theme-${this._config.colorScheme}`
                    ? (el = `theme-${config.colorScheme}`)
                    : el
            )
            .join('/');

        this.replaceThemeLink(newHref);

        console.log(config.theme)
        console.log(config.colorScheme)
        console.log(config.saveTheme)
        console.log(localStorage.getItem('theme'))
        console.log(localStorage.getItem('colorScheme'))
    }

How can I get this to work?

Thank you!

How to handle TransactionExpiredBlockheightExceededError when submitting a transaction on Solana

I’m working on a Solana project where I need to swap tokens using the Jupiter API. The code occasionally runs properly (successful transaction), but I usually get an issue where the transaction expired and failed with the TransactionExpiredBlockheightExceededError even after retrying with a new blockhash.

I’ve tried hardcoding prioritizationFeeLamports to a set value instead of auto, and also tried using dynamicComputeUnitLimit: true

import { Connection, Keypair, VersionedTransaction, TransactionExpiredBlockheightExceededError } from '@solana/web3.js';
import fetch from 'cross-fetch';
import { Wallet } from '@project-serum/anchor';
import bs58 from 'bs58';
import { privateKey } from './header.js';
import { publicKey } from './header.js';

// Connection to the Solana mainnet
const connection = new Connection('https://api.mainnet-beta.solana.com', 'confirmed');

// Convert privateKey to a Uint8Array using bs58 decoding
const wallet = new Wallet(Keypair.fromSecretKey(bs58.decode(privateKey)));

// Define the mint addresses as constants
const INPUT_MINT = 'So11111111111111111111111111111111111111112';
const OUTPUT_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
const amount = 10000000;

// Define other parameters
const slippageBps = 50;

// Use the constants in the URL
const url = `https://quote-api.jup.ag/v6/quote?inputMint=${INPUT_MINT}&outputMint=${OUTPUT_MINT}&amount=${amount}&slippageBps=${slippageBps}`;
console.log(url);  // Just to check the URL with the constants

// Fetch quote response
const quoteResponse = await fetch(url).then(res => res.json());
console.log({ quoteResponse });

// Get serialized transactions for the swap
const { swapTransaction } = await (
  await fetch('https://quote-api.jup.ag/v6/swap', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      quoteResponse,
      userPublicKey: publicKey,
      wrapAndUnwrapSol: true,
      prioritizationFeeLamports: "auto",
    })
  })
).json();

// Deserialize the transaction
const swapTransactionBuf = Buffer.from(swapTransaction, 'base64');
var transaction = VersionedTransaction.deserialize(swapTransactionBuf);
console.log(transaction);

// Sign the transaction
transaction.sign([wallet.payer]);

// Execute the transaction
const rawTransaction = transaction.serialize();
console.log(rawTransaction);

const sendTransaction = async () => {
  let txid;  // Declare txid here to use it later in case of retry
  try {
    // Fetch the latest blockhash just before sending the transaction
    const latestBlockHash = await connection.getLatestBlockhash();
    console.log(latestBlockHash);

    // Send the transaction
    txid = await connection.sendRawTransaction(rawTransaction, {
      skipPreflight: true,
      maxRetries: 2
    });

    // Confirm the transaction
    await connection.confirmTransaction({
      blockhash: latestBlockHash.blockhash,
      lastValidBlockHeight: latestBlockHash.lastValidBlockHeight,
      signature: txid
    });

    console.log(`Transaction confirmed: https://solscan.io/tx/${txid}`);
  } catch (error) {
    if (error instanceof TransactionExpiredBlockheightExceededError) {
      console.error('Transaction expired, resubmitting...');
      
      // Retry by getting the latest blockhash again
      const newBlockHash = await connection.getLatestBlockhash();
      console.log('Using new blockhash for retry:', newBlockHash);
      
      // Update transaction with the new blockhash
      const retryTransaction = VersionedTransaction.deserialize(swapTransactionBuf);
      retryTransaction.sign([wallet.payer]);
      
      // Resend with the new blockhash
      txid = await connection.sendRawTransaction(retryTransaction.serialize(), {
        skipPreflight: true,
        maxRetries: 2
      });

      console.log("Retrying with new blockhash...");

      // Confirm the transaction again with the new blockhash
      await connection.confirmTransaction({
        blockhash: newBlockHash.blockhash,
        lastValidBlockHeight: newBlockHash.lastValidBlockHeight,
        signature: txid
      });

      console.log(`Transaction retried and confirmed: https://solscan.io/tx/${txid}`);
    } else {
      console.error('Error confirming transaction:', error);
    }
  }
};

sendTransaction();

Output:

TransactionExpiredBlockheightExceededError: Signature 2PT8n78c9YC5CH7Kp6YfBHgwMHe67iRpirQN4aNKSqDAo8uYwenxCyhWjYzUKnb3u4GdLBgrw37jLkXgq9bWBQUK has expired: block height exceeded.

need a solution to rotate a 3D model in html and javascript

I have implemented a slider in html, css and javascript. there is 3D model glb file is render on every slide. The problem I’m facing is that on last slide the model is rotatable while on previous slides it’s not rotating.
example: if there are 4 slides there model is rotating on 4th slides and not rorating on first three slides. Can anyone help to fix this problem.

I’m using model-viewer for displaying 3D model and camera-controls to rotate so camera-controls are not working on every slide.

<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>
    <script>
        (function () {
            function init(item) {
                var items = item.querySelectorAll('li'),
                    current = 0;

                var prevbtn = document.querySelector('.prev');
                var nextbtn = document.querySelector('.next');
                var counter = document.querySelector('.counter span:first-child');

                items[current].classList.add("current");

                var navigate = function (dir) {
                    items[current].classList.remove("current");

                    if (dir === 'right') {
                        current = current < items.length - 1 ? current + 1 : 0;
                    } else {
                        current = current > 0 ? current - 1 : items.length - 1;
                    }

                    items[current].classList.add("current");
                    counter.textContent = current + 1;
                }

                prevbtn.addEventListener('click', function () {
                    navigate('left');
                });

                nextbtn.addEventListener('click', function () {
                    navigate('right');
                });

                document.addEventListener('keydown', function (ev) {
                    var keyCode = ev.keyCode || ev.which;
                    switch (keyCode) {
                        case 37:
                            navigate('left');
                            break;
                        case 39:
                            navigate('right');
                            break;
                    }
                });

                item.addEventListener('touchstart', handleTouchStart, false);
                item.addEventListener('touchmove', handleTouchMove, false);
                var xDown = null;
                var yDown = null;

                function handleTouchStart(evt) {
                    xDown = evt.touches[0].clientX;
                    yDown = evt.touches[0].clientY;
                }

                function handleTouchMove(evt) {
                    if (!xDown || !yDown) return;

                    var xUp = evt.touches[0].clientX;
                    var yUp = evt.touches[0].clientY;
                    var xDiff = xDown - xUp;
                    var yDiff = yDown - yUp;

                    if (Math.abs(xDiff) > Math.abs(yDiff)) {
                        navigate(xDiff > 0 ? 'right' : 'left');
                    }

                    xDown = null;
                    yDown = null;
                }
            }

            [].slice.call(document.querySelectorAll('.cd-slider')).forEach(function (item) {
                init(item);
            });
        })();
</script>
<div class="cd-slider">
            <!-- Scrolling Text Background -->
            <div class="scrolling-text">
                <p>Special Offers - New Collection - Limited Edition - Sale</p>
                <p>Special Offers - New Collection - Limited Edition - Sale</p>
            </div>

            <ul>
                <li class="current">
                    <div class="image">
                        <section id="model-section">
                            <model-viewer class="model" autoplay camera-controls disable-zoom src="./Aztec.glb"></model-viewer>
                        </section>
                    </div>
                    <div class="content">
                        <h2>Jackets Collection 2017</h2>
                        <p>
                            Lorem ipsum dolor sit amet consectetur adipisicing elit. <br>
                            Esse, eum sapiente laboriosam eligendi minus similique. <br>
                            Repellat aut earum modi, sunt doloribus ullam deleniti saepe, <br>
                            itaque totam pariatur corporis error ut?
                        </p>
                    </div>
                </li>
                <li>
                    <div class="image">
                        <section id="model-section">
                            <model-viewer class="model" autoplay camera-controls disable-zoom src="./Aztec.glb"></model-viewer>
                        </section>
                    </div>
                    <div class="content">
                        <h2>Accessories</h2>
                        <p>
                            Lorem ipsum dolor sit amet consectetur adipisicing elit. <br>
                            Esse, eum sapiente laboriosam eligendi minus similique. <br>
                            Repellat aut earum modi, sunt doloribus ullam deleniti saepe, <br>
                            itaque totam pariatur corporis error ut?
                        </p>
                    </div>
                </li>

                <li>
                    <div class="image">
                        <section id="model-section">
                            <model-viewer class="model" autoplay camera-controls disable-zoom src="./Aztec.glb"></model-viewer>
                        </section>
                    </div>
                    <div class="content">
                        <h2>Accessories</h2>
                        <p>
                            3
                        </p>
                    </div>
                </li>

                <li>
                    <div class="image">
                        <section id="model-section">
                            <model-viewer class="model" autoplay camera-controls disable-zoom src="./Aztec.glb"></model-viewer>
                        </section>
                    </div>
                    <div class="content">
                        <h2>Accessories</h2>
                        <p>
                            4
                        </p>
                    </div>
                </li>

                <li>
                    <div class="image">
                        <section id="model-section">
                            <model-viewer class="model" autoplay camera-controls disable-zoom src="./Aztec.glb"></model-viewer>
                        </section>
                    </div>
                    <div class="content">
                        <h2>Accessories</h2>
                        <p>
                            5
                        </p>
                    </div>
                </li>

                <li>
                    <div class="image">
                        <section id="model-section">
                            <model-viewer class="model" autoplay camera-controls disable-zoom src="./Aztec.glb"></model-viewer>
                        </section>
                    </div>
                    <div class="content">
                        <h2>Accessories</h2>
                        <p>
                            6
                        </p>
                    </div>
                </li>

                <li>
                    <div class="image">
                        <section id="model-section">
                            <model-viewer class="model" autoplay camera-controls disable-zoom src="./Aztec.glb"></model-viewer>
                        </section>
                    </div>
                    <div class="content">
                        <h2>Accessories</h2>
                        <p>
                            7
                        </p>
                    </div>
                </li>

                <li>
                    <div class="image">
                        <section id="model-section">
                            <model-viewer class="model" autoplay camera-controls disable-zoom src="./Aztec.glb"></model-viewer>
                        </section>
                    </div>
                    <div class="content">
                        <h2>Accessories</h2>
                        <p>
                            8
                        </p>
                    </div>
                </li>

                <li>
                    <div class="image">
                        <section id="model-section">
                            <model-viewer class="model" autoplay camera-controls disable-zoom src="./Aztec.glb"></model-viewer>
                        </section>
                    </div>
                    <div class="content">
                        <h2>Accessories</h2>
                        <p>
                            9
                        </p>
                    </div>
                </li>

                <li>
                    <div class="image">
                        <section id="model-section">
                            <model-viewer class="model" autoplay camera-controls disable-zoom src="./Aztec.glb"></model-viewer>
                        </section>
                    </div>
                    <div class="content">
                        <h2>Accessories</h2>
                        <p>
                            10
                        </p>
                    </div>
                </li>
            </ul>
        </div>

        <!-- Slider Navigation -->
        <nav class="nav_arrows">
            <button class="prev" aria-label="Previous Slide">❮</button>
            <div class="counter">
                <span class="navigation-number">1</span><span class="navigation-number">/10</span>
            </div>
            <button class="next" aria-label="Next Slide">❯</button>
        </nav>
        .cd-slider {
            position: relative;
            width: 100%;
            height: 100vh;
        }

        .cd-slider ul {
            list-style: none;
            position: relative;
            width: 100%;
            height: 100%;
            display: flex;
            overflow: hidden;
        }

        .cd-slider li {
            position: absolute;
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            transition: opacity 0.5s ease;
            opacity: 0;
            transform: translateY(100px);
        }

        .cd-slider li.current {
            opacity: 1;
            transform: translateY(0);
            animation: slideIn 0.7s ease-out;
        }

        .cd-slider .image {
            width: 80%;
            height: 80%;
            background-size: contain;
            background-position: center;
            background-repeat: no-repeat;
            z-index: 2;
            position: relative;
        }

        .cd-slider .content {
            position: absolute;
            bottom: 20px;
            left: 100px;
            color: #fff;
            padding: 10px 20px;
            border-radius: 8px;
            opacity: 0;
            transform: translateY(50px);
            animation: contentSlideIn 0.7s ease-out forwards;
            animation-delay: 0.2s;
            z-index: 3;
        }

        .cd-slider .content h2 {
            margin-bottom: 5px;
            font-size: 1.8rem;
        }

        .cd-slider .content a {
            color: #ffcc00;
            text-decoration: none;
        }

        .nav_arrows {
            position: absolute;
            bottom: 20px;
            right: 100px;
            display: flex;
            align-items: center;
        }

        .nav_arrows button {
            background: transparent;
            border: 3px solid white !important;
            color: #fff;
            border: none;
            padding: 5px 15px;
            margin: 0 5px;
            cursor: pointer;
            border-radius: 20%;
            font-size: 1.2rem;
        }

        .nav_arrows button:hover {
            background: white;
            color: black;
        }

        .nav_arrows .counter {
            color: #333;
            font-size: 1rem;
            margin: 0 10px;
        }

        .navigation-number {
            color: white;
        }

        /* Scrolling text styling */
        .scrolling-text {
            position: absolute;
            top: 50%;
            width: 200%;
            white-space: nowrap;
            overflow: hidden;
            z-index: 0;
            transform: translateY(-50%);
            display: flex;
        }

        .scrolling-text p {
            font-size: 10rem;
            color: white;
            animation: scroll 30s linear infinite;
            margin-right: 50px;
        }

        /* Keyframes for scrolling text animation */
        @keyframes scroll {
            0% {
                transform: translateX(0);
            }

            100% {
                transform: translateX(-50%);
            }
        }

        /* Keyframe for slide-in animation */
        @keyframes slideIn {
            0% {
                transform: translateY(100px);
                opacity: 0;
            }

            100% {
                transform: translateY(0);
                opacity: 1;
            }
        }

        /* Keyframe for content slide-in animation */
        @keyframes contentSlideIn {
            0% {
                transform: translateY(50px);
                opacity: 0;
            }

            100% {
                transform: translateY(0);
                opacity: 1;
            }
        }


        @media only screen and (max-width: 900px) {
            .cd-slider .image {
                margin-left: auto;
                margin-right: auto;
            }

            .cd-slider .content {
                bottom: 100px;
                left: 0;
            }

            .nav_arrows {
                position: relative;
                bottom: 70px;
                right: 0;
                left: 50%;
                transform: translateX(-50%);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 1;
            }
        }
        @media only screen and (max-width: 767px){
            .scrolling-text p{
                font-size: 5rem;
            }
        }


        #model-section{
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .model{
            display: flex;
            justify-content: center;
            align-items: center;
            width: 500px;
            height: 500px;
        }

I cant seem to find out why my code if failing to get a snapshot in my react expo project?





import { View, StyleSheet, Platform } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import { useState, useRef } from 'react';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import * as MediaLibrary from 'expo-media-library';
import { captureRef } from 'react-native-view-shot';
import { type ImageSource } from "expo-image";

import Button from '@/components/Button';
import ImageViewer from '@/components/ImageViewer';
import IconButton from '@/components/IconButton';
import CircleButton from '@/components/CircleButton';
import EmojiPicker from '@/components/EmojiPicker';
import EmojiList from '@/components/EmojiList';
import EmojiSticker from '@/components/EmojiSticker';

const PlaceholderImage = require('@/assets/images/background-image.png');

export default function Index() {
  const [selectedImage, setSelectedImage] = useState<string | undefined>(undefined);
  const [showAppOptions, setShowAppOptions] = useState<boolean>(false);
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [pickedEmoji, setPickedEmoji] = useState<ImageSource | undefined>(undefined);
  const [status, requestPermission] = MediaLibrary.usePermissions();
  const imageRef = useRef<View>(null);

  if (status === null) {
    requestPermission();
  }

  const pickImageAsync = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ['images'],
      allowsEditing: true,
      quality: 1,
    });

    if (!result.canceled) {
      setSelectedImage(result.assets[0].uri);
      setShowAppOptions(true);
    } else {
      alert('You did not select any image.');
    }
  };

  const onReset = () => {
    setShowAppOptions(false);
  };

  const onAddSticker = () => {
    setIsModalVisible(true);
  };

  const onModalClose = () => {
    setIsModalVisible(false);
  };
`problematic function`
  const onSaveImageAsync = async () => {
    try {
      if (!imageRef.current) {
        throw new Error('View reference is not available');
      }

      const localUri = await captureRef(imageRef.current, {
        height: 440,
        quality: 1,
        format: 'png', // Explicitly set format
        result: Platform.OS === 'ios' ? 'tmpfile' : 'data-uri', // Different result types for iOS/Android
      });

      if (!localUri) {
        throw new Error('Failed to capture view');
      }

      await MediaLibrary.saveToLibraryAsync(localUri);
      alert('Saved!');
    } catch (e) {
      console.log(e);
    }
  };

  return (
    <GestureHandlerRootView style={styles.container}>
      <View style={styles.imageContainer}>
        <View ref={imageRef} collapsable={false}>
          <ImageViewer imgSource={PlaceholderImage} selectedImage={selectedImage} />
          {pickedEmoji && <EmojiSticker imageSize={40} stickerSource={pickedEmoji} />}
        </View>
      </View>
      {showAppOptions ? (
        <View style={styles.optionsContainer}>
          <View style={styles.optionsRow}>
            <IconButton icon="refresh" label="Reset" onPress={onReset} />
            <CircleButton onPress={onAddSticker} />
            <IconButton icon="save-alt" label="Save" onPress={onSaveImageAsync} />
          </View>
        </View>
      ) : (
        <View style={styles.footerContainer}>
          <Button theme="primary" label="Choose a photo" onPress={pickImageAsync} />
          <Button label="Use this photo" onPress={() => setShowAppOptions(true)} />
        </View>
      )}
      <EmojiPicker isVisible={isModalVisible} onClose={onModalClose}>
        <EmojiList onSelect={setPickedEmoji} onCloseModal={onModalClose} />
      </EmojiPicker>
    </GestureHandlerRootView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#25292e',
    alignItems: 'center',
  },
  imageContainer: {
    flex: 1,
  },
  footerContainer: {
    flex: 1 / 3,
    alignItems: 'center',
  },
  optionsContainer: {
    position: 'absolute',
    bottom: 80,
  },
  optionsRow: {
    alignItems: 'center',
    flexDirection: 'row',
  },
});




this is the page im getting the problem, the error is probably something with the onSaveImageAsync function.
I couldnt get chatgpt to find the problem

the message i get when i try to save is
[Error: Failed to snapshot view tag 14]

i tried asking chatgpt and claudia but they couldnt help,

this code is also the original tutorial code from
https://docs.expo.dev/tutorial/screenshot/

WebSocket Connection Failure and Unexpected Socket Closure in Django Channels

I’m experiencing issues with establishing and maintaining a WebSocket connection in my Django project using Django Channels. I’ve set up a notification system that uses WebSockets to broadcast messages to connected clients. However, I’m encountering two errors:

  1. “WebSocket connection to ‘ws://127.0.0.1:8000/ws/notification/broadcast/’ failed”
  2. “Chat socket closed unexpectedly”
    Here’s my code:

routing.py:

from django.urls import re_path  
from . import consumers  
  
websocket_urlpatterns = [  
   re_path(r'ws/notification/(?P<room_name>w+)/$', consumers.NotificationConsumer.as_asgi()),  
]

views.py:

def notification_view(request):  
   return render(request,'person/notification.html',{'room_name': "broadcast"})

settings.py:

CHANNEL_LAYERS = {  
   'default': {  
      'BACKEND': 'channels_redis.core.RedisChannelLayer',  
      'CONFIG': {  
        "hosts": [('127.0.0.1', 6379)],  
      },  
   },  
}

consumer_context_processor.py:

from notification_app.models import BroadcastNotification  
def notifications(request):  
   allnotifications = BroadcastNotification.objects.all()  
   return {'notifications': allnotifications}

models.py:

class BroadcastNotification(models.Model):  
   message = models.TextField()  
   notification_image=models.ImageField(upload_to="notification",default="notification.jpg",blank=True,null=True)  
   notification_link = models.URLField(max_length=10000, help_text="Add a valid URL",blank=True,null=True)  
   broadcast_on = models.DateTimeField()  
   sent = models.BooleanField(default=False)  
  
   class Meta:  
      ordering = ['-broadcast_on']  
  
@receiver(post_save, sender=BroadcastNotification)  
def notification_handler(sender, instance, created, **kwargs):  
   # call group_send function directly to send notificatoions or you can create a dynamic task in celery beat  
   if created:  
      schedule, created = CrontabSchedule.objects.get_or_create(hour = instance.broadcast_on.hour, minute = instance.broadcast_on.minute, day_of_month = instance.broadcast_on.day, month_of_year = instance.broadcast_on.month)  
      task = PeriodicTask.objects.create(crontab=schedule, name="broadcast-notification-"+str(instance.id), task="notifications_app.tasks.broadcast_notification", args=json.dumps((instance.id,)))

task.py:

@shared_task(bind = True)  
def broadcast_notification(self, data):  
   print(data)  
   try:  
      notification = BroadcastNotification.objects.filter(id = int(data))  
      if len(notification)>0:  
        notification = notification.first()  
        channel_layer = get_channel_layer()  
        loop = asyncio.new_event_loop()  
        asyncio.set_event_loop(loop)  
        loop.run_until_complete(channel_layer.group_send(  
           "notification_broadcast",  
           {  
              'type': 'send_notification',  
              'message': json.dumps(notification.message),  
           }))  
        notification.sent = True  
        notification.save()  
        return 'Done'  
  
      else:  
        self.update_state(  
           state = 'FAILURE',  
           meta = {'exe': "Not Found"}  
        )  
  
        raise Ignore()  
  
   except:  
      self.update_state(  
           state = 'FAILURE',  
           meta = {  
                'exe': "Failed"  
                # 'exc_type': type(ex).__name__,  
                # 'exc_message': traceback.format_exc().split('n')  
                # 'custom': '...'  
              }  
        )  
  
      raise Ignore()

Frontend (JavaScript):

{{ room_name|json_script:"room-name" }}  
   <script>  
      const roomName = JSON.parse(document.getElementById('room-name').textContent);  
  
      const notificationSocket = new WebSocket(  
        'ws://'  
        + window.location.host  
        + '/ws/notification/'  
        + roomName  
        + '/'  
      );  
  
      notificationSocket.onmessage = function(e) {  
        const data = JSON.parse(e.data);  
        //document.querySelector('#chat-log').value += (data.message + 'n');  
        console.log(data);  
        document.getElementById("notifications-dropdown").innerHTML = "<li class='dropdown-item'>" + data + "</li><hr class='dropdown-divider'>" + document.getElementById("notifications-dropdown").innerHTML;  
        document.getElementById("notification-badge").innerHTML = parseInt(document.getElementById("notification-badge").innerHTML) + 1;  
      };  
  
      notificationSocket.onclose = function(e) {  
        console.error('Chat socket closed unexpectedly');  
      };  
   </script>

consumers.py:

class NotificationConsumer(AsyncWebsocketConsumer):  
   async def connect(self):  
      self.room_name = self.scope['url_route']['kwargs']['room_name']  
      self.room_group_name = 'notification_%s' % self.room_name  
  
      # Join room group  
      await self.channel_layer.group_add(  
        self.room_group_name,  
        self.channel_name  
      )  
  
      await self.accept()  
  
   async def disconnect(self, close_code):  
      # Leave room group  
      await self.channel_layer.group_discard(  
        self.room_group_name,  
        self.channel_name  
      )  
  
  
   # Receive message from room group  
   async def send_notification(self, event):  
      message = json.loads(event['message'])  
  
      # Send message to WebSocket  
      await self.send(text_data=json.dumps(message))

I’ve tried to follow the official Django Channels documentation and examples, but I’m still facing these issues. Can anyone help me identify the problem and provide a solution?

How to target dynamically rendered tbody with jquery selector

I need to hide an entire column in my table(see below: id=DrugReturn). I am currently hiding the accountability date header and footer using jquery selectors that reference the class of the accountability date header and footer. However the body of the table is rendered dynamically so there is no way Im aware of to add a class or id to the rows of data in my accountatbility date column. I need to be able to add a selector inorder to hide these column rows. I can access the appropriate column header and footer with jQuery selectors but since the tbody is rendered dynamically (dataset) I don’t know how to target it. Have tried and failed to use the index but I may be getting the logic wrong.

@{
    ViewBag.Title = $"Site {YPrimeSession.Instance.SingleSiteAlias} Destruction";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<ul class="breadcrumb">
    <li>
        @Html.Partial("~/Views/UI/HomeLink.cshtml", new { })
    </li>
    <li>
        @Html.PrimeActionLink($"{YPrimeSession.Instance.SingleSiteAlias} Management", "Index", "Site")
    </li>
    <li>
        @Html.ActionLink(Model.Location.Site.Name, "EditSite", "Site", new { id = Model.Location.Site.Id }, null)
    </li>
</ul>

<div class="grid-wrapper">
    <h2>@YPrimeSession.Instance.SingleSiteAlias Destruction</h2>

    @using (Html.BeginForm("ReturnDrug", "DrugReturn", FormMethod.Post, new { @class = "form-horizontal", id = "DrugReturnForm" }))
    {
    @Html.HiddenFor(x => x.Location.Site.Name)
    @Html.HiddenFor(x => x.Location.Site.Id)
    @Html.HiddenFor(x => x.DrugReturnControlId)

        if (TempData["ErrorMessage"] != null && !string.IsNullOrEmpty(TempData["ErrorMessage"].ToString()))
        {
    <div class="alert alert-danger">
        @TempData["ErrorMessage"]
    </div>
        }

    <div id="kitStatusUpdates">

        <div class="form-group" id="ApplyToAll">
            <label class="control-label col-md-4">Apply Status To All Displayed Records</label>
            <div class="col-md-4">
                <select class="form-control col-md-4 standard" id="ApplyToAllSelect" onchange="ApplyStatusToAll($(this))"></select>
            </div>
        </div>

        <div class="form-group" id="ApplyAttributeToAll" style="display: none">
            <label class="control-label col-md-4">Add Attributes To All Displayed Records</label>

        </div>

        <div class="container-fluid">
            <div class="table-responsive">
                <table id="DrugReturn" class="table table-striped table-bordered display dataTable" cellspacing="0" width="100%">
                    <thead>
                        <tr>
                            <th>@YPrimeSession.Instance.SingleKitAlias Number</th>
                            <th>Current Status</th>
                            <th>@YPrimeSession.Instance.SinglePatientAlias Assigned</th>
                            <th class="accountability-date-header">Accountability Date</th>
                            <th>Selected Status</th>
                        </tr>
                    </thead>
                    <tfoot>
                        <tr>
                            <th id="kit_number">@YPrimeSession.Instance.SingleKitAlias Number</th>
                            <th id="current_status">Current Status</th>
                            <th id="patient_assigned">@YPrimeSession.Instance.SinglePatientAlias Assigned</th>
                            <th id="accountability_date" class="accountability-date-footer">Accountability Date</th>
                            <th class="hidesearch" id="selected_status">Selected Status</th>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-2 col-md-offset-5">
                <button id="save" type="submit" class="btn btn-primary btn-block panel-default" disabled>
                    Save <i class="fa fa-check"></i>
                </button>
            </div>
        </div>
    </div>
    }

</div>

@{
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    serializer.MaxJsonLength = int.MaxValue;
    var data = serializer.Serialize(Model.ReturnableDrugs);
}
<script>
    var url = "@Url.Action("GetDrugAvailableForReturn", "DrugReturn")";
    var siteId = '@Model.Location.Site.Id';
    var drugReturnControlId = '@Model.DrugReturnControlId';
    var AvailableStatuses = @Html.Raw(Json.Encode(Model.AvailableStatuses));
    var dataSet = @Html.Raw(data);

    var tableId = "@ViewBag.DrugReturn" || "DrugReturn";
    var table = $('#' + tableId).DataTable();

    table.columns().every(function () {
        var header = this.header();
        var footer = this.footer();
        var nodes = this.nodes();

        //how to target nodes like I target the header and footer?  Data for table is populated dynamically through: var dataSet = Html.Raw(data);

        if ($(header).hasClass('accountability-date-header')) {
            $(header).hide();
        }
        if ($(footer).hasClass('accountability-date-footer')) {
            $(footer).hide();
        }
    });

    table.columns.adjust().draw();
</script>
<script src="~/Scripts/Views/DrugReturn.js"></script>
<script src="~/Scripts/Views/SIteDestruction.js"></script>

Ive tried using the index position of the table cell but Im not sure I did this correctly. I dont want to alter the data itself if at all possible because this could affect other parts of a large project.

Why is the user data not being fetched correctly in my React Redux app despite `id` being fetched successfully?

I’m working on a React and Redux application where I fetch the user’s profile details after successful authentication. The id is being fetched correctly from the useParams hook, but the user data is not displaying as expected.

Here’s a breakdown of my setup:

  1. Auth Context: I’m using a context provider to manage authentication states and store the token in localStorage. The token is being retrieved and decoded properly.

  2. Redux Actions: The fetchProfile action makes an API call to get the user’s profile using Axios.

    export const fetchProfile = () => async (dispatch) => {
      dispatch({ type: SET_PROFILE_LOADING, payload: true });
      try {
        const { data } = await axios.get(`${API_URL}/user/me`);
        dispatch({ type: FETCH_PROFILE, payload: data });
      } catch (error) {
        handleError(error);
      } finally {
        dispatch({ type: SET_PROFILE_LOADING, payload: false });
      }
    };
    
  3. Redux Reducer: The reducer updates the state with the fetched profile data.

    case FETCH_PROFILE:
      return {
        ...state,
        user: {
          ...state.user,
          ...action.payload,
        },
      };
    
  4. Component: In the AccountDetails component, I fetch the user profile if the user is authenticated.

    useEffect(() => {
      if (isAuthenticated) {
        dispatch(fetchProfile());
      } else {
        console.warn("Token is null when trying to fetch profile.");
      }
    }, [dispatch, isAuthenticated]);
    
    useEffect(() => {
      console.log(user); // Debugging user data
    }, [user]);
    

However, the issue is that the user object from Redux state is either undefined or incomplete, even though the id from the URL (useParams) is fetched correctly, and the API call for fetching the profile seems successful. I’ve verified that:

  • The API is returning the correct data in the response.
  • The token is being sent with the request header.
  • The FETCH_PROFILE action is being dispatched.

What I’ve tried:

  • Logging the user state to check its value—it’s undefined initially and doesn’t update.
  • Verifying the API response directly in the network tab.
  • Ensuring the reducer updates the state correctly.
  • Confirming that fetchProfile is called when the component mounts.

Any help or suggestions to resolve this issue would be greatly appreciated. Let me know if more details are needed!

Flatten the array of objects and removing duplicate key entry

I have array of objects data as below where ID is duplicate key in nested array of object:

 const arr =  [
      {
        "First Name": "ABC",
        "Last Name": "XYZ",
        "Gender": "MALE",
        "Id": "123",
        "moreDetails": {
          "items": [
            {
              "Id": "123",
              "City": "BLR",
              "State": "KA"
            }
          ]
        }
      },
      {
        "First Name": "Test",
        "Last Name": "Me",
        "Gender": "FEMALE",
        "Id": "12345",
        "moreDetails": {
          "items": [
            {
              "Id": "12345",
              "City": "BLR",
              "State": "KA"
            }
          ]
        }
      }
    ]

Expecting below format data where ID is now with one entry and nested array is also flattened:

[
  {
    "First Name": "ABC",
    "Last Name": "XYZ",
    "Gender": "MALE",
    "Id": "123",
    "City": "BLR",
    "State": "KA"
  },
  {
    "First Name": "Test",
    "Last Name": "Me",
    "Gender": "FEMALE",
    "Id": "12345",
    "City": "BLR",
    "State": "KA"
  }
]

I tried using Array.flat() and Array.flat(Infinity) but then do not work on this data set.
I have also tried with simple for loop but not getting expected result. Can anyone please help with missing logic here.

const result2 = [];
for (let key in arr) {
if (arr.hasOwnProperty(key)) {
  if(!typeof arr[key].moreDetails === 'object'){
    result2.push(arr[key]);
  }else{
    for(let key2 in arr[key].moreDetails.items){
      result2.push(arr[key2]);
    }
  }
}
}

”Too Many Redirects Error“ on my Cloudflare Worker Application and I can’t figure out why

Firstly….

Hello! I am really new to StackOverflow and English isn’t my primary language.
If my question is bad (like lack of information or too long etc) I am sorry.

What I am doing

I have created a Cloudflare Worker Application to proxy images and I have assigned Custom Domain proxy.example.tld to it.

My DNS Setting

The proxy.example.tld is proxied via Cloudflare, while other records like example.tld or *.example.tld are DNS-only.
my dns setting(image)*

What happened?

The problem is, When fetching images from https://www.example.tld/logo.png, my Cloudflare Worker shows a ‘Too Many Redirects’ error if accessed through proxy.example.tld, but works fine with the Worker’s default domain.

….also www.example.tld is hosted on Cloud Compute and It’s configured to port forwarding to my Local Backend Server via VPN tunnel.
I use Nginx as PortForwarder and ZerotierVPN for tunnel.
My Nginx is configured to do https redirect and root domain to www subdomain redirect.

Shortly

My worker is configured to fetch to https://www.example.tld/logo.png, If I access to My worker via custom domain proxy.exampel.tld 1101 error happen (too many redirect),
However if access via exampleworker.johndoe.workers.dev It will fetch without error and show logo.png which is what I intent.

I tried changing Cors-Origin e.g. however it is not fix that issues.

This is my worker application code.

// workers.js I have only that! =)

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

function urlGen(text) {
  // this is generate error image, I do this because Cloudflare Worker did not support  Image Related API(s)...
  return "https://www.example.tld/WriteTextOnImage.php?text=" + btoa(text); // this php works fine!
}

// the reason I using base64 for URL is if URL have parameter or something special, It will be not work. so I encoded in Base64 for prevent from that.

async function handleRequest(request) {
  try {
    const url = new URL(request.url)
    const base64url = url.searchParams.get('img')
    if (!base64url) {
      return await fetchImage(urlGen("URL decoding Error,nURL is not encoded in base64 or have another issues."), 500)
    }

    const decodedUrl = decodeURIComponent(atob(base64url));
    const resp = await fetchImage(decodedUrl, 200);

    if ( resp == null ) {
      return await fetchImage(urlGen("Fetching image error,nImage not exist or origin is down, or blocked by security."), 500);
    }

    return resp;

  } catch (err) {
    return await fetchImage(urlGen("During handling request,nSome error happened."),500);
  }
}

async function fetchImage(decodedUrl, statusCode=200) {
  const imageResponse = await fetch(new Request(decodedUrl, {
    method: 'GET',
    headers: {
      'Referer': decodedUrl,
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36 (compatible; ImgProxy/1.0; +http://example.tld/imgbot.html)'
    }
  }))

  if ( !imageResponse.ok ) {
    return null;
  }

  return new Response(await imageResponse.blob(), {
    status: statusCode,
    headers: { 'Content-Type': imageResponse.headers.get('Content-Type') }
  });;
}

What’s my goal

I’d like to make my worker application fetch the URL that using domain www.example.tld, even if worker accessed via domain proxy.example.tld.

Thanks for reading.

Unexpected RangeError in Three.js

I’ve been using Three.js to generate 3D objects in my website and I just came across this problem yesterday.

I was gonna generate a PlaneGeometry
with widthSegments = 1100 and heightSegments = 17500

Now then the points would have been stored in a position array with

length = 3 * widthSegments * heightSegments = 57750000

which is way lower than the imposed 2^32 length limit of arrays.

But when I tried to run it, it threw a RangeError: Invalid array length

What?

Tried testing it on a Three.js playground, and got the same results.

How to scan and highlight tiny QR code similar camera on iphone using Javascript

I am developing a QR code scanning feature using JavaScript libraries. I’ve tried libraries like html5-qrcode and jsQR, and they work well for standard-sized QR codes. However, my application needs to scan very small QR codes, about 1 cm in size, which are difficult to detect. How can I improve the detection and highlight these tiny QR codes, similar to the seamless performance of the iPhone camera? I would greatly appreciate any suggestions or advice.
My QR code need to scan