Why is new Date() giving wrong date for other time zone users?

I have a hotel booking website ,so the problem is when the users who are residing in India and have IST time zone tries to book any hotel then the date they’re seeing is correct but when users who are outside IST time zone for example Eastern Daylight time zone they’re not able see correct date when they select it from calendar
I have set my laptop to EST time zone and when I select 7th of september 2024 from calendar and I can see props.checkin also has the same date but when it is passed to new Date(props.checkin) then the date automatically changes to 6th of september 2024 and this only happen in time zone other then IST

 useEffect(() => {
    console.log(
      "props.checkin>>>>>",
      new Date("Sat Sep 07 2024 00:00:00 GMT+0530 (India Standard Time)"),
    );
    dispatch(
      updateBookingDateRange({
        checkInDate: new Date(props.checkin),
        checkOutDate: new Date(props.checkout),
        searchedRoomCount: Number(props.num_rooms),
        searchAdultCount: Number(props.num_adults),
        searchedChildrenCount: Number(props.num_children),
        searchGuestCount: Number(props.num_guests),
      }),
    );

    if (
      totalRoomCount === 0 &&
      props.planStatus &&
      router.query.roomId &&
      router.query.planId
    ) {
      dispatch(
        addFirstRoom({
          roomInfo: props.roomDetails,
          planInfo: props.planDetails,
          roomCount: props.num_rooms,
          guestCount: Number(props.num_guests),
          adultCount: Number(props.num_adults),
          childCount: Number(props.num_children),
        }),
      );
    }
  }, [
    router.query.hotelInfo,
    router.query.checkin,
    router.query.checkout,
    router.query.num_guests,
    router.query.num_children,
    router.query.num_rooms,
  ]);

I’m expecting that when users that are in different time zone chooses some date then they too should see correct date instead of wrong date.

Python Template overrides JavaScript Function [closed]

I have a button that submits a form to a flask server and runs a JS function. When the button is pressed the JS function runs , then it is overridden by the flask render_template function.

HTML:

<div id="index">
    <form action="/analyse" method="post">
        <!-- Form and button --!>
        <input id="fileupload" type="file" accept=".xlsx, .xls" name="fileupload" />
        <input type="submit" class="button" value="Send to Server" onclick="hide()"/>
    </form>
</div>

<div id="analyse" class="hidden">
    <!-- The hidden items that will be visible after the submittion of the form --!>
</div>

JS Button Function:

// Function hides the form and unhides the 'analyse' div
// Another function reverses hide() function
function hide() {
    var index = document.getElementById('index');
    var analyse = document.getElementById('analyse');
    index.classList.add('hidden');
    analyse.classList.remove('hidden');
}

Server-side Python:

@app.route('/', methods=['GET','POST'])
def index():
    return render_template('index.html')

@app.route('/analyse', methods=['GET','POST'])
def analyse():
    # Validation and functions, etc.
    return render_template('index.html')

Form validation JavaScript unresponsive to “submit” eventListener

I’ve been assigned a task to make a sign-up page for a hypothetical training business.

I’m currently creating the form validation for the first name input, which checks whether the field is empty, equal to the placeholder, has any numbers or special characters. However, my code is not responding when I click my button element (not input type=submit).

The expected result was the font colour to change to pink and the innerText to display “Please enter a valid first name”.

I’ve attempted calling both the form form.addEventListener("submit", newCustomer); and the button tn.addEventListener("submit", newCustomer); in my javascript, but nothing happens.

