Google One Tap Login not Working in chrome incognito

I am working on adding one tap login to my project using google JS api, code for the same

    google.accounts.id.initialize({
        client_id: CLIENT_ID,
        cancel_on_tap_outside: false,
        callback: LoginSuccess,
        prompt_parent_id: "root",
        itp_support: true,      
    });


This is working fine firefox, safari in both normal and incognito mode, but in chrome its working fine in normal but not working in incognito mode (Allowed all the cookies in incognito), it returning response as opt_out_or_no_session.

i tried with setting the g_state cookie, but it doesn’t not work

google.accounts.id.prompt(function(oneTapPromptResponse) {
    if (oneTapPromptResponse.isNotDisplayed()) {
        document.cookie =  "g_state=;path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT";
        console.info("Google Login Not Displayed");
    } else if (oneTapPromptResponse.isSkippedMoment()) {
        console.info("Google Login skiiped");
    } else if (oneTapPromptResponse.isDismissedMoment()) {
        console.info("Google Login dismissed");
    } else if (oneTapPromptResponse.isDisplayed()) {
        console.info("Google Login displayed")
    }
});

Attached the image for Firefox private browsing mode response

Firefox private browsing mode response

Can anyone help me to resolve this.

Issues getting preloader animation to show up when render.com server is spinning up (free tier web service)

I am using render.com to deploy my dynamic websites and have opted to use their free tier. Render will spin down the free web service after 15 minutes of inactivity and spin the service back up whenever it next receives a request to process. However, spinning up a service from idle takes quite a bit of time, causing a noticeable delay for incoming requests until the service is back up and running. The result is that the browser page load will hang momentarily.

To make the experience more user friendly I decided to create a preloader animation that shows up while the server is spinning up from idle (using fetch). However, my current code only works after the server has been spun up. I am clearly doing something wrong but am completely stumped.

Here is my current code that checks if the service is up and handles the preload animation using jQuery.

// Function to check if the service is up using async/await
async function isServiceUp() {
    try {
      const response = await fetch("https://cookyourkitchen.onrender.com"); 
      console.log(response);

    } catch (error) {
      console.error('Error checking service status:', error);
      return false; // Service is down or unreachable
    }
  }

$(document).ready( () => {
    if(isServiceUp){
        $("#loader").fadeOut(1000);
        $("#content").fadeIn(1000);
    } else {
        $("#loader").show();
    }
    
});

Here is the html (ejs) that is relevant to my problem.

<body>
    <div id="loader" class="loader"></div>

    <div id="content" class="container">
        <div class="px-4 py-5 my-4 text-center">
            <h1 class="display-5 fw-bold text-body-emphasis">Cook Your Kitchen</h1>
            <div class="col-lg-6 mx-auto">
                <p class="lead mb-4">Have some random ingrediants in your kitchen? <br>
                    Those veggies about to go bad?? <br>
                    Enter the ingrediants you want to use and get recipe suggestions!
                </p>
                <form action="/search" method="post">
                    <div class="d-grid gap-2 d-sm-flex justify-content-sm-center">
                        <input type="text" id="search" name="ingrediants" class="form-control"
                            placeholder="Chicken, beans, tomato,..." aria-label="Recipient's username"
                            aria-describedby="button-addon2">
                        <button class="btn btn-outline-secondary" type="submit" value="Submit" id="button-addon2">Get a recipe</button>
                    </div>
                </form>

            </div>
        </div>
    </div>
 <script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" 
       crossorigin="anonymous"></script>
       <script src="preloadwebpage.js"></script>
       <script src="loadrecipes.js"></script>
</body>

Issue with Rendering Image Swatch Colors on Product Page

I am currently working on a project where I need to implement image swatches on a product page. However, I seem to be facing an issue with the code

I have used the following code for the image swatches, but it does not seem to be working as expected

class ColorName extends HTMLElement {
constructor() {
super()
this.color = this.parentNode.innerText
this.optionSelects = this.parentNode.parentNode
this.optionSelects.addEventListener('change', this.colorRender.bind(this))
THIS.colorRender()
  console.log(this)
  console.log(this.color)
  console.log(this.optionSelects)
}

colorRender() {
this.selectedColor = document.querySelector(`input[name="Color"]:checked`).value
this.innerText = this.selectedColor.charAt(0).toUpperCase() + this.selectedColor.slice(1)
}
}

customElements.define('color-name', ColorName)

