How to create a writable byte stream I can evaluate?

I want to wrap a array, e.g. an Uint8Array, into a WriteStream so I can read its content later. How can I do that?

Background: For testing my winston logger, I want to set up a custom transport which just holds all the logged data in a manner I can evaluate it later. The example reads like this:

logger.add(new winston.transports.Stream({
  stream: fs.createWriteStream('/dev/null')
  /* other options */
}));

But if I create the stream like fs.createWriteStream('/dev/null', I cannot see its content. And why would I need fs anyway?

I figure I could try with an event listener on pipe, but this feels a bit overengineered.

Custom hook for Getting latitude and longitude and os name and version using typescript [closed]

import { useState, useEffect } from "react";

interface GeolocationData {
  latitude: number | null;
  longitude: number | null;
  osName: string;
  osVersion: string;
  error?: string;
}

const useGeolocationAndOS = (): GeolocationData => {
  const [location, setLocation] = useState<GeolocationData>({
    latitude: null,
    longitude: null,
    osName: "Unknown",
    osVersion: "Unknown",
  });

  useEffect(() => {
    // Get OS details
    const userAgent = navigator.userAgent;
    let osName = "Unknown";
    let osVersion = "Unknown";

    if (/Windows NT 10/.test(userAgent)) {
      osName = "Windows";
      osVersion = "10";
    } else if (/Windows NT 6.3/.test(userAgent)) {
      osName = "Windows";
      osVersion = "8.1";
    } else if (/Windows NT 6.2/.test(userAgent)) {
      osName = "Windows";
      osVersion = "8";
    } else if (/Windows NT 6.1/.test(userAgent)) {
      osName = "Windows";
      osVersion = "7";
    } else if (/Mac OS X (d+[_.]d+)/.test(userAgent)) {
      osName = "Mac OS";
      osVersion = RegExp.$1.replace("_", ".");
    } else if (/Android (d+.d+)/.test(userAgent)) {
      osName = "Android";
      osVersion = RegExp.$1;
    } else if (/iPhone OS (d+_d+)/.test(userAgent)) {
      osName = "iOS";
      osVersion = RegExp.$1.replace("_", ".");
    }

    setLocation((prev) => ({ ...prev, osName, osVersion }));

    // Get Geolocation
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          setLocation((prev) => ({
            ...prev,
            latitude: position.coords.latitude,
            longitude: position.coords.longitude,
          }));
        },
        (error) => {
          setLocation((prev) => ({ ...prev, error: error.message }));
        }
      );
    } else {
      setLocation((prev) => ({ ...prev, error: "Geolocation is not supported" }));
    }
  }, []);

  return location;
};

export default useGeolocationAndOS;

Cookies disappear page re-visit [duplicate]

I have a Webflow landingpage (example.com) and a Angular web-app on a subdomain (dashboard.example.com).

To ease up consent for tracking on both websites I am creating crossdomain cookies on said webflow landingpage which look like the following in the chrome browser application tab:

Name: consent   
Value: true  
Domain: .example.com    
Path: / 
Expires / Max Age: 2026-02-04T15:10:25.000Z 
Size: 11        
HttpOnly:
Secure: ✓   
SameSite: Strict    
Partition Key Site: 
Cross Site: 
Priority: Medium

and is set and updated at consent in the Webflow Custom Code in javascript:

const d = new Date();
d.setTime(d.getTime() + (365*24*60*60*1000)); // expires in 365 days
let expires = "expires="+ d.toUTCString() + ";"; 
document.cookie = "consent=true; " + expires + "path=/;SameSite=Strict;Secure;domain=.example.com;";

Now the cookie is set and even works and is visible on both example.com and dashboard.example.com. The only issue is, as soon as I close the browser window and open the webflow landingpage again, the cookies disappeared for some reason.

Feature hover state not working on Mapbox GL JS