div class="form-container">
          <form action="" id="form">
            <div class="form-top">
              <div class="title">
                <label for="firstname" class="firstname">First Name:</label>
                <label for="lastname" class="lastname">Last Name:</label>
                <label for="email address" class="email-address">Email:</label>
                <label for="card details " class="card-details"> Card:</label>
              </div>
              <div class="textbox">
                <input type="text" placeholder="Enter Your Firstname" id="f-name">
                <input type="text" placeholder="Enter Your Last Name" id="l-name">
                <input type="text" placeholder="Enter Your Email" id="email">
                <input type="text" placeholder="Enter a Proxy Credit Card Number" id="card">
              </div>
            </div>
            <div class="button-container"><button id="btn" type="submit">Submit</button></div>
          </form>
          
            <script>
                var fname = document.getElementById("f-name");
                var lname = document.getElementById("l-name");
                var email = document.getElementById("email");
                var card = document.getElementById("card");
                const btn = document.getElementById("btn");
                const form = document.getElementById("form");

                var Customers = [];

                function newCustomer(event, firstname, lastname, emailAddress, cardNum) {
                event.preventDefault();
                firstname = fname;
                lastname = lname;
                emailAddress = email;
                cardNum = card;

                if (firstname === "" || firstname.placeholder === "Enter Your Firstname") {
                    firstname.innerText = "Please enter a valid first name";
                    firstname.style.color = "rgb(231,0,100)";
                } else {
                    var specialChars = /[!@#$%^&*(),.?":{}|<>]/g;
                    for (let i = 0; i < firstname.value.length - 1; i++) {
                    if (!isNaN(firstname[i])) {
                        firstname.placeholder.style.color = "rgb(231,0,100)";
                        firstname.placeholder.innerText = "Please enter a valid first name";
                    } else if (specialChars.test(firstname[i]) == true) {
                        firstname.style.color = "rgb(231,0,100)";
                        firstname.innerText = "Please enter a valid first name";
                    } else {
                        firstname.style.color = "rgb(137,200,46)";
                        form.reset();
                    }
                    }
                }
                }
                btn.addEventListener("submit", newCustomer);

            </script>
        </div>

Javascript – does memory allocated if function returns early?

For efficient memory usage of a highly used class instance (multiple calls to init), I would like to know if memory for anything inside init function is allocated if it returns early.

Sandbox

class X {
    private static smth: Smth

    public static init(): Smth {
        // if this is evalueated to true and returned
        if (this.smth) {
            return this.smth;
        }

        // does memory allocated here (imagine there will be a big object)?
        const smth: Smth = {
            x: 1
        }

        this.smth = smth

        return this.smth
    }

    // if for previous question answer is yes, can we avoid memory allocation for `const smth` like this?
    public static getInstance(): Smth {
        if (!this.smth) {
            throw new Error("Not initialized");
        }

        return this.init();
    }
}

type Smth = {
    x: number
}

How to get a list of chat names that a Telegram bot is a member of using Telegram Bot API?

I am developing a Telegram bot using Node.js and axios to interact with the Telegram Bot API. I need to get a list of all chat names that the bot is a member of. I am able to fetch updates and chat information using the getUpdates and getChat methods. Here is my current code:

const axios = require('axios');

const botToken = process.env.BOT_TOKEN;
const apiUrl = `https://api.telegram.org/bot${'botToken'}`;

const getUpdates = async () => {
  try {
    const response = await axios.get(`${apiUrl}/getUpdates`);
    return response.data;
  } catch (err) {
    console.error(err);
    throw err
  }
};
const getChat = async (chatId) => {
  try {
    const response = await axios.get(`${apiUrl}/getChat`, {
        params: {
            chat_id: chatId,
        },
    });
    return response.data;
  } catch (err) {
    console.error(err);
    throw err
  }
}

module.exports = {getUpdates, getChat}

How can I get a list of all chats that the bot is a member of using the getUpdates method?
How can I extract the names of these chats?
At the moment, I am receiving updates but am not entirely sure how to properly extract chat information and its name from the data received. What is the best way to do this? Are there any potential issues or limitations when obtaining this information?

I would appreciate any help!

Audio offset get wrong after some time when streaming audios

I use microsoft-cognitiveservices-speech-sdk (1.38.0) in order to do real time speech to text.
It seems like the offset is right when I send a full audio but it is wrong when I send it cut in a lot of audio chunks.

The more there is audio chunks the more inaccurate the offset is :

  • No chunks : 1 726 300 000
  • 369 chunks of 0.5 seconds : 1 729 600 000
  • 923 chunks of 0.2 seconds : 1 744 600 000
  • 1443 chunks of 0.1 seconds : 1 757 900 000

To reproduce here is some piece of code :

    const speechConfig = SpeechConfig.fromSubscription(<KEY>, <REGION);

    const pushStream = AudioInputStream.createPushStream();
    const audioConfig = AudioConfig.fromStreamInput(pushStream);
    const speechRecognizer = new SpeechRecognizer(speechConfig, audioConfig);

    speechRecognizer.recognized = async (recognizer, event) => {console.log(event)}
    speechRecognizer.canceled = async (recognizer, event) => {console.log(event)}
    speechRecognizer.startContinuousRecognitionAsync();

    for (let i = 1; i <= 1443; i++) {
      const formattedNumber = i.toString().padStart(4, '0');
      const buffer = fs.readFileSync(`/var/tmp/chunks/output_${formattedNumber}.wav`);
      pushStream.write(buffer);
    }

To create the audio chunks :

ffmpeg -i <INPUT_FILE> -f segment -segment_time 0.1 -c copy output_%04d.wav

Here is the audio link : https://drive.google.com/file/d/1H_RJuqMiBaVkpo9XHrgp1bpuFdgQl64O/view?usp=sharing

Thanks for your help

How to Differentiate Between Navigation Route Change and Initial Load in Next.js 14?

I’m currently working with Next.js 14 and its App Router paradigm to manage navigation within my application. I have implemented a background color transition on certain pages that is triggered when navigating between routes. However, I want this transition to occur only on route changes, not when the page is accessed directly by typing the URL into the browser.

Problem: My layout includes a CSS transition effect for the background color that I only want to trigger when users navigate to specific pages from other parts of the app (not on initial page loads).

Question: Is there a way in Next.js 14 to detect if a page load is the result of a navigation route change versus an initial direct access? I need this to conditionally apply the background color transition.

Any guidance or suggestions on how to approach this would be greatly appreciated!

I attempted to adjust my layout.tsx to make it a client component, thinking it might help differentiate between navigation changes and direct loads. However, this approach did not resolve the issue as it didn’t logically fit the requirements.

Dynamic Rules Framework in Javascript/Typescript

Our team is building a insurance suite digital web application for customer to purchase policies. We have state and policy coverage related requirements where

  1. we need to dynamically ask customer questions based on the state or policy coverage
  2. we need to validate customer input based on state or policy coverage rules
  3. we need to dynamically transform/update/set the the data object values based on customer input during the workflow

Currently team is hardcoding all this logic in the front end NextJS application to handle the above scenarios and are concerned on the maintenance and scalability with more app deployments in the new state.

We are looking to into possibility of building json driven rules per state or coverage which shall retrieved by web app during the workflow and then with help of a framework which shall read json config and the customer input data to address the above requirements.

Any suggestions are highly appreciated

texture bug when use ShaderMaterial in three.js

import React, { useRef, useEffect } from 'react';
import { Canvas, useFrame, useThree } from '@react-three/fiber';
import { OrbitControls } from '@react-three/drei';
import { useLoader } from '@react-three/fiber';
import * as THREE from 'three';
import getStarfield from '../../public/src/getStarfield.js';
import { getFresnelMat } from '../../public/src/getFresnelMat.js';

function Earth() {
  const earthGroupRef = useRef();
  const { scene } = useThree();

  useEffect(() => {
    const earthGroup = earthGroupRef.current;
    earthGroup.rotation.z = -23.4 * Math.PI / 180;
    const stars = getStarfield({ numStars: 2000 });
    scene.add(stars);

    return () => {
      scene.remove(stars);
    };
  }, [scene]);

  useFrame(() => {
    if (earthGroupRef.current) {
      earthGroupRef.current.children.forEach((mesh, index) => {
        if (index == 2) {
          mesh.rotation.y += 0.0013 ;
        }else{
          mesh.rotation.y += 0.001 ;
        }
      });
    }
  });

  const map = useLoader(THREE.TextureLoader, '../public/textures/2k_earth_daymap.jpg');
  const specularMap = useLoader(THREE.TextureLoader, '../public/textures/02_earthspec1k.jpg');
  const bumpMap = useLoader(THREE.TextureLoader, '../public/textures/01_earthbump1k.jpg');
  const lightsMap = useLoader(THREE.TextureLoader, '../public/textures/2k_earth_nightmap.jpg');
  const cloudsMap = useLoader(THREE.TextureLoader, '../public/textures/04_earthcloudmap.jpg');
  const cloudsAlphaMap = useLoader(THREE.TextureLoader, '../public/textures/05_earthcloudmaptrans.jpg');
  const earthMaterial = new THREE.MeshPhongMaterial({
    map: map,
    specularMap: specularMap,
    bumpMap: bumpMap,
    bumpScale: 0.04,
  });

  const lightsMaterial = new THREE.ShaderMaterial({
    uniforms: {
      lightsMap: { value: lightsMap },
      lightDirection: { value: new THREE.Vector3(-2, 0.5, 1.5) }, // Adjust based on your light source
    },
    vertexShader: `
      varying vec3 vWorldNormal;
      varying vec2 vUv;
  
      void main() {
        vUv = uv;

        vWorldNormal = normalize(mat3(modelMatrix) * normal);
  
        gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1);
      }
    `,
    fragmentShader: `
      uniform sampler2D lightsMap;
      uniform vec3 lightDirection;

      varying vec3 vWorldNormal;
      varying vec2 vUv;
  
      void main() {

        float lightFactor = clamp(dot(normalize(vWorldNormal), normalize(lightDirection)), 0.0, 1.0);

        float transition = smoothstep(-0.1, 0.1, lightFactor); 

        vec4 nightLights = texture2D(lightsMap, vUv);
  
        gl_FragColor = mix(nightLights, vec4(0.0, 0.0, 0.0, 1.0), transition);
      }
    `,
    blending: THREE.AdditiveBlending,
    transparent: true, 
  });

  const cloudsMaterial = new THREE.MeshStandardMaterial({
    map: cloudsMap,
    transparent: true,
    opacity: 0.8,
    blending: THREE.AdditiveBlending,
    alphaMap: cloudsAlphaMap,
  });

  const fresnelMaterial = getFresnelMat();

  const geometry = new THREE.IcosahedronGeometry(1, 64);

  return (
    <group ref={earthGroupRef}>
      <mesh geometry={geometry} material={earthMaterial} />
      <mesh geometry={geometry} material={lightsMaterial} />
      <mesh geometry={geometry} material={cloudsMaterial} scale={1.003} />
      <mesh geometry={geometry} material={fresnelMaterial} scale={1.01} />
    </group>
  );
}

export const Model = () => {
  return (
    <Canvas camera={{ position: [0, 0, 5], fov: 75 }} gl={{ clearColor: 0x00000 }} >
      <OrbitControls minDistance={1.8} maxDistance={10}/>
      <ambientLight intensity={0.01} />
      <directionalLight position={[-2, 0.5, 1.5]}intensity={1}/>
      <Earth />
    </Canvas>
  );
};

I’ve been trying to make the light material render the world’s surface at night but it’s not working very well. There are still dark spots appearing from time to time. I think it’s a ShaderMaterial or fragmentShader material. However, I’ve been searching for a solution for 2 hours and nothing works.

HELP

How to get it with javascript / jquery

I am a beginner and try to learn self.

I try to learn the following

Problem 1

Try to change the background color from the input color and the code is as follows

 function changebg(){

      var bgColor = $("#red").val();
      
      document.querySelectorAll(".a").forEach((c1) => {
    c1.style.backgroundColor = bgColor;
  });
     }
    changebg();
     $("input#red").change(changebg);
});
<input id="red" type="color" >