class SizeName extends HTMLElement {
constructor() {
super()
this.size = this.parentNode.innerText
this.optionSelects = this.parentNode.parentNode
this.optionSelects.addEventListener('change', this.sizeRender.bind(this))
THIS.sizeRender()
  console.log(this)
  console.log(this.size)
  console.log(this.optionSelects)
}

sizeRender() {
this.selectedSize = document.querySelector(`input[name="Size"]:checked`).value
this.innerText = this.selectedSize.toUpperCase()
this.innerText = this.selectedSize.charAt(0).toUpperCase() + this.selectedColor.slice(1)
}
}

I am unsure of what I am doing wrong here. I have tried reaching out to the original developer for assistance, but have not received a response yet.

Set Apache echart series dynamically

I have an array of points and want to set the array as the source of series like text. How can I set series via javascript code dynamically?

My code is:

series: this.graph?.data.map(data => {
        return { 
          name: data.label,
          showSymbol: data.showIcon,
          type: 'line',
          lineStyle: {
            width: data.lineTickness ? data.lineTickness : data.isThreshold ? 6 : 1,
            cap: 'round',
            color: data.lineColor ? data.lineColor : null,
            type: data.lineType ? data.lineType.toLowerCase() : null,
          },
          itemStyle: {
            normal: {
                color: data.lineColor ? data.lineColor : null,
            }
          },
          step: data.step,
          data: data.points.map(point => {return point.value?.numeric?.toFixed(4)}),
          areaStyle: data.area ? {} : null,
          yAxisIndex: data.associatedY2Axis ? 1 : 0,
          zlevel: data.isThreshold ? 0 : 1
        }
      })

But doesn’t work properl and will miss some data on the exported chart.

Prevent sorting of object while using map function in javascript [duplicate]

I am trying to put some values in an object by using map function on an array. But its automatically sorting it in ascending order which I don’t want. How would I keep my object key values in same sequence as my array. Or is there any alternate approach which I can use in place of using map function. Below is what I have tried and what I am expecting with an example using fiddle.

let data = {};
const carsArray = [
{id:1,name:"A-Ferrari"},
{id:2,name:"A-BMW"},
{id:4,name:"A-Audi"},
{id:5,name:"A-Mango"},
{id:3,name:"B-Fiat"},
{id:6,name:"B-Suzuki"}
]

const arr = carsArray.map(x=> {data[x.id] = x.name})

// Output

{1: 'A-Ferrari', 2: 'A-BMW', 3: 'B-Fiat', 4: 'A-Audi', 5: 'A-Mango', 6: 'B-Suzuki'}

// Expected Output

{1: 'A-Ferrari', 2: 'A-BMW',4: 'A-Audi', 5: 'A-Mango', 3: 'B-Fiat', , 6: 'B-Suzuki'}

fiddle

Webpack bundle to call functions from another js file

New to webpack here, managed to setup and so far it’s all good (I’m able to build my bundle file – npm run build). I have read through some documentations like code splitting, but not sure if that’s what I need now.

The issue I’m having currently is that, for example, I have 2 js files (I have more than that, this is just an example), and each js files is sort of dependent on each other (global variables are shared, function called between files).

Below is the sample scenario:

a.js, b.js

b.js has a function called function b() {};

a.js calls function b() onload, which was working fine previously when I manually imported the scripts via script tags, but now after bundling, it will say

b is not defined

I have tried importing, but it still doesn’t work

import “./b.js” at the top of a.js file

I am migrating to webpack because, despite using cloudfronts, having numerous scripts loading is still costing me, so my end goal is to bundle all of my scripts into 1 file to use for production, but still maintain multiple files when in development (change each individual js file, then always build and commit the built file together). If there’s a better option to achieve what I need above, please do enlighten me as well.

Below is my webpack.config.js file

const path = require('path');

module.exports = {
    mode: 'development',
    entry: ['../assets/js/a.js', '../assets/js/b.js'],
    output: {
        filename: 'compiled_script.js',
        path: path.resolve(__dirname, '../assets/js'),
    },
};

Thanks

issue with Google Analystics 4 in React js project

issue with Google Analystics 4 in React js project
there is public routes events on login page like about us page contact us email id etc these and protected routes like dashbored user details , some kind of buttons drop downs radio button these evetns should be tracked in googleanaysticId so.
when i clicked on the events on real time its working correct. but when i see after 48 hours these events in explore section in GA websites these evetns getting mixup in explore section
protected routes evtents showing in sessionid which unauthentic user

Hi all
I have implemented Google analytics (GA-4) in my project. i am facing an issue in that.i want to track separate events for before login and after login.
what is happening now is the public route events are getting tracked in session Id but as user get logged in GoogleanalyticsuserId get generated and we set the reactGA GoogleanalyticsuserId all protected routes events are getting tracked but as user logout if something clicks on publics routes events. these events are getting tracked in session I’d GoogleanalyticsuserId.

