Add custom method to ECMAScript object

Since I am limited to use ECMAScript version 7, and I wanted to use String methods like padStart() introduced in ES 8

I added the folowing code for the custom padStart(digits,character) method which was working as expected:

String.prototype.padStart = function(digits,fill){
        value = this;
        while (value.length < digits){
       value = fill+value;
   }
   return value
}

Now I added a second method padEnd(digits,character) to my code:

String.prototype.padEnd = function(digits,fill){
        value = this;
        while (value.length < digits){
       value = value + 'X';
   }
   return value + 'X'
}

And I was expecting I were able to uses both new methods on String-Objects, but I found that only the code of the first method is used, even if I use the padEnd() method on the String object.

What am I doing wrong?

Div covered using ngIf is still visible for a second

I’m trying to make a webpage using Angular 17 that opens into a ‘loading screen’ div positioned above the other elements, and the div disappears after two seconds. The timer is controlled using setTimeout(). It sort of works, except the main content is still visible for a second before the loading screen pops up.

app.component.html

<div *ngIf = "LoadingStatus" class = "LoadingScreen">
  <!-- div displays loading screen for two seconds upon opening, then disappears. -->
</div>

<!-- <ng-container *ngIf = "!LoadingStatus"> -->
  <div class = "background">
    <div id = pLogo>
      <!-- main content -->
    </div>
  </div>
  <router-outlet />
<!-- </ng-container> -->

app.component.ts

import { Component, OnInit } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { ButtonModule } from 'primeng/button';
import { DividerModule } from 'primeng/divider';
import { RippleModule } from 'primeng/ripple';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, ButtonModule, DividerModule, RippleModule, CommonModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent implements OnInit{
  title = 'login_app';
  LoadingStatus = true;

  ngOnInit(): void {
    setTimeout(() => {
      this.LoadingStatus = false;
    }, 2000);
  }
}

app.component.css

h1, h2, h3, p {
    font-family: "Arial";
}

#pLogo {
    position: fixed;
    top: 20px;
    left: 20px;
}

.background {
    background-color: #ffffff;
    height: 100vh;
    width: 45%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
}

#welcomeText {
    margin-top: 25%;
}

#loginButton {
    margin-top: 15%;
}

#RequestAccessLink {
    margin-top: auto;
    margin-bottom: 10%;
}

:host ::ng-deep .p-button { 
    background-color: #00a19c;
    border-color: #00a19c;
    font-family: Arial, sans-serif !important;
    font-size: 1.5vw;
}

:host ::ng-deep .p-button:hover { 
    background-color: #00928d;
    border-color: #00928d;
    font-family: Arial, sans-serif !important;
    font-size: 1.5vw;
}

.LoadingScreen {
    background-color: #00a19c;
    height: 100vh;
    width: 100vw;
    margin:0px;
    position: fixed;
    z-index: 1000;
}

What could the issue be?

Thank you!

Openlayers throws error by applying extent on ol.layer.Tile

I’m trying to render a tile layer on Open Street Map as an overlay layer.
When I set extent to avoid sending out-of-bound requests to the tile server, I get error tilesByZ[z] is not iterable which I don’t understand.

enter image description here

Here is my code:

/**
 * Create ol.layer.Tile
 * @param {ITileLayer} params layer parameters
 */
export const CreateTileLayer = (params: ITileLayer): TileLayer<OSM | XYZ> => {
  const layer = new TileLayer({
    source: CreateTileSource(params.id, params.url),
    properties: {
      id: params.id,
      label: params.label,
      groupId: params.groupId,
      type: params.type,
    },
    extent: params.extent,
  });
  layer.setZIndex(params.zIndex);
  layer.setVisible(params.visible);
  return layer;
};

I searched on Openlayer github issues and I found it was reported here as a bug and fixed here.

Then I tried to install the latest version ("ol": "^10.0.0") but it didn’t work.
I expected the new release fixes this issue.

Should I wait for a new release?

How to correctly manage state in a parent component when passing data to child components in React?