I have added a hover state to the countries in my map, but the hover state only works in the Studio environment and not in any other external embed e.g. iframe or preview.

I have created a codepen to demonstrate the issue: https://codepen.io/jplatford/pen/emOrebx.

Mapbox provides the following snippet. I can see that it hits the handler because of the console log, but the state (name hover-state) never seems to take affect and change the colour of the country currently hovered over.

map.addInteraction("move-handler", {
  type: "mousemove",
  target: {
    "layerId": "available-countries"
},
  handler: (e) => {

    if (e.feature) {
      if (feature) {
        map.setFeatureState(feature, { ["hover-state"]: false });
      }

      feature = e.feature;
      console.log(feature);
      map.setFeatureState(feature, { ["hover-state"]: true });
    }

    if (feature) {
      map.setFeatureState(feature, { ["hover-state"]: false });
      feature = null;
    }
  }
});

res.download doesnt work even though the file exists [closed]

I am trying to download a file but it doesn’t work for some reason. The function I will send is running at a get request from a router file:

const downloadPayment = async (req, res) => {
    const { id } = req.params;
    if (!mongoose.Types.ObjectId.isValid(id)) {
        return res.status(404).send('No payment with that id');
    }

    const payment = await Payment.findById(id);

    if (!payment) {
        return res.status(404).send('No payment with that id');
    }

    /*if (fs.existsSync(`./util/outputs/TestSözleşme.xlsx`)) {
        console.log('Success');
    }*/

    res.download(`./util/outputs/${payment.title}.xlsx`, `${payment.title}.xlsx`);
};

It doesnt give any errors but also doesn’t download the file either.

Why does this authorization header cause a 401 status from X API’s Log in with X feature?

I’m trying to manually integrate with X API’s Login with X feature which follows OAuth 1.0a.

Given the request token POST request example here: https://docs.x.com/resources/fundamentals/authentication/guides/log-in-with-x

and given OAuth1.0a /initiate example here:
https://datatracker.ietf.org/doc/html/rfc5849#section-1.2

I’ve created the helper function below. When I send my POST request with an Authorization header created by the following function, I receive a status 401 code from X API’s /oauth/request_token endpoint. I expected a status 200 and to receive temporary credentials from the endpoint.

I’m now trying to figure out which part of this I’ve messed up.
I’ve ensured my ENV_VARS all have expected values and I’m console.logging the resulting Authorization header and to me it looks OK (Maybe it needs newlines after commas to be read properly?).


