Not able to keep trailing zero’s in decimal after conversion to float in Angular

I am trying to convert string to float in angular, but when I use parseFloat it is removing zero’s from decimal. How can I keep these zero’s with the values. Below example will help you to understand more

ex: My value is b=”12.00″ and I am trying to convert it to float using below syntax.

   abc = parseFloat(b.toFixed(2))

Current Output : 12

Expected Output : 12.00

How to make a vite react.ts project to run on localhost:3000 [duplicate]

Previously i asked question here on stack overflow about how to run a reactJS(Javascript) project on localhost:3000 and i got a perfect working answer like this image of vite.config.js file.

Now i want to run a reactTS(Typescript) project on localhost:3000 but now the case is the project is running on localhost:3000 but im getting a error in VS code like error image.

I want to know why im getting this error in vite reactTS project which is not in the case of vite reactJS project.

Production build fail after Angular upgrade document.documentElement.setAttribute is not a function

I have upgraded my application to Angular 16 and upgrade went well and application is working as expected

But when I run the command for prod build

ng build --configuration=production

I got this error

Index html generation failed.
document.documentElement.setAttribute is not a function

I am not sure how to fix this as I don’t have documentElement.setAttribute in my code

Setting optimization and buildOptimizer to false in angular.json does work but I know this is not right way to fix

any help or suggestion would be appreciated

Dynamic arguements in procedures in Javascript

can someone help me to understand the signifigance of : 1 and : 2 in below code.
I understand these will be replaced by dynamic values but what exact values would it be?

call insert_data(''val1'',''val2'',''val3,''val4);