<p class="a">If you click on me, I will disappear.</p>
<p class="a">Click me away!</p>
<p class="a">Click me too!</p>

Also need to call changebg(); in another function as well.

The below code works with 3 input values. But don’t know the reason for the above or how to correct it as well.

 function rgb() {
  const bgColor = `rgb(${document.getElementById("red").value},${
    document.getElementById("green").value
  },${document.getElementById("blue").value})`;
    document.querySelectorAll(".odd").forEach((odd) => {
    odd.style.backgroundColor = bgColor;
    
  });
}

rgb();

Don’t know why the code not functioning.

Problem 2

Try to change the the active states of two divisions corresponding elements simultaneously. Also the first button of each groups must toggle classes as well. It functions some what but when the button[0] state is always active once clicked.

But there is no correspondence response from the other division elements.

 document.querySelector('.toggle-container').addEventListener('click', ({ target }) => {
  if (!target.matches('.toggle-button')) {
    return;
  }
  const toggleContainer = target.parentElement;
  const btns = toggleContainer.children;
  if (target === btns[0]) {
    
    btns[1,2,3].classList.remove('active');
    btns[0].classList.add('active').toggle('active1 active2');
     
  }  if (target === btns[1]) {
    btns[-1,0,2,3].classList.remove('active active1');
    btns[1].classList.add('active');
  }
   if (target === btns[2]) {
    btns[-1,0,1,3].classList.remove('active');
    btns[2].classList.add('active');
  }
   if (target === btns[3]) {
    btns[-1,0,1,2].classList.remove('active');
    btns[3].classList.add('active');
  }
 
});

});
.active {
  background-color: yellow;
}
.active1 {
  background-color: red;
}
.active2 {
  background-color: blue;
}
<div class="toggle-container">
    <button class="toggle-button">List-0</button>
    <button class="toggle-button">List-1</button>
     <button class="toggle-button">List-2</button>
      <button class="toggle-button">List-3</button>
  </div>
  
  
    <div class="toggle-container">
    <button class="toggle-button">List-0</button>
    <button class="toggle-button">List-1</button>
     <button class="toggle-button">List-2</button>
      <button class="toggle-button">List-3</button>
  </div>