function createAuthorizationHeaderWithSignature() {
  const method = 'POST';

  const encodedCallbackUrl = encodeURIComponent(X_CALLBACK_URL);

  const params = {
    'oauth_callback': encodedCallbackUrl,
    'oauth_consumer_key': X_CLIENT_ID,
    'oauth_nonce': Math.random().toString(36).substring(2),
    'oauth_signature_method': 'HMAC-SHA1',
    'oauth_timestamp': Math.floor(Date.now() / 1000),
    'oauth_version': '1.0'
  };

  //@ts-ignore
  // Sort parameters and encode
  const sortedParams = Object.keys(params).sort().map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`).join('&');

  // Construct base string
  const baseString = encodeURIComponent(method) + '&' + encodeURIComponent(BASE_URL) + '&' + encodeURIComponent(sortedParams);

  // Construct encoded signature
  const signingKey = encodeURIComponent(X_CLIENT_SECRET!) + '&';
  const hmac = crypto.createHmac('sha1', signingKey);
  hmac.update(baseString);
  const signature = hmac.digest('base64');
  const encodedSignature = encodeURIComponent(signature);

  const authorizationHeader = `OAuth oauth_callback="${params.oauth_callback}",oauth_consumer_key="${params.oauth_consumer_key}",oauth_nonce="${params.oauth_nonce}",oauth_signature="${encodedSignature}",oauth_signature_method="${params.oauth_signature_method}",oauth_timestamp="${params.oauth_timestamp}",oauth_version="${params.oauth_version}"`;
  return authorizationHeader;
}

res.download doesnt work even though the file exists

I am trying to download a file but it doesn’t work for some reason. The function I will send is running at a get request from a router file:

const downloadPayment = async (req, res) => {
    const { id } = req.params;
    if (!mongoose.Types.ObjectId.isValid(id)) {
        return res.status(404).send('No payment with that id');
    }

    const payment = await Payment.findById(id);

    if (!payment) {
        return res.status(404).send('No payment with that id');
    }

    /*if (fs.existsSync(`./util/outputs/TestSözleşme.xlsx`)) {
        console.log('Success');
    }*/

    res.download(`./util/outputs/${payment.title}.xlsx`, `${payment.title}.xlsx`);
};

It doesnt give any errors but also doesn’t download the file either.

I am getting this error in next Js project Even though I have the output I needed. I think it is because the changes made in Nextjs 15

So I was working on my project I wanted to make a dynamic url function where if you visit different URLs you get different content in the same page, So if you visit ‘wuilder.in/client1’ you get different title and description and if you visit ‘wuilder.in/client2’ you get another title and description I created this page inside app/[client]/page.tsx:

import brandingData from '@/data/brandingData';

export default function ClientWebsite({ params }: { params: { client: string } }) {
    const defaultConfig = { 
        title: "Welcome to Wuilder", 
        bgColor: "bg-gray-500",
        logo: "/logos/default.png",
        description: "Powerful websites for every business."
    };

    const clientConfig = brandingData[params.client] || defaultConfig;

    return (
        <div className='min-h-screen flex flex-col items-center justify-center'>
            <img src={clientConfig.logo} alt="Logo" className="w-32 h-32 mb-4" />
            <h1 className="text-white text-3xl font-bold">{clientConfig.title}</h1>
            <p className="text-white text-lg mt-2">{clientConfig.description}</p>
        </div>
    );
}

It worked fine and fetching and displaying all the data from the brandingData.ts:

type BrandingConfig = {
    title: string;
    logo: string;
    description: string;
};

const brandingData: Record<string, BrandingConfig> = {
    client1: { 
        title: "Client 1 - Tech Solutions", 
        logo: "/space/satelite-launch.jpg",
        description: "Innovative tech solutions for modern businesses.",
    },
    client2: { 
        title: "Client 2 - Fashion Hub", 
        logo: "/space/gabriele-garanzelli-PzO_CitnJdI-unsplash.jpg",
        description: "Trendy fashion and lifestyle brand.",
    },
    client3: { 
        title: "Client 3 - Coffee Express", 
        logo: "/space/spacex-OHOU-5UVIYQ-unsplash.jpg",
        description: "The best coffee experience, delivered to you.",
    }
};

export default brandingData;

but I am getting this annoying error in my console:

Error: Route "/[client]" used `params.client`. `params` should be awaited before using its properties. Learn more: https://nextjs.org/docs/messages/sync-dynamic-apis
    at client (app[client]page.tsx:11:45)
   9 |     };
  10 |
> 11 |     const clientConfig = brandingData[params.client] || defaultConfig;
     |                                             ^
  12 |
  13 |     return (
  14 |         <div className='min-h-screen flex flex-col items-center justify-center'>
 GET /client3 200 in 203ms

I tried everything I don’t know what to do

I am expecting this error to be gone, Help me!

Why does Google Pub/Sub deliver messages with the same orderingKey in parallel before calling ack()?

I am working with Google Cloud Pub/Sub, and I am trying to ensure that messages with the same orderingKey are processed in order, as stated in the official documentation. However, I notice that messages with the same orderingKey are delivered in parallel, even though I haven’t yet called message.ack() for the previous message.

Here are the details of my configuration and implementation:

  1. Subscription: Created with –enable-message-ordering to respect
    message order.
  2. Message Publishing: Messages are published with the exact same
    orderingKey.
  3. Subscriber: I am using a Node.js subscriber with explicit message
    handling and asynchronous processing. I ensure that message.ack() is
    only called after the message has been fully processed.

Code Example:

Publishing:

const { PubSub } = require("@google-cloud/pubsub");
const pubSubClient = new PubSub();

const publishMessage = async (orderingKey, data) => {
  const dataBuffer = Buffer.from(JSON.stringify(data));
  await pubSubClient
    .topic("YOUR_TOPIC_NAME")
    .publishMessage({
      data: dataBuffer,
      orderingKey: orderingKey,
    });
};

publishMessage("my-key", { orderId: "123" });

Subscriber:

const subscription = pubSubClient.subscription("YOUR_SUBSCRIPTION_NAME");

subscription.on("message", async (message) => {
  try {
    console.log(`Message received: ${message.id}, orderingKey: ${message.attributes.orderingKey}`);
    const data = JSON.parse(message.data);

    // Simulate long processing
    await new Promise((resolve) => setTimeout(resolve, 5000));
    console.log(`Message processed: ${data.orderId}`);
  } catch (err) {
    console.error(`Error: ${err}`);
    return;
  } finally {
    console.log(`Calling message.ack() for: ${message.id}`);
    message.ack();
  }
});

Problem:

Despite this configuration:

Messages with the same orderingKey are delivered and executed in parallel.
This happens even though I haven’t yet called message.ack().

What I Want:

I want to ensure that Google Pub/Sub processes messages with the same orderingKey sequentially, meaning:

The next message is only delivered after the previous one has been marked as ack().

Questions:

  1. Why does Pub/Sub deliver messages with the same orderingKey in
    parallel in my case?
  2. How can I configure my subscriber or system to ensure that messages
    are strictly sequential with orderingKey?

Additional Context:

I am using Node.js.
The subscription was created with –enable-message-ordering.
I want to avoid adding local logic (like a queue) to manage this manually.

How to Add Grid Spacing issues in mui?

enter image description hereif you’re using Material-UI (MUI) Grid inside your dashboard and you’ve already added spacing, but it’s not showing, there could be a few reasons for this. I’ll walk you through some potential causes and how to fix them.

    < Grid container spacing={4} my={2}>
 <Grid  xs={12} md={4} key={index}>
</Grid>
</Grid>

Problem Solving :Get the wrong id when product is clicked

I need a help of solving my below issues:

I have generated dynamically cards with javascript and try to get the id when product is clicked.The results what i Have done are:

1)when click the first product it gets the wrong id,showing the details of the last product
2)the event listener works only for the first element so i can’t show the other product.

product-list.js

    let cardData = [
    {
        id: 1,
        imgFile: 'images/products/marievi5.jpg',
        heading: 'Marievi the Influencer',
        body: 'this is card body',
        price: 150,


    },
    {
        id: 2,
        imgFile: 'images/products/rock1.jpg',
        heading: 'card 2',
        body: 'this is card body',
        price: 200,

    },
    {
        id: 3,
        imgFile: 'images/products/marievi5.jpg',
        heading: 'card 3',
        body: 'this is card body',
        price: 400,

    },
    {
        id: 4,
        imgFile: 'images/products/marievi5.jpg',
        heading: 'card 4',
        body: 'this is card body',
        price: 300,

    },
];


const createCard = () => {
    
    let cardContainer = document.querySelector('.card-container');
    cardContainer.innerHTML = ''; // Clear the grid first

    cardData.forEach((data) => {
        //create product card
        let card = document.createElement('div');
        card.classList.add('card-body');
        card.setAttribute('data-product-id', data.id);

        // Add content inside the product card
        let content = `<div class="card-container  py-5">
        
             <div class="row  ">
                <div class="col">
                <div class="listProduct">
        
                    <div class="card-body product-card" data-product-id="${data.id}">
                        <img class="card-img-top " id="productImg" src="${data.imgFile}" alt="Card image cap">

                            <div class=" product-details" id="details-${data.id}">
                                <h5 class="card-title mb-3 fw-bold ">${data.heading}</h5>
                                <p class="card-text text-muted mb-4">${data.body}</p>
                                <div class="d-flex justify-content-between align-items-center">
                                <span class="product-price">Price:${data.price}</span>
                            </div>
                            <button class="btn btn-custom text-white px-4 py-2 rounded-pill" data-product-id="${data.id}"btn btn-primary">View Details</button>
                    </div>
                    </div>
                </div>
                
                </div>
                </div>
                 
        </div>`;

        cardContainer.innerHTML += content;
       


            document.querySelector('.listProduct').addEventListener('click',function(){

                let productId = data.id;  // This should not be undefined
                console.log(productId);
                window.location.href = `ProductDetails1.html?id=${productId}`;

            });

       
        return card;

    })

}

// Call the function to generate products on page load
createCard(cardData);

ProductDetails.html

   <!DOCTYPE html>
<html lang="en">

<head>
    <title>Product Details</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=1.0">
    <meta charset="utf-8">

    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
        crossorigin="anonymous"></script>

    <script src="https://kit.fontawesome.com/ce111f8d46.js" crossorigin="anonymous"></script>
    <script src="//code.jquery.com/jquery.min.js"></script>

    <link rel="stylesheet" href="mystyle.css">
    <link rel="stylesheet" href="ProductDetails.css">

</head>


<body>

    <!--Navigation bar-->
    <div id="nav-placeholder">

    </div>

    <script>
        $(function () {
            $("#nav-placeholder").load("nav.html");
        });
    </script>

   

    <div class="container my-5 pt-5">


        <div class=" row mt-5">
            <div class="col-sm-8 d-flex flex-column d-inline-flex p-2 bd-highlight justify-content-around ">
                <div class="detail">
                    <figure class="ProductItem-gallery">

                        <div class="image1">
                            <img src="" alt="">
                            
                        </div>
                        
                    </figure>

                    <div class="col">
                        <div class="content">
                            <h1 class="name"></h1>
                            <p class="price"></p>
                            <p class="description"></p>
                            <button class="btn btn-primary">Add to Cart</button>

                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>


    <script>

        let products = null;
        fetch('./products.json')
            .then(response => response.json())
            .then(data => {
                products = data;
                showDetail();
            })
        //find this product
        function showDetail() {
            let detail = document.querySelector('.detail');
            let productId = new URLSearchParams(window.location.search).get('id');

            console.log("product id  "+productId);

            let thisProduct = products.filter(value => {
                return value.id == productId
            })[0];

            //if there is no product has id =productId
            //=>return to home page
            if (!thisProduct) {
                window.location.href = "/shoplist.html";
            }

            //and if has,add data this product in html
            detail.querySelector('.image1 img').src = thisProduct.imgFile;
            detail.querySelector('.name').innerText = thisProduct.heading;
            detail.querySelector('.price').innerText = '$' + thisProduct.price;
            detail.querySelector('.description').innerText = thisProduct.body;

        }
    </script>
</body>

</html>

shoplist.html

  <!DOCTYPE html>
<html lang="en">

<head>
    <title>ShopList</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=1.0">
    <meta charset="utf-8">

    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
        crossorigin="anonymous"></script>

    <script src="https://kit.fontawesome.com/ce111f8d46.js" crossorigin="anonymous"></script>
    <!-- <script src="https://code.jquery.com/jquery-1.10.2.js"></script> -->



    <link rel="stylesheet" href="shopstyle.css">
    <link rel="stylesheet" href="mystyle.css">
    <script src="//code.jquery.com/jquery.min.js"></script>
</head>


<body>

    <!--Navigation bar-->
    <div id="nav-placeholder">

    </div>

    <script>
        $(function () {
            $("#nav-placeholder").load("nav.html");
        });
    </script>


    <h1 class="heading-top-op text-center">Original Paintings</h1>


    <div class="card-container">
        <div class="listProduct"></div>

        

    </div>


    <script src="product-list.js" defer>
    </script>

    <script>

        let products = null;
        fetch('./products.json')
            .then(response => response.json())
            .then(data => {
                products = data;
                console.log(products);
                addDataToHTML();
            })

        let listProduct = document.querySelector('.listProduct');
        function addDataToHTML() {
            products.forEach(product => {
                //create new element item
                let newProduct = document.createElement('a');
                newProduct.setAttribute("id", "clicktag");
                newProduct.href = '/ProductDetails1.html?id=' + product.id;


                

                newProduct.classList.add('item');
                newProduct.innerHTML = `
                    <img src="${product.imgFile}"/>;
                    <h2>${product.heading}</h2>;
                    <p class="price">${product.price}</p>`;


                //add this element in listProduct class
                listProduct.appendChild(newProduct);

            })
            // end - of for 
        }
        // end of fuction addDataToHtML
      




    </script>

</body>

<!--footer -->
<div id="footer-placeholder">

</div>

<script>
    $(function () {
        $("#footer-placeholder").load("footer.html");
    });
</script>

</html>

Loop through a state array in React and switch each item to true using setTimeout

I have an array in state:

const [show, setShow] = useState([false, false, false, false])

These affect whether or not an image is displayed.

I’d like to iterate through them one by one, using a delay of 500ms between each iteration, and switch each to true so that the images are slowly revealed. To be clear, they should all end up as true, rather than just being temporarily switched to true.

I’ve used lots of methods so far, but can only get them to change the current index to true during that loop iteration.

Any help would be appreciated!

CryptoJS.AES.encrypt() and Java AES encryption producing different results

I’m trying to encrypt data using AES in both JavaScript (with CryptoJS) and Java/Scala, but the Java encryption cannot be decrypted by a service while the CryptoJS version works correctly.

Here’s my working CryptoJS code:

const encrypted = CryptoJS.AES.encrypt(data, secret);

And here’s my Java/Scala implementation that’s not working:

val sha256 = java.security.MessageDigest.getInstance("SHA-256")
val key = new SecretKeySpec(sha256.digest(secret.getBytes("UTF-8")), "AES")
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
val iv = new Array[Byte](16)
new java.security.SecureRandom().nextBytes(iv)
val ivSpec = new IvParameterSpec(iv)
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec)
val encrypted = cipher.doFinal(data.getBytes("UTF-8"))
val combined = iv ++ encrypted
Base64.getEncoder.encodeToString(combined)

Expected Behavior:

Both implementations should produce encrypted data that the service can decrypt

Actual Behavior:

CryptoJS encryption works and can be decrypted
Java/Scala encryption cannot be decrypted by the service

Questions

  • What are the default settings used by CryptoJS.AES.encrypt()?
  • How can I modify my Java/Scala code to match CryptoJS’s encryption format?

How to generate a locale-specific alphabet array?

For an application with a quiz functionality, I need to generate an array of indivdual letters based on a locale. For example for the locale en-GB, an array that looks like ['a', 'b', 'c', ... ], and for bg-BG, an array like ['а', 'б', 'в', 'г' ].

I understand that both strings conceptually and languages are incredibly complex and varied, and in certain languages there might not be a letter-based alphabet. So I don’t know:

  • Is there a standardized “alphabet” per locale?
  • If there is, how is it best defined? A Unicode code-point of the first “letter”?
  • Is every alphabet necessarily possible to enumerate (i.e. is it for example a series of consequtive Unicode code points)?
  • How could this all be put together in a JavaScript implementation?

I would like to have a somewhat comprehensive standards-based solution if possible.

I am writing this in TypeScript / JavaScript. Any advice appreciated.