I’m building a React application where I have a parent component that holds the state and several child components that need to receive and update this state. I’m using props to pass the state and a callback function to update the state from the child components. However, I’m encountering issues where the state updates aren’t reflecting immediately in the child components, or the state becomes inconsistent.

function ParentComponent() {
    const [data, setData] = useState([]);

    const updateData = (newData) => {
        setData(newData);
    };

    return (
        <div>
            <ChildComponent data={data} updateData={updateData} />
            <AnotherChildComponent data={data} />
        </div>
    );
}

function ChildComponent({ data, updateData }) {
    const handleClick = () => {
        const updatedData = [...data, 'New Item'];
        updateData(updatedData);
    };

    return (
        <div>
            <button onClick={handleClick}>Add Item</button>
        </div>
    );
}

function AnotherChildComponent({ data }) {
    return (
        <ul>
            {data.map((item, index) => (
                <li key={index}>{item}</li>
            ))}
        </ul>
    );
}


What is the best practice for managing state between parent and child components in React?
How can I ensure that all child components receive the updated state immediately?
Are there any performance concerns with this approach, and how can I optimize it?

Converting array and array of arrays into array of objects [duplicate]

I’ve been facing issues in making array of objects using array and array of arrays. In my scenario I’m having 400 cols and 5000 rows. Having col names in separate array and user data in array of arrays.

My Expectation:
Array of objects = Array (Cols_name) + Array_of_arrays (User_data)

var cols_names=['name','address','phoneno'];
var arr_of_arrs=[
    ['ABC','INDIA','0989898976'],
    ['XYZ','USA','0989898998'],
    ['CDE','UK','0989898956']
    ];
    
const arr_of_obj = arr_of_arrs.map((...cols_names) => ({cols_names}));
console.log(arr_of_obj);

I got output like this:

[
  { cols_names: [ [Array], 0, [Array] ] },
  { cols_names: [ [Array], 1, [Array] ] },
  { cols_names: [ [Array], 2, [Array] ] }
]

I need like this:

[
  {
    "name":"ABC",
    "address":"INDIA",
    "phoneno":"0989898976"
  },
  {
   "name":"XYZ",
    "address":"USA",
    "phoneno":"0989898998"
  },
  {
    "name":"CDE",
    "address":"UK",
    "phoneno":"0989898956"
    
  }
]

Note: I can’t write the below code like this because I’m having 400 cols. I should not specify each and every col names statically in the code:

const arr_of_obj = arr_of_arrs.map(([name,address,phoneno]) => ({name, address,phoneno}));

console.log(arr_of_obj);

Javascript amcharts5 heat map heat legend add gradient color

I am sorry this question may not be smooth using a translator.

I using amcharts5.
I’d like to add some color to the gradients.
The only thing found was to specify start color and end color.
The other gradation demo was not to have a smooth color, but to specify a color for each value.

https://www.amcharts.com/demos/heat-map-with-legend/

When using code, you can specify only two colors.

https://www.amcharts.com/docs/v5/tutorials/a-custom-heat-legend-using-a-gradient/

This demo wasn’t the gradient addition I wanted.
I want to add the desired color and designate offset for each color so that it connects naturally.

color: [
‘#313695’, ‘#00a31b’, ‘#f0d800’, ‘#f06c00’, ‘#f00000’, ‘#cc0055’
]

I hope the color will be designated and it will continue smoothly.

enter image description here

I want to add colors to make a legend like the image.

cors error in backend php server , the api is working in some devices and giving cors error in some devices

i have created a chatbot has form , and the form will send the payload to backend php server , the api will create conversation , the chatbot is fully working in some devices, and it is giving cors error some devices.
headers i am sending from frontend –

    const response = await fetch("https://example.com/api/create-conversation", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    });
    const result = await response.json();

the backend php code :

header("Access-Control-Allow-Headers: *");
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        header("HTTP/1.1 200 OK");
        header("Content-type:application/json");
        header('Content-Type: text/plain');