All help at all levels for either or both problems welcome.

(if provide with a simple explanation may more useful).

How to manipulate/copy ElementRef in angular without manipulating the DOM?

I have a formatted html table of nearly 200rows which I have to export to PDF. Currently I’m using jsPDF library.

makePdf() {
    var elWidth = this.el.nativeElement.getBoundingClientRect().width
    var elHeight = this.el.nativeElement.getBoundingClientRect().height
    this.loadingSubject.next(true)
    this.zone.run(() => {
    let pdf = new jsPDF({
      orientation: 'l',
      unit: 'px',
      format: [elWidth, elHeight],
      compress:true
    });
    pdf.html(element.nativeElement, {
      callback: (pdf) => {
        pdf.save('sample.pdf');
      }
    })
    })
  }

It is now saving as pdf segregating the height by default causing the rows cut in line to the next page as shown in below image.
enter image description here

I want to separate rows like 13 rows and append table, thead tags to each 13 rows making them separate tables in each page.

Any changes to el.nativeElement is affecting the DOM. Is there any alternative where I can get html and make changes to the html without manipulating the DOM in angular??

String middle character on JavaScript [closed]

Hi guys I am trying to solve this problem on JavaScript and I am stuck.

Instructions
This function takes a string of at least one character, and it should return the middle character(s) from that string.