I want public routes clicked events to be tracked in sessionId and protected routes clicked events to be tracked in GoogleanalyticsuserId.
but what the issue I am facing sessionid and GoogleanalyticsuserId events are getting mixup

clicked events are getting tracked
for what I have to try resolve the issue on logout I am clearing session storage as well as I am setting reactGA.set(‘ ‘)

initFoodModel is not a function Cannot read properties of undefined (reading ‘findAll’)


wishList.js

const { initFoodModel } = require("../../model/FoodModel");
const { initWishlistModel } = require("../../model/wishListModel");
const initWishlistModel = async () => {
try {
const sequelize = await getConnection();
const Food = await initFoodModel()
const User = await initUserModel()
const Wishlist = sequelize.define("Wishlist", wishlistModel, {
freezeTableName: true,
});

        Wishlist.belongsTo(Food, { foreignKey: 'Food_id', targetKey: 'Food_id' });
        Wishlist.belongsTo(User, { foreignKey: 'user_id' });
        await Wishlist.sync({ alter: true });
        return Wishlist;
    } catch (err) {
        console.log(err.message);
    }

};

module.exports = { initWishlistModel };

listFood.js

const  {initWishlistModel}  = require("../../model/wishListModel");
const { initFoodModel } = require("../../model/FoodModel");
const getFood = async (req, res) => {
try {
const { Food_id } = req.params
const user_id = req.token.user.id;
console.log(req.token.user.id);
const schema = await initFoodModel();

        const wishlist = await initWishlistModel();
    
        let isWishlisted = await wishlist.findAll({ where: { Food_id: Food_id, user_id: user_id } })
        console.log(isWishlisted);
    
        if (isWishlisted) {
            return send(res, RESPONSE.SUCCESS, "already wishlisted")
        }
        return send(res, RESPONSE.ERROR })
    
    
    
    // let check = await schema.findOne({ where: { Food_id: Food_id, stat: true }, });
    // if (check.length === 0) {

// return send(res, RESPONSE.ITM_NOT_FOUND);
 // }
 // return send(res, RESPONSE.SUCCESS, { check })

} catch (err) {
console.log(err.message);
return send(res, RESPONSE.ERROR, err.stack)
}
};

i want to check whether the given food_id is there in wishlist or not

i have already checked all the files, the initFoodModel is properly defined

this error occurs only when i try to use initFoodModel in wishList, if i use initfoodModel directly it works fine. [check commented lines]

Swagger UI doesn’t show Choose a File button

So i am trying to create a nodejs application with an endpoint that uploads file , but seems anything I research on, and using chatGPT , it won’t show any CHOOSE A FILE BUTTON but rather just a input textbox.

Code sample below that i have tried, but it shows no button in swagger.
http://localhost:3000/api-docs/

const express = require('express');
const multer = require('multer');
const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');

const app = express();
const port = process.env.PORT || 3000;

// Set up Multer for handling file uploads
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

// Swagger configuration
const swaggerOptions = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'File Upload API',
      version: '1.0.0',
    },
  },
  apis: ['./server.js'], // Specify the file where your routes are defined
};

const swaggerSpec = swaggerJsdoc(swaggerOptions);

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

/**
 * @swagger
 * /upload:
 *   post:
 *     summary: Upload a file
 *     consumes:
 *       - multipart/form-data
 *     parameters:
 *       - in: formData
 *         name: file
 *         type: file
 *         required: true
 *         description: The file to upload
 *     responses:
 *       200:
 *         description: File uploaded successfully
 */