Why is the API working on some devices but not on others? I am using var client = new XMLHttpRequest(); to load the page, and the UI automatically updates. The targeted frontend has an embed code which is opened with client.open(“GET”, “https://example.com/embed-code”);. I have targeted the UI of the embed code with DOM manipulation and handle the UI inside the client.onload scope, while the functions responsible for API handling are outside this scope.

Given this setup, why does the API work on some devices but not on others? The console shows an error: “(Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 404.” I have added the header: header(“Access-Control-Allow-Origin: *”);.

The API is not working consistently across all devices; some devices return a CORS error. I want the API to work on every device. What could be the issue?

ReadableStream from Fetch API not consuming entire data

I am trying to use Fetch API’s stream capability to read streaming data from backend and use it, based on this.

My code is structured as:

function init() {
  container = document.createElement("div");
  document.body.appendChild(container);

  fetch("http://localhost:8080/data/stream", {
    method: "GET",
    headers: {
      Accept: "application/json",
    },
  }).then((response) => {
    const reader = response.body.getReader();
    return new ReadableStream({
      start(controller) {
        return pump();
        function pump() {
          return reader.read().then(({ done, value }) => {
            // When no more data needs to be consumed, close the stream
            if (done) {
              controller.close();

              // do something with data fetched

              return;
            }
            // Enqueue the next data chunk into our target stream
            controller.enqueue(value);

            // put data in some data structures(like arrays) for using at end

            return pump();
          });
        }
      },
    });
  });
}

init();

But this is not working as expected. I expect it to consume all of the streamed data, but while backend streams almost 1.5 million records, this code is able to consume very little of that. ‘done’ gets true even before entire data has arrived.

What mistake am I making here?

How do I set up a UI Aceternity component in a preexisting Next.js project?

I watched a video and found out about UI Acernity and it feels like a godsend. However, I am struggling with setting it up. I have read some articles and watched some videos but it feels like I am learning how to code for the first time again and I have no clue what I am doing. I am so clueless I nearly deleted my project directory by accident.

So I was wondering if anyone could explain how to do this. I am trying to follow the guides on https://ui.aceternity.com/components/background-boxes which is the component I want to add, but typescript is tripping me up. Could anyone explain to me how to do this?

I tried downloading dependencies, then adding a util file, and then updating my tailwind.config.js file, but I kept on running into an error or some issue that was different everytime. I also tried installing shadcn and doing it that way but that led to even more issues.

Making JavaScript WebApps based on a database

I’d like to learn to make web applications based on databases, like this example. I couldn’t find a lot of information regarding the backend on the GitHub repo of the example.

In the example, there seems to be a central database, and other individual elements are also generated for each “card”. Finally, there are scripts that control how the elements come together.

What should one learn to make such apps? Is this a Single Page Application? Are there any frameworks that exist already that can be used? How about the animations: are they made using CSS or Javascript? Does one have to use JavaScript, or can one use something like Rails or Django for the purpose? What about Flutter?

If someone can help me get started, that would be great!

Problem populating Street Address field using javascript in console on USPS Click-N-Ship web site

I am having a problem populating one field on the USPS Click-N_Ship web site from the console using Javascript.

I can populate First, Middle and Last Names, City, State, and Zip code, and even the Apartment field, but cannot populate the Street Address field. I suspect this is because the Street Address is a lookup field.

This code:

document.querySelector('input[name="recipient.firstName"]').value = "Jay";
document.querySelector('input[name="recipient.middleInitial"]').value = "A";
document.querySelector('input[name="recipient.lastName"]').value = "Talbott";
document.querySelector('input[name="recipient.addressLine2"]').value = "Apt 3.";
document.querySelector('input[name="recipient.city"]').value = "Denver";
document.getElementById('recipient-state').value = 'CO'
document.querySelector('input[name="recipient.zip9"]').value = "80601";

Will produce the expected results filling in the appropriate fields.

The elements of the Street Address are shown in the image.

Can someone tell me what javascript I need to use to populate the Street Address field?

Thank you.

I have tried document.getElementById(‘recipient-addressLine1’) and variations thereof without any luck..

[elements of Street Address field]
: https://i.sstatic.net/AbC69M8J.png

Using .scale() in HTML canvas causes hit detection issues

NOTE

Here is a link to a video I made demonstrating the issue at hand on Dropbox: https://www.dropbox.com/scl/fo/p19oite64o22sh9bl8s1b/ALnUvrJzNbK7QixHrgHGgdY?rlkey=gpxahqur1kmfdqr1ulow4bk04&st=hybj5h8y&dl=0

CONTEXT

I’m trying to create an agario-type game where the player spawns in as a circle and is able to eat small, circular foods to get bigger. I’m using HTML canvas on the client side and Node.js on the server side.

PROBLEM

I’ve been having great difficulty figuring out how to correctly scale the world as the player eats more food. In this game, when the player touches the food at all, they eat it. I’m using the .scale() method to slowly zoom out, so that as the player gets bigger, they don’t eventually totally overtake the screen so that they can’t see anything but themselves. However, as the player gets bigger, the hit detection gets worse — the player will be on top of a food and won’t eat it or will eat it before they touch it. It also seems that this poor hit detection corresponds to the direction: when the player moves upwards, the food is eaten late, as in the food will overlap the player and not be eaten. The same happens when the players moves left, where the food will overlap the player and not be eaten. Oppositely, when the player moves either right or down, the food will be eaten before the player makes contact with food. It’s as if I just have to move the player to the right a certain amount, but I don’t know which code to change or why it is causing issues in the first place.

CODE

I’ve removed code that does not seem to be relevant to the issue.

The Node.js server currently handles everything (spawning foods, calculating collisions between players, foods, etc.) except for giving player coordinates, as the client sends their coordinates to the server on every frame.

The “Player” class creates the structure for player objects. Within the Player class, I have the draw() method, which looks like this: 



draw(viewport) {
    if (this.isLocal) { //if it's the local player, send coordinates to server
        socket.emit('currentPosition', {
            x: this.x / zoom,
            y: this.y / zoom,
            radius: this.radius / zoom,
            speedMultiplier: this.speedMultiplier,
            vx: this.vx, //update these on server side?
            vy: this.vy
        });
    }

    ctx.save();
    ctx.translate(-viewport.x, -viewport.y);

    //scale the player
    ctx.scale(zoom, zoom);

    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
    ctx.fillStyle = this.color;
    ctx.fill();
    ctx.strokeStyle = this.strokeColor;
    ctx.lineWidth = 5;
    ctx.stroke();
    ctx.closePath();
    ctx.restore(); 
}

Within this draw() method, I use ctx.scale(zoom, zoom) to scale the player. My understanding is that this essentially multiplies the x/y position and the radius by the zoom factor. 

I also have a Food class, which creates food objects. The Food class’s draw() method looks like this: 



draw(viewport) {
        ctx.save();
        ctx.translate(-viewport.x, -viewport.y);
        ctx.scale(zoom, zoom); //scale foods
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
        ctx.fillStyle = this.color;
        ctx.fill();
        ctx.strokeStyle = this.strokeColor;
        ctx.lineWidth = 3.5;
        ctx.stroke();
        ctx.closePath();
        ctx.restore();
}

Both of these draw() methods are meant to scale the player and foods according to how many foods the player has eaten. When the player eats an individual food, the zoom rate decreases. The server tells the player when they have eaten food:



socket.on('foodEaten', (data) => {
    const player = gamePlayers.get(data.playerId);
    if (player.id == localPlayer.id) {
        zoom *= 0.9999;
    }
…

So, for each food the player eats, they zoom out by 0.9999.

The player’s movement is determined by where their mouse moves. When they move their mouse, this event listener calculates the direction the mouse is pointing in and sets the player on that path: 



canvas.addEventListener('mousemove', (event) => {
    const rect = canvas.getBoundingClientRect(); 
    mouse.x = (event.clientX - rect.left) / zoom; 
    mouse.y = (event.clientY - rect.top) / zoom; 

    // Update player's target position
    localPlayer.targetX = (mouse.x + viewport.x / zoom);
    localPlayer.targetY = (mouse.y + viewport.y / zoom);

    const dx = (localPlayer.targetX - localPlayer.x) * zoom;
    const dy = (localPlayer.targetY - localPlayer.y) * zoom;
    const distance = Math.sqrt(dx * dx + dy * dy); 

    ...does some other stuff in between...

    const xMovingDirection = dx / distance;
    const yMovingDirection = dy / distance;

    localPlayer.movingDirection = { x: xMovingDirection, y: yMovingDirection};
});

I mentioned in the draw() method of the Player class that they emit their current position to the server before the player is drawn:



socket.emit('currentPosition', {
    x: this.x / zoom,
    y: this.y / zoom,
    radius: this.radius / zoom,
    speedMultiplier: this.speedMultiplier,
    vx: this.vx,
    vy: this.vy
});

I divide the x and y coordinates and the radius by the zoom level to allow the server to disregard individual player’s zoom levels, so that every other player in the game is being sent non-zoomed coordinates.

After the server receives this information, it evaluates the player’s position against every food in the game, checking if they are colliding: 



socket.on('currentPosition', (data) => { //get player's current x/y coordinates and update them
    const player = room.players.get(socket.id);
    if (player) {
        player.x = data.x; //update player x position
        player.y = data.y; //update player y position

        room.foods.forEach((food, foodId) => { //check for foods being eaten
            if (checkCollision(player, food)) {
                player.radius += food.radius * normalRadiusIncreaseRate; //increase player radius

                let newFood; //add food back in
                newFood = new Food(); //add new food item
                room.foods.set(newFood.id, newFood);

                //let player know that they ate food
                io.to(room.roomId).emit('foodEaten', {
                    food: food,
                    playerId: player.id,
                    radius: player.radius,
                    newFood: newFood
                });

                room.foods.delete(food.id); //delete eaten food
            }

        //send this player’s data to other players
        socket.to(room.roomId).emit('updatePlayerTarget', {
            id: socket.id,
            x: player.x,
            y: player.y
            // radius: player.radius
        });                   
    }
});

If a player collides with a food, they should eat it. Node.js emits ‘foodEaten’ to the client, which allows the client to update the radius of the player who ate the food. It also gives the player’s x and y coordinates at the end of the block.

QUESTION

Why is it that, when using .scale(), the synchronization between the player and the food gets worse over time?

How do I create an array out of specific parts of JSON data?

After calling an API, I have some data in JSON format. Within that format, there is an array with sub-parts (I apologize, I don’t know the terminology) that exist inside each key of the array.

{
  "id": "<my id>",
  "bots": [],
  "avatar": "https://static-cdn.jtvnw.net/jtv_user_pictures/1c1c09ef-3937-4408-8f31-04ec6bec2238-profile_image-300x300.png",
  "channelEmotes": [],
  "sharedEmotes": [
    {
      "id": "<emote id>",
      "code": "<emote name>",
      "imageType": "<filetype>",
      "animated": true,
      "user": {
        "id": "<emote creator id>",
        "name": "<emote creator username>",
        "displayName": "<emote creator display name>",
        "providerId": "<not sure what this field is actually>"
      }
    },
    {
      "id": "<emote id>",
      "code": "<emote name>",
      "imageType": "<filetype>",
      "animated": true,
      "user": {
        "id": "<emote creator id>",
        "name": "<emote creator username>",
        "displayName": "<emote creator display name>",
        "providerId": "<not sure what this field is actually>"
      }
    }
  ]
}

Specifically, I want to make separate arrays for all the emote name, emote id, and filetypes like (I plan to have many more than these two)

var emotecodes = [code0, code1, ...];
var emoteids = [id0, id1, ...];
var emotefiletypes = [imageType0, imageType1, ...];

I’ve tried various other things I’ve found around the internet but have had no success.