CREATE OR REPLACE PROCEDURE "INSERT_DATA"("val1" VARCHAR(16777216), "val2" VARCHAR(16777216), "val3" VARCHAR(16777216), "val4" VARCHAR(16777216))
RETURNS VARCHAR(16777216)
LANGUAGE JAVASCRIPT
EXECUTE AS OWNER
AS '

    var status="";
    var insertTemplateSQL = `
        insert into identifier(:1)
        (    PRACTICE_ID,CLIENT_ID,PLANNING_PLACEMENTID,CLIENT_PLACEMENTID,ME_ID,BRAND_NAME,SUPPLIER,VEHICLE_NAME,TARGETL....
        )
        select 
a.GRANULARITY,a._UPLOAD_ID,:2, HASH(a.*)
    from 
        identifier(:2) a

I googled but couldn’t find anything related.

Twilio – Voice – Javascript SDK – Issue in Incoming call – Capture call disconnect

I have setup a webhook for incoming call which forwards the call to a browser javascript client.

The browser client, on incoming call, asks the user to accept or reject the call. The call is continued or rejected based on the user’s choice.

The issue is when the call is waiting at the browser client and the user is not reacted yet, the call times out and the caller is forwarded to voice mail.

However, the browser client still waits for the user to respond. The user comes to know about the timeout after accepting the call.

I tried to use the call disconnect event but it is not invoked. Below is the JS code used. How to resolve this issue?

function disconnectCall() { 
    $("#m_callsubmit").show();  
    $("#endcall").hide();       
    $("#hangup").hide();  
    if(swal.isVisible()){swal.close();}         
}

async function startupClient() {
    try {const data = await $.getJSON("");token = data.token;intitializeDevice();} 
    catch (err) {console.log(err);}
}
  

function intitializeDevice() {
    device = new Twilio.Device(token, {logLevel: 1,codecPreferences: ["opus", "pcmu"]});

    device.on("registered", function () { $("#spnDeviceR").show();  $("#spnDeviceN").hide(); }); 

    device.on("error", function (error) { $("#spnDeviceR").hide(); $("#spnDeviceN").show(); $("#spnDeviceN").attr("title", error.message);  cosole.log(error.message); });

    device.on("incoming", function (call) {  

    call.on("disconnect", disconnectCall);  

    swal.fire({
    text: "You have a Call.",
    type: "info",showCancelButton: true,
    confirmButtonText: "Accept",cancelButtonText: "Reject",}).then(function(result){
    if (result.value) { call.accept(); scallid = call.parameters.CallSid ;  $("#m_callsubmit").hide();  $("#endcall").show();       $("#hangup").show();    }
    else if (result.dismiss === "cancel") { call.reject();   } })   }); 

    device.register();
}

startupClient();

nana4d situs terpercaya hadiah 10 juta deposit qris

Permainan togel online saat ini sudah bisa anda mainkan dan mendapatkan hadiah terbesar mencapai togel hadiah 4D 10 juta rupiah. Modal yang anda butuhkan juga termasuk sangat murah yaitu hanya dengan modal deposit 10 ribu saja dan juga minimal bet 100 perak saja. Anda juga sudah bisa memasang taruhan di 86 pasaran terbesar yang sudah resmi terdaftar di WLA. Jadi akan dipastikan jika anda memasang taruhan di situs togel terpercaya NANA4D sudah sangat aman dan terpercaya.

DAFTAR DISINI : https://preciseurl.com/NANA4D24

Selain itu jika anda juga memasang taruhan di situs NANA4D maka anda juga sudah berkesempatan mendapatkan togel hadiah terbesar 10 juta rupiah. Tentu saja hal ini akan sangat menguntungkan bagi para pecinta togel online karena bisa menikmati berbagai fasilitas terlengkap dan juga pelayanan terbaik di situs NANA4D. Selain menyediakan modal deposit yang murah, situs NANA4D juga menyediakan transaksi pembayaran deposit yang sangat memudahkan anda dalam melakukan pembayaran. Anda bisa menggunakan Tarnsfeer Bank dan juga e-wallet yang saat ini sudah memiliki sangat banyak pengguna di Indonesia.

NANA4D SITUS TERPERCAYA HADIAH 10 JUTA DEPOSIT QRIS

object clipping in Javascript physics simulation

Following a few tutorials to create a physics sim with javascript and html. The goal is to spawn a number of different sized balls and when they spawn to have them fall to the bottom of the canvas and land on each other till it nearly fills the canvas. I’ve gotten pretty far with proper collisions and gravity but one bug I’m running into is that once the balls start to settle at the bottom, the balls start to slowly sink and clip into each other.

gif of the outcome


const canvas = document.querySelector('canvas')
const c = canvas.getContext('2d')
const img = document.getElementById('planet1');

canvas.width = innerWidth-100;
canvas.height = innerHeight-100;

const mouse = {
  x: innerWidth / 2,
  y: innerHeight / 2
}

const colors = ['#2185C5', '#7ECEFD', '#FF46E5', '#FF7F66'];

var gravity = 0.2;
var friction = .4;

// Event Listeners
addEventListener('mousemove', (event) => {
  mouse.x = event.clientX
  mouse.y = event.clientY
})

addEventListener('resize', () => {
  canvas.width = innerWidth-100
  canvas.height = innerHeight-100

  init()
})

function randomIntFromRange(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min)
    }
  
function randomColor(colors) {
    return colors[Math.floor(Math.random() * colors.length)]
    }
    
function distance(x1, y1, x2, y2) {
    const xDist = x2 - x1
    const yDist = y2 - y1
    
    return Math.sqrt(Math.pow(xDist, 2) + Math.pow(yDist, 2))
    }

function rotate(velocity, angle) {
    const rotatedVelocities = {
        x: velocity.x * Math.cos(angle) - velocity.y * Math.sin(angle),
        y: velocity.x * Math.sin(angle) + velocity.y * Math.cos(angle)
    };

    return rotatedVelocities;
}

function resolveCollision(particle, otherParticle) {
    const xVelocityDiff = (particle.velocity.x - otherParticle.velocity.x);
    const yVelocityDiff = (particle.velocity.y - otherParticle.velocity.y);

    const xDist = otherParticle.x - particle.x;
    const yDist = otherParticle.y - particle.y;

    // Prevent accidental overlap of particles
    if (xVelocityDiff * xDist + yVelocityDiff * yDist >= 0) {

        // Grab angle between the two colliding particles
        const angle = -Math.atan2(otherParticle.y - particle.y, otherParticle.x - particle.x);

        // Store mass in var for better readability in collision equation
        const m1 = particle.mass;
        const m2 = otherParticle.mass;

        // Velocity before equation
        const u1 = rotate(particle.velocity, angle);
        const u2 = rotate(otherParticle.velocity, angle);

        // Velocity after 1d collision equation
        const v1 = { x: u1.x * (m1 - m2) / (m1 + m2) + u2.x * 2 * m2 / (m1 + m2), y: u1.y };
        const v2 = { x: u2.x * (m1 - m2) / (m1 + m2) + u1.x * 2 * m2 / (m1 + m2), y: u2.y };

        // Final velocity after rotating axis back to original location
        const vFinal1 = rotate(v1, -angle);
        const vFinal2 = rotate(v2, -angle);

        // Swap particle velocities for realistic bounce effect
        particle.velocity.x = vFinal1.x;
        particle.velocity.y = vFinal1.y;

        otherParticle.velocity.x = vFinal2.x;
        otherParticle.velocity.y = vFinal2.y;
    }
}

// Objects
class Planet {
  constructor(x, y, radius, color) {
    this.x = x
    this.y = y
    //this.dx = dx;
    //this.dy = dy;
    this.velocity = {
        x: Math.random() - 0.5,
        y: Math.random() - 0.5
    }
    this.radius = radius
    this.color = color
    this.mass = 2;
  }

  draw() {
    c.beginPath()
    c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false)
    c.fillStyle = this.color
    c.fill()
    c.strokeStyle = 'black'
    c.stroke()
    c.closePath()
  }

  update(planets) {
    for (let i = 0; i < planets.length; i++){
        if (this === planets[i])continue;
        if ((distance(this.x,this.y,planets[i].x,planets[i].y)) - (this.radius + planets[i].radius) < 0){
            resolveCollision(this,planets[i])          
        }
    }
    if (this.y + this.radius + this.velocity.y > canvas.height) {
      this.velocity.y = -this.velocity.y;
      this.velocity.y = this.velocity.y * friction;
      this.velocity.x = this.velocity.x * friction;
    } else {
      this.velocity.y += gravity;
    }

    if (this.x + this.radius >= canvas.width || this.x - this.radius <= 0) {
      this.velocity.x = -this.velocity.x * friction;
    }

    
  

    this.x += this.velocity.x;
    this.y += this.velocity.y;
    this.draw()
  }
}

// Implementation
let planets;
function init() {
  planets = [];

  for (let i = 0; i < 150; i++) {
    const radius = randomIntFromRange(10,40);
    let x = randomIntFromRange(radius,canvas.width-radius);
    let y = randomIntFromRange(radius,canvas.height-radius);
    //const dx = randomIntFromRange(-3,3);
    //const dy = randomIntFromRange(-2,2);
    const color = randomColor(colors);

    //dont spawn on top of each other
    if (i!==0){
        for(let j = 0; j < planets.length; j++){
            if((distance(x,y,planets[j].x,planets[j].y)) - (radius + planets[j].radius) < 0){
                x = randomIntFromRange(radius,canvas.width-radius);
                y = randomIntFromRange(radius,canvas.height-radius);

                j = -1;
            }
        }
    }

    planets.push(new Planet(x,y,radius,color));
  }
}

// Animation Loop
function animate() {
    requestAnimationFrame(animate)
    let length = planets.length;
    c.clearRect(0, 0, canvas.width, canvas.height);
    
    for(let i =0;i<planets.length;i++){
        planets[i].update(planets);
    }
}

init()
animate()

I’m thinking it has to do with how I’m applying the gravity on line 132 but I am not sure how to proceed with fixing it. Any help would be greatly appreciated! Thanks!!

App badge doesn’t update on getting notifications in React Native

In my React Native application, i am getting notifications and i am using @react-native-community/push-notification-ios to update the badge on app icon when the user opens a notification. But when the app is in the background, notification comes and the badge count remains the same. It always shows 1. What can i do to fix this part. I am guessing i have to do something in AppDelegate.m as i am not using any other dependency for the notification. Here’s what my AppDelegate.m looks like:

#import "AppDelegate.h"

#import <React/RCTBundleURLProvider.h>
#import <Firebase.h>
#import <UserNotifications/UserNotifications.h>
#import <RNCPushNotificationIOS.h>
#import <React/RCTLog.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  self.moduleName = @"Bisly";
  // You can add your custom initial props in the dictionary below.
  // They will be passed down to the ViewController used by React Native.
  self.initialProps = @{};

   [FIRApp configure];
  RCTLog(@"Some information3");
  NSLog(@"Some information4");

  return [super application:application didFinishLaunchingWithOptions:launchOptions];

  // UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  // center.delegate = self;

  // return YES;
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
 [RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

// Required for the notification event. You must call the completion handler after handling the remote notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
  RCTLog(@"Some information");
  NSLog(@"Some information2");
  [RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}

// Required for the registrationError event.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
 [RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
}
// Required for localNotification event
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)(void))completionHandler

{
  RCTLog(@"Some information1");
  [RNCPushNotificationIOS didReceiveNotificationResponse:response];
}


//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
  completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}


- (BOOL)concurrentRootEnabled
{
  return true;
}

@end

Multiple PDF Base64 convert to single PDF file in Javascript or Jquery

we have a multiple PDF Base64 string on array object. Its convert to single PDF file in Javascript or Jquery

var base64String = “JVBERi0xLjcNCiWhs8XXDQoxIDAgb2JqDQo8PC9QYWdlcyAyIDAgUiAvVHlwZS9DYXRhbG9nPj4NCmVuZG9iag0KMiAwIG9iag0KPDwvQ291bnQgMS9LaWRzWyA0IDAgUiBdL1R5cGUvUGFnZXM+;

function openPDF() {
  console.log('open pdf clicked');
  window.open("data:application/octet-stream;base64," + base64String);
}

function openPDFv2() {
  console.log('open pdf v2 clicked');
  const container = document.querySelector('#container');
  const tempLink = document.createElement('a');
  tempLink.href = `data:application/pdf;base64,${base64String}`;
  tempLink.setAttribute('download', 'my-fancy.pdf');
  console.log('click now!', tempLink.click);
  //container.append(tempLink);
  tempLink.click();
}   

Its Working Single Base64.

D3 .extent() rejecting array of Dates in typescript

I’m struggling to utilize d3’s .extent() function in typescript.

I’ve got some code here that creates Date objects out of dates

 const dates:(Date | null)[] = data.map(row => d3.timeParse("%Y-%m-%d")(row.Date))

When I console log the dates variable, it looks something like this

[Sat Jun 24 2023 00:00:00 GMT-0700 (Pacific Daylight Time), Sat Jun 24 2023 00:00:00 GMT-0700 (Pacific Daylight Time), Fri Jun 23 2023 00:00:00 GMT-0700 (Pacific Daylight Time), Fri Jun 23 2023 00:00:00 GMT-0700 (Pacific Daylight Time), Fri Jun 23 2023 00:00:00 GMT-0700 (Pacific Daylight Time), ...]

Therefore, I know my dates variable is full of Date objects, like expected…

However, when I try and use the d3.extent() function to find the highest and lowest dates

const xScale = d3
      .scaleTime()
      .domain(d3.extent(dates))
Argument of type '[undefined, undefined] | [string, string]' is not assignable to parameter of type 'Iterable<Date | NumberValue>'.

I’m confused as to why this might be, though, as my dates variable is in fact exclusively dates, and not, as is expressed in the error, ‘[undefined, undefined] | [string, string]’.

What is wrong about what I am passing in? How should I be passing in dates to the extent() function in typescript?

Convert UTC string to local time string moment js

I’ve a utc time string lets say 05:01 I want to convert this into localtime string.
Something like this 08:33.

I’ve tried this but its giving blank output.

var str = "05:03";
var d = moment(str, 'HH:mm').format('HH:mm').local();

I want to make it work using momemt js.

When the button is pressed twice by the same user, it crashes the bot. Discordjs

I wanted to make a fight command. So basically,

1, the player would type /fight

2, embed and button will be displayed

3, when the player presses the punch button, it will decrease the enemy’s health. Which worked. But when the same player presses the punch button again, it will log ‘Interaction is already acknowledged.’ crashing the whole bot.

Here is the code where it went wrong, this is to prevent the ‘Interaction failed’ error that appears in discord:

 const collector = lastReply.createMessageComponentCollector({
                    componentType: ComponentType.Button,
                    time: 15000,
                  });
                
                    collector.on("collect", async (interaction) => {
                        await interaction.deferUpdate()
                        
                        console.log('yes.')
                        return;
                    })
                

I got a seperate part to check if player had punched and decrease health

const confirmation = await lastReply.awaitMessageComponent({ time: 60_000 });
if (confirmation.customId === 'punch') {
 //the part where i decrease the enemy's health
}

I tried removing await interaction.deferUpdate() in the collector.on but it says ‘Interaction failed’.
I only wanted to allow the player to press the button twice without ‘Interaction failed’ error.

Typescript compiler not emitting errors in browser environment

I was making a code editor for typescript that runs within browser. For transpilation, i decided to use the typescript compiler (https://cdnjs.cloudflare.com/ajax/libs/typescript/5.1.6/typescript.min.js)

I transpiles to javascript, but is not emitting errors such as type errors, etc. The compiler I am using runs in a browser environment.

This is the typescript code before compiling
Raw typescript code

This is the code after compiling to javascript
Compiled typescript code

It should have raised some errors.

How do i enable the errors? Do i need to toggle some compiler options or do I need to use a different compiler?

For the code editor, you can find it at devnuts.surge.sh (for more clarity on what i am trying to make)

Thanks

I’ve done some research on it but the most i could find was errors in nodejs environment.
I tried toggling the compiler options for emitting errors but didn’t help.

Which laptop is recommended for a front-end programmer

Could you kindly assist me by recommending a laptop suitable for a front-end programmer? I’m currently a beginner in JavaScript but proficient in HTML and CSS. I’d appreciate it if you could specify a particular laptop and provide reasons. It’s important for me to avoid switching laptops due to work commitments in the near future, so I’m seeking a reliable option that can support my coding endeavors without interruption.

This is the laptop I have in mind “HP Folio 1040 G3”.