app.post('/upload', upload.single('file'), (req, res) => {
  const file = req.file;
  if (!file) {
    return res.status(400).json({ message: 'No file uploaded' });
  }

  // Process the file (you can save it, manipulate it, etc.)
  // For now, we'll just return some information about the uploaded file
  res.json({
    message: 'File uploaded successfully',
    originalname: file.originalname,
    mimetype: file.mimetype,
    size: file.size,
  });
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

p5.js sketch crashes after making window larger

This is my code:

// A Perlin Noise Flow Feild
import 'react'
import Sketch from 'react-p5'
import "../../App.css"

const Flow = () => {
    let w, h, nums;
    let density = 0.005
    let zOff = 0;
    let scl = 0.001;
    let speed = 12;
    let particles = []

    const setup = (p5, canvasParentRef) => {
        // Sets initial conditions
        w = p5.windowWidth
        h = p5.windowHeight
        nums = Math.ceil((w + h) / 1.5)
        p5.frameRate(30)
        p5.createCanvas(w, h, p5.WEBGL).parent(canvasParentRef)

        // Creates particle vectors
        for (let i = 0; i < nums; i++) {
            particles.push(p5.createVector(p5.random(w), p5.random(h)))
        }
    }

    const draw = (p5) => {
        // Styling
        p5.background(getComputedStyle(document.documentElement).getPropertyValue('--main-bg-color'));
        p5.stroke(getComputedStyle(document.documentElement).getPropertyValue('--main-text-color'));
        p5.translate(-w / 2, -h / 2)
        p5.strokeWeight(3)


        // Brains of the flow feild, takes the positions and modifies the particles positions given by noise.
        for (let i = 0; i < nums; i++) {
            let p = particles[i]
            p5.point(p.x, p.y)
            let n = p5.noise(p.x * scl, p.y * scl, zOff * 3);
            let angle = p5.TWO_PI * n
            p.x += Math.cos(angle) * speed
            p.y += Math.sin(angle) * speed
            if (!onScreen(p)) {
                p.x = p5.random(w)
                p.y = p5.random(h)
            }
        }

        zOff += 0.002
    }

    const onScreen = (v) => {
        return v.x >= 0 && v.x <= w && v.y >= 0 && v.y < h
    }

    const windowResized = (p5) => {
        w = p5.windowWidth;
        h = p5.windowHeight;
        nums = Math.ceil((w + h) / 1.5)
        p5.resizeCanvas(w, h);
        // Creates particle vectors
        for (let i = 0; i < nums; i++) {
            particles.push(p5.createVector(p5.random(w), p5.random(h)))
        }
    };

    return (
        <Sketch setup={setup} draw={draw} windowResized={windowResized} />
    )
}

export default Flow

I start with an initial size for my browser window, say 1000 x 1000. Whenever I increase the size of the window (by either dragging or fullscreening), the sketch crashes. Why is that? If I shrink the window, then everything continues to work (fullscreen or drag to bigger window). In essence, given an original sized window, I cannot drag the window to be larger

Hi i have a trouble, please help to Failed to retrieve data [closed]

cannot show data

Please help me to fix the trouble
please replay my message
thank you

enter image description here

how i can show data insert use name, i use railway to deploy my project

i am add database, front end, back end, i use express.js to back end

The heart of the issue lies in how data is retrieved and displayed in your application. You’ve created a user interface that presumably collects a name input from the user. When a user submits this input, your front-end code sends a request to your Express.js server, which, in turn, is expected to interact with your Railway-hosted database to retrieve the relevant data.

To resolve this issue, you’ll need to ensure that your Express.js server is correctly configured to handle incoming requests, extract the name input, interact with your Railway database, and return the fetched data to the front end. This process typically involves creating API routes in Express.js that handle GET requests with parameters, querying the database using these parameters (in this case, the name), and returning the results as JSON to the front end.

Additionally, you should check for any errors or issues at each step of this process, including proper error handling for database queries, response status codes, and data serialization.

By systematically reviewing your front-end and back-end code, confirming that your API routes are correctly structured, and ensuring that your database schema aligns with your application’s requirements, you can pinpoint and resolve the issue that prevents your data from being displayed as expected.

Disallow Set and Map to have unknown generics in Typescript?

I noticed I forgot to add a generic for a Set in code I wrote a long time ago. It’s typed as Set<unknown>. Surprisingly, this allows me to use all the Set methods without errors. With arrays, if I type it as unknown[], it’ll throw errors. E.g.:

const set = new Set();
set.has(1);

const map = new Map();
map.has(1);

const arr = []; // Variable 'arr' implicitly has type 'any[]' in some locations where its type cannot be determined.
arr.includes(1); // Variable 'arr' implicitly has an 'any[]' type.

How can I make Set and Map also throw errors if their types are unknown?

Tsc won’t let me use “in” keywork due to type error

I have some Javascript like:

const array32 = new Float32Array(this.analyser.fftSize);
let counts = {};
for(let i in detectors){
    let detector = detectors[i];
    let guess = detector(array32);
    if(!(guess in counts)){
        counts[guess] = 0;
    }
    counts[guess] += 1;
}

And when I try to build it with tsc --build tsconfig.json, it gives me the error:

error TS2360: The left-hand side of an 'in' expression must be of type 'any', 'string', 'number', or 'symbol'.

This had been building fine, and then I upgraded either tsc or some dependency, and now it gives me this. How do I fix this? Since my source isn’t Typescript, I can’t simply define guess as a number type.