If the string is of odd length, the function should return a single character. If the string is of even length, it should return the middle two characters concatenated together.

This is what I tried:

function returnMiddleCharacter(string) {
      
    let letterCount = string.length;
    let midChar = Math.round(letterCount/2)
    
    if (letterCount === 1) {
        return string;
    }
    if(letterCount % 2 !== 0){
        return string[midChar]
    }else{
        string[midChar -1] + string[midChar]

    }

}

HTML for UI design

I want to be able to develop my user interface designs from figma. Do I need to learn HTML or just CSS and Javascript? And what are the best resources for that?

So far in dev mode, I’ve only seen the CSS codes so I was wondering if it’s the only thing I need to learn.

Div element going out of parent div in Browser

I am making a website for currency exchange (as a college assignment), and I am facing this absurd issue here.

This is my entire code:

@import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}

#bg {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background-color: aquamarine;
}

.wrapper {
  background-color: aliceblue;
  overflow: hidden;
  width: 370px;
}
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
<section id="bg">
  <div class="wrapper">
    <header>Currency Converter</header>
    <form action="#">
      <div class="amount">
        <p>Enter the amount:</p>
        <input type="text" value="1">
      </div>
      <div class="droplist">
        <div class="from">
          <p>From:</p>
          <div class="select-box">
            <img src="https://flagsapi.com/US/flat/64.png" alt="flag">
            <select title="Country">
              <option value="USD">USD</option>
              <option value="INR">INR</option>
              <option value="PKR">PKR</option>
              <option value="JPY">JPY</option>
            </select>
          </div>
        </div>

        <div class="icon"><i class="fas fa-exchange-alt"></i></div>

        <div class="to"></div>
        <p>To:</p>
        <div class="select-box">
          <img src="https://flagsapi.com/IN/flat/64.png" alt="flag">
          <select title="Country">
            <option value="USD">USD</option>
            <option value="INR">INR</option>
            <option value="PKR">PKR</option>
            <option value="JPY">JPY</option>
          </select>
        </div>
      </div>
  </div>
  </form>
  <div class="exchange-rate">1 USD = 83.343 INR</div>
  <button>Get Exchange Rate</button>
  </div>
</section>

The website is like this: Website Image

And code of the website using Inspect Element:Inspect Code

The last Div and Button are outside the Wrapper Div Element in Edge. I tried adding Section etc to debug and found that even without CSS the problem persists.

Till now, I have tried the following:

  • Remove CSS completely
  • Remove , and only keeping div elements.
  • Open the webpage without Live Server (VS Code).

Everything Works if I put the last two components in between other divs inside the wrapper div, but that’s not what I want.

Can anyone tell me why this absurd issue is happening? Am I making some rudimentary mistake?