Mapping through a json array to produce individual in astrojs

I am having problems mapping through a json array to produce individual li’s of the array items in astrojs. I was able to successfully map over a card component I made and was able to target specific elements to dynamically pull in json data but I am having trouble with doing the same with the li’s. I am able to pull in the json data but it does not showcase as individual li’s. All of the data shows up in one li oppose to individual li’s. A snippet of my json array and astrojs file code are below.

File: portData.json

"roleList": [ "UX/UI & Strategy", "Art Direction", "Prototyping" ],

File: astrojs code

<ul class="list-none text-base font-light">
   {
     portData.map((portData) => {
       return ( 
         <li>{portData.roleList}</li>
        )
     })
   }

Umbraco Rich Text Editor Insert/Edit Link Button Not Working

My Umbraco Document Type includes a property with a Rich Text Editor, which is used to edit the content for a product in Merchello within the Umbraco Backoffice. However, when I try to edit the content by clicking the Insert/Link button in the editor, the dialog doesn’t appear. Instead, I see an error in the browser’s Console Log.

Could this be a caching issue? I’d like to republish the site, but it’s currently in Production.

enter image description here

enter image description here

Uncaught TypeError: Cannot read properties of null (reading ‘properties’) at DependencyHandler.axd

It’s complaining that the editorState.current is Null. I don’t have any custom JavaScript code for this.

enter image description here

Why is my expand/collapse animation “jumping”?

I am working on an Angular 17 project with a Tailwind CSS-styled sidebar.

The expand/collapse functionality works as intended, but the animation is not as smooth as I would like. There is a noticeable “jump” in the animation, which disrupts the smooth transition I aim for. Ideally, the animation should smoothly transition from the top to bottom (and vice versa) without glitches.

Showcase of the problem: https://i.imgur.com/4RpEwYv.gif

My HTML Code:

<div class="flex h-screen bg-white">
  <aside class="w-72 bg-gray-900 shadow-lg flex flex-col">
    <!-- Navigation -->
    <nav class="p-4 pl-0 overflow-y-auto">
      @for (group of navigation; track $index) {
        <div class="mb-2" [class.pb-3]="$index != navigation.length - 1">
          <div class="flex flex-col">
            <div class="flex items-center justify-between pl-2 pr-0 cursor-pointer gap-2 w-[104%]" (click)="toggleGroup(group.category)">
              <div>
                <h3 class="px-0 mb-0 text-xs font-semibold text-gray-500 uppercase tracking-wider text-{{group.color}}-gradient">
                  {{ group.category }}
                </h3>
                <p class="text-xs text-gray-500 mb-0">{{ group.description }}</p>
              </div>
           </div>
          </div>

          <div class="mt-2 space-y-1 overflow-hidden" [@expandCollapse]="expandedGroups[group.category] ? 'expanded' : 'collapsed'">
            <div class="space-y-1">

              <!-- Show only 3 pages if group is not expanded & be able to expand it -->
              @for (page of (expandedGroups[group.category] ? group.pages : group.pages.slice(0, 3)); track $index) {
                <a [routerLink]="page.redirect_url"
                   class="flex items-center p-2 !text-slate-400 hover:bg-gray-500 rounded-lg transition-none hover:!text-white">
                  <div class="w-6 flex-shrink-0">
                    <fa-icon [icon]="page.icon"></fa-icon>
                  </div>
                  <span class="ml-3 text-[0.9rem]">{{ page.title }}</span>
                </a>
              }
            </div>
          </div>
        </div>
      }
    </nav>

  </aside>
</div>

TypeScript Code with Angular animation part:

@Component({
  selector: 'app-dashboard',
  standalone: true,
  imports: [
    NgOptimizedImage,
    RouterLink,
    FaIconComponent,
  ],
  templateUrl: './dashboard.component.html',
  styleUrl: './dashboard.component.scss',
  animations: [
    trigger('expandCollapse', [
      state('collapsed', style({
        height: '86px',
        overflow: 'hidden',
        opacity: 1
      })),
      state('expanded', style({
        height: '*',
        overflow: 'hidden',
        opacity: 1
      })),
      transition('expanded => collapsed', [
        style({ height: '*' }),
        animate('300ms cubic-bezier(0.4, 0.0, 0.2, 1)',
          style({ height: '96px' })
        )
      ]),
      transition('collapsed => expanded', [
        style({ height: '96px' }),
        animate('300ms cubic-bezier(0.4, 0.0, 0.2, 1)',
          style({ height: '*' })
        )
      ])
    ])
  ]
})
export class DashboardComponent {
  // it is filled, but commented out
  navigation = []

  expandedGroups: { [key: string]: boolean } = {};

  toggleGroup(category: string) {
    this.expandedGroups[category] = !this.expandedGroups[category];
  }

  constructor() {
      this.navigation.forEach(group => {
        this.expandedGroups[group.category] = false;
      });
  }

Initiate all potential props of the object right away or as you go?

I’m my scenario I have to create a lot of objects (100k+). Those objects can ‘evolve’ in the course if their life. Some will stay practically unchanged, others with will mutate and have a bunch of props assigned.

The most evolved objects might have 30+ properties.

All object are just data, no function, no logic.

From performance point of view, should I use:

const obj = Object.create(null)

obj.prop1 = ...;
obj.prop2 = ...;

//later

obj.prop3 = ...;

//later still

obj.prop4 = ...;

or

cost obj = {
    prop1 = ...;
    prop2 = ...;

    prop3 = undefined;
    prop4 = undefined;
}

Or just define the class and use new.

I’m considering the first approach because:

  1. there might be some memory savings with null prototype (and smaller hashtable?)
  2. it is nicer to iterate over object properties without doing ‘hasOwnProperty’.
  3. Also it will be easier for me to debug without a bunch of undefined properties hanging on the list in IDE/DevTools.

At the same time, I vaguely remember that v8 was doing some JIT magic with compilation of objects, but if I continue to add properties overtime, that this optimization could go out of the window.

Which option is better from memory usage and/or performance point of view?

if my oop design makes sense or any suggestions for chess

I’m creating a chess game and I was wondering if my OOP desighn makes sense or are there any suggestions to improve or bad pratices to avoid. Down below is the code

”’
export abstract class Pieces {

private color: string;
private prevRow: number
private prevCol: number
private name: string
public image: string

constructor(color: string,  prevRow: number, prevCol:number, image: string, name:string){
    this.color = color
    this.prevRow = prevRow
    this.prevCol = prevCol
    this.image = image
    this.name = name
}

abstract validMoves(chessboard: (Pieces | null)[][]):  number[][];

setPrevRow(row:number){
    this.prevRow = row
}

setPrevCol(col:number){
    this.prevCol = col
}

getColor() {
    return this.color
}

getPrevRow(){
    return this.prevRow
}

getprevCol(){
    return this.prevCol
}

getName(){
    return this.name
}

}

import { Pieces } from “./pieces”;

import { Riders } from “./riders”;

export class Bishop extends Pieces {

riders = new Riders()


validMoves(chessboard: (Pieces | null)[][]): number[][] {

    let prevRow = this.getPrevRow()
    let prevCol = this.getprevCol()
    let color  = this.getColor()

    let movements:[number, number][] = [
        [1,1],[1,-1],[-1,1],[-1,-1]
    ];

    const newMoves = this.riders.getMoves(chessboard, movements, prevRow, prevCol, color)
   
    return newMoves

}

}

import { Pieces } from “./pieces”;

export class King extends Pieces {

validMoves(chessboard: (Pieces | null)[][]): number[][] {
  
    let newMoves: number[][] = []; 

    let prevRow = this.getPrevRow()
    let prevCol = this.getprevCol()

    let movements:[number, number][] = [
        [ 1,0],[-1,0],[0,1],[0,-1],[1,-1],[1,1],[-1,-1],[-1,1]
    ];


    for(let movement of movements){
        if ( prevRow + movement[0] > -1 && prevRow + movement[0] < 8 && prevCol + movement[1]  > -1 && prevCol + movement[1] < 8 && chessboard[prevRow + movement[0]][ prevCol + movement[1]]?.getColor() != this.getColor()){
            const newMove = [prevRow + movement[0], prevCol + movement[1]]
            newMoves.push(newMove)
        }
        
    }
   
    return newMoves

}

}

import { Pieces } from “./pieces”;

export class Knight extends Pieces {

validMoves(chessboard: (Pieces | null)[][]): number[][] {

  
    let newMoves: number[][] = []; 

    const prevRow = this.getPrevRow()
    const prevCol = this.getprevCol()

    let movements:[number, number][] = [
        [prevRow+1, prevCol+2],
        [prevRow+2, prevCol+1],
        [prevRow+2, prevCol-1],
        [prevRow-1, prevCol+2],

        [prevRow-2, prevCol+1],
        [prevRow+1, prevCol-2],
        [prevRow-2, prevCol-1],
        [prevRow-1, prevCol-2]

    ];

    for(let movement of movements){
        if (movement[0] > -1 && movement[0] < 8 && movement[1]  > -1 && movement[1] < 8 && chessboard[movement[0]][movement[1]]?.getColor() != this.getColor()){
            let newMove = [movement[0], movement[1]]
            newMoves.push(newMove)
        }
        
    }

   
    return newMoves

}

}

import { Pieces } from “./pieces”;

export class Pawn extends Pieces {

validMoves(chessboard: (Pieces | null)[][]): number[][] {

  
    let newMoves: number[][] = []; 

    const prevRow = this.getPrevRow()
    const prevCol = this.getprevCol()

    if(this.getColor() === "Black"){
        if(prevRow === 6 ) {
            const newMove = [prevRow-2, prevCol]
            newMoves.push(newMove)
        }

        if(chessboard[prevRow-1][prevCol-1]!=null && chessboard[prevRow-1][prevCol-1]?.getColor()!=this.getColor()){
            const newMove = [prevRow-1, prevCol-1]
            newMoves.push(newMove)
        }

        if(chessboard[prevRow-1][prevCol+1]!=null && chessboard[prevRow-1][prevCol+1]?.getColor()!=this.getColor()){
            const newMove = [prevRow-1, prevCol+1]
            newMoves.push(newMove)
        }

        if(chessboard[prevRow-1][prevCol]?.getColor()!="White"){
            const newMove = [prevRow-1, prevCol]
            newMoves.push(newMove)
        }
      

    }

    else{
        if(prevRow === 1 ) {
            const newMove = [prevRow+2, prevCol]
            newMoves.push(newMove)
        }

        if(chessboard[prevRow+1][prevCol-1]!=null && chessboard[prevRow+1][prevCol-1]?.getColor()!=this.getColor()){
            const newMove = [prevRow+1, prevCol-1]
            newMoves.push(newMove)
        }

        if(chessboard[prevRow+1][prevCol+1]!=null && chessboard[prevRow+1][prevCol+1]?.getColor()!=this.getColor()){
            const newMove = [prevRow+1, prevCol+1]
            newMoves.push(newMove)
        }

        if(chessboard[prevRow+1][prevCol]?.getColor()!="Black"){
            const newMove = [prevRow+1, prevCol]
            newMoves.push(newMove)
        }
      
    }

    return newMoves

}

}

import { Pieces } from “./pieces”;
import { Riders } from “./riders”;

export class Queen extends Pieces {

riders = new Riders()


validMoves(chessboard: (Pieces | null)[][]): number[][] {

    let prevRow = this.getPrevRow()
    let prevCol = this.getprevCol()
    let color  = this.getColor()


    let movements:[number, number][] = [
        [1,0],[-1,0],[0,1],[0,-1],
        [1,1],[1,-1],[-1,1],[-1,-1]
    ];


    const newMoves = this.riders.getMoves(chessboard, movements, prevRow, prevCol, color)

   
    return newMoves

}

}

import { Pieces } from “./pieces”;

export class Riders {

getMoves(chessboard: (Pieces | null)[][], movements: [number, number][], prevRow:number, prevCol:number, color: string): number[][] {

  
    let newMoves: number[][] = []; 

    for(let movement of movements){
        
        let row_counter = prevRow
        let col_counter = prevCol
       
        while(row_counter + movement[0]!=-1 && row_counter + movement[0]!=8 && col_counter + movement[1]!=-1 && col_counter + movement[1]!=8){
            
            if (chessboard[movement[0] + row_counter][movement[1] + col_counter]?.getColor() != color && chessboard[movement[0] + row_counter][movement[1] + col_counter]?.getColor() != null){
                const newMove = [movement[0] + row_counter, movement[1] + col_counter]
                newMoves.push(newMove)                    
                break
            }

            if (chessboard[movement[0] + row_counter][movement[1] + col_counter]?.getColor() == color){
                break
            }
            
            
            const newMove = [movement[0] + row_counter, movement[1] + col_counter]
            newMoves.push(newMove)    
            
            row_counter+=movement[0]
            col_counter+=movement[1]

        }
        
    }
   
    return newMoves

}

}

import { Pieces } from “./pieces”;
import { Riders } from “./riders”;

export class Rook extends Pieces {

riders = new Riders()

validMoves(chessboard: (Pieces | null)[][]): number[][] {


    let prevRow = this.getPrevRow()
    let prevCol = this.getprevCol()
    let color  = this.getColor()


    let movements:[number, number][] = [
        [1,0],[-1,0],[0,1],[0,-1],
        [1,1],[1,-1],[-1,1],[-1,-1]
    ];


    const newMoves = this.riders.getMoves(chessboard, movements, prevRow, prevCol, color)

   
    return newMoves


}

}

”’

New tasks in todo list don’t render

Im making a project where you can have multiple todo lists which is managed by one big state.
Whenever you add a new item into the todo list the state gets updated twice the first time with the same value and then only once when you add another task. Also the new tasks don’t render. I want them to render and be put inside of the Task component.

import NewProj from "./components/NewProj";
import Button from "./components/Button";
import NoProj from "./components/NoProj";
import TodoList from "./components/TodoList";
import ColumnButton from "./components/ColumnButton";
import {useState, useRef } from "react";


function App() {
  const [masterTable, setMasterTable] = useState([]);
  const [pageIndex, setPageIndex] = useState({
    index: undefined, 
    page: false,
    proj: false,
  });

  function handleNewProj(title, desc, dueDate) {
    setMasterTable((prev) => {
      const id = Math.random();
      console.log(...prev);     
      return [...prev, {
        id: id,
        title: title,
        desc: desc,
        dueDate: dueDate,
        tasks: []
      }];
    });
  }
  function handlePage() {
    setPageIndex((prev) => {
      return {
        ...prev,
        page: true,
        proj: false,
      }
    });
  }
  function handleIndex(id) {
    const theIndex = masterTable.findIndex((proj) => proj.id === id);
    // console.log("theIndex: " + theIndex);
    setPageIndex(() => { 
      return {
        index: theIndex,
        proj: true,
        page: false,
      }
    });
  }

  // This adds the new task into the masterTable state
  function handleAddTask(task, index) {
    setMasterTable((prev) => {
      let prevRows = prev[index].tasks;
      const newRows = [...prevRows, task];
      let prevTable = prev;
      prevTable[index].tasks = newRows;
      return prevTable;
    });
  }

  return (
    <>
      
      <div className="flex flex-row w-screen mt-16">
        <div className="flex flex-col flex-wrap pl-12 bg-black w-[35%] s-12 h-screen rounded-tr-3xl rounded-br-3xl min-w-[300px] max-w-[400px]">
          <p className="text-white text-2xl font-semibold mt-[70px]">YOUR PROJECTS</p>
          <Button title="+ Add Project" newPage={handlePage} />
          <div className="flex flex-col ">
            {masterTable.map((obj, index) => <ColumnButton key={index} id={obj.id} title={obj.title} onC={handleIndex}/>)}
          </div>
        </div>
        
        { (!pageIndex.page && !pageIndex.proj) &&  <NoProj newPage={handlePage} />}
        {pageIndex.page  && <NewProj handleSubmit2={handleNewProj} /> }
        {pageIndex.proj && <TodoList {...masterTable[pageIndex.index]} index={pageIndex.index} addTask={handleAddTask}/> }
      </div>
    </>
  );
}

export default App;

And this the TodoList component where you add a task into the masterTable state

import Task from "./Task"
import { useRef, useState } from "react"


export default function TodoList({id, title, desc, dueDate, tasks, addTask, index}) {
    const taskInput = useRef();



    return <div className="flex flex-col mt-20 ml-10 w-[40%] ">
        <div className="flex flex-row justify-between mb-4">
            <p className=" text-3xl font-bold">{title}</p>
            <button className="w-[80px] h-10 hover:text-red-600">Cancel</button>
        </div>
        <p className="mb-4 text-stone-400">{dueDate}</p>
        <p className="mb-4 leading-loose border-b-2 pb-4 border-stone-300">{desc}</p>
        <p className="mt-1 text-3xl font-bold">Tasks</p>
        <div className="flex flex-row items-center">
            <input ref={taskInput}  className="mt-5 bg-stone-200 rounded-[3px] h-9 p-2 caret-stone-500 min-w-[250px] focus:ring-2 focus:ring-blue-500 focus:outline-none"></input>
            <button onClick={() => {
                const task = taskInput.current.value;    
                addTask(task, index);
                }} className="rounded-lg p-2 ml-2 text-stone-600 h-9 mt-5 w-fit">Add Task</button>
        </div>
        <div className="mt-7 bg-stone-200 p-7 divide-y-[20px]  divide-stone-200 rounded-sm ">
                {tasks.map((task) => {
                    <Task text={task} />
                })}

        </div>
    </div>
}

I tried instead of getting the value from the input element with ref and instead with useState which did display the tasks but only when you typed a letter into the input box which is not what i want. Also it still had added the same task twice when putting in the first task.

How to select the first specific element after a element (not in) by using JS

Recently, I am working on a Youtube comment loader project, and I want to select the first <p> element after <a> element in this example:

<p></p>
<a id="this_is_the_a_element">
  <p></p>
</a>
<pre></pre> <!-- More random elements here -->
<p id="first_p_after_a"></p>
<p id="second_p_after_a"></p>
<p id="third_p_after_a"></p>

I know I can using substring to achieve that, but is there a more efficient way (just like querySelector) to do that?

Also, how could I select the second, third, and so on element after a specific element?

GRPC issue with NestJS

I try to call an grpc python service with NestJS client I pass my parameter on the call and the python API return to me an error “Invalid URL: The ‘pdf_url’ field is empty”.

When I try to do the call with my terminal the parameter is correctly receive by my python API.

So I don’t know where my NestJS conf is not good.

pdf.proto (NestJS & Python service)

syntax = "proto3";

package pdfwhitespace;

service PDFWhitespaceService {
  rpc FindWhitestSpace (PDFRequest) returns (WhitespaceResponse) {}
}

message PDFRequest {
  string pdf_url = 1;
}

message WhitespaceResponse {
  message PageWhitespace {
    int32 page_number = 1;
    float left = 2;
    float top = 3;
    float width = 4;
    float height = 5;
  }
  repeated PageWhitespace whitespaces = 1;
}

server.py

class PDFWhitespaceServicer(pdf_whitespace_pb2_grpc.PDFWhitespaceServiceServicer):
def FindWhitestSpace(self, request, context):
        print(f"Raw request received: {request}")
        if not request.pdf_url:
            print("Field 'pdf_url' is missing or empty")
            context.set_details("Invalid URL: The 'pdf_url' field is empty")
            context.set_code(grpc.StatusCode.INVALID_ARGUMENT)
            return pdf_whitespace_pb2.WhitespaceResponse()
        print(f"Received URL: {request.pdf_url}")

NestJS config :

app.module.ts

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      cache: true,
      load: [
        ...
        PdfWhitespaceMicroserviceConfig,
      ],
    }),
    ...
  ],
  controllers: [...],
  providers: [...],
})

microservice.config.js

import { registerAs } from '@nestjs/config';
import { Transport } from '@nestjs/microservices';
import { join } from 'path';

export default registerAs('pdf-whitespace-microservice', () => ({
  transport: Transport.GRPC,
  options: {
    url: 'pdf-whitespace-microservice:50051',
    package: 'pdfwhitespace', // Doit correspondre au package défini dans .proto
    protoPath: join(__dirname, '../../protos/pdf_whitespace.proto'), // Chemin correct
  },
}));

pdf.service.ts

interface PageWhitespace {
  page_number: number;
  left: number;
  top: number;
  width: number;
  height: number;
}

interface WhitespaceResponse {
  whitespaces: PageWhitespace[];
}

interface GRPCPdfService {
  FindWhitestSpace(data: string): Observable<WhitespaceResponse>;
}

@Injectable()
export class PdfService extends ALoggerService {
  private grpcService: GRPCPdfService;

  constructor(@Inject('PDF_WHITESPACE_PACKAGE') private client: ClientGrpc) {
    super();
    try {
      this.grpcService = this.client.getService<GRPCPdfService>(
        'PDFWhitespaceService',
      );
      this.logger.debug('PDF service connection initialized successfully');
    } catch (error) {
      this.logger.error('Failed to initialize PDF service', error);
      throw error;
    }
  }

 async findWhitestSpace(pdf_url: string): Promise<PageWhitespace[]> {
    if (!pdf_url) {
      throw new Error('pdf_url cannot be empty');
    }
    console.log(`'{'pdf_url': '${pdf_url}'}'`);

    // const req = this.grpcService.FindWhitestSpace();

    return new Promise((resolve, reject) => {
      this.grpcService.FindWhitestSpace(`{pdf_url:plop}`).subscribe(
        (response) => {
          console.log('Response received:', response);
          resolve(response.whitespaces);
        },
        (error) => {
          console.error('gRPC error:', error);
          reject(error);
        },
      );
    });
  }
}

On my terminal I try with this command line :

grpcurl -plaintext -d '{"pdf_url": "https://example.com"}' localhost:50051 pdfwhitespace.PDFWhitespaceService/FindWhitestSpace

And it’s return “Received URL: https://example.com”

What’s wrong with my NestJS config ?

Google Maps API – Marker not working with a styled map

I’m trying to create a map with styles and markers.

The styled map works fine–but the marker is not showing.

What am I doing wrong?

I tried many solutions that are submitted here and reddit but none seems to work.

Here is the code:


function initMap() {
  // Styles a map in night mode.


  const map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: 40.674, lng: -73.945 },
    zoom: 12,
    disableDefaultUI: true,



    styles: [
    {
        "featureType": "all",
        "elementType": "all",
        "stylers": [
            {
                "visibility": "on"
            },
            {
                "color": "#3b6c39"
            }
        ]
    },
    {
        "featureType": "all",
        "elementType": "labels.text.fill",
        "stylers": [
            {
                "saturation": 36
            },
            {
                "color": "#000000"
            },
            {
                "lightness": 40
            }
        ]
    },
    {
        "featureType": "all",
        "elementType": "labels.text.stroke",
        "stylers": [
            {
                "visibility": "on"
            },
            {
                "color": "#000000"
            },
            {
                "lightness": 16
            }
        ]
    },
    {
        "featureType": "all",
        "elementType": "labels.icon",
        "stylers": [
            {
                "visibility": "off"
            }
        ]
    },
    {
        "featureType": "administrative",
        "elementType": "geometry.fill",
        "stylers": [
            {
                "color": "#000000"
            },
            {
                "lightness": 20
            }
        ]
    },
    {
        "featureType": "administrative",
        "elementType": "geometry.stroke",
        "stylers": [
            {
                "color": "#000000"
            },
            {
                "lightness": 17
            },
            {
                "weight": 1.2
            }
        ]
    },
    {
        "featureType": "landscape",
        "elementType": "geometry",
        "stylers": [
            {
                "color": "#000000"
            },
            {
                "lightness": 20
            }
        ]
    },
    {
        "featureType": "poi",
        "elementType": "geometry",
        "stylers": [
            {
                "color": "#000000"
            },
            {
                "lightness": 21
            }
        ]
    },
    {
        "featureType": "road.highway",
        "elementType": "geometry.fill",
        "stylers": [
            {
                "color": "#000000"
            },
            {
                "lightness": 17
            }
        ]
    },
    {
        "featureType": "road.highway",
        "elementType": "geometry.stroke",
        "stylers": [
            {
                "color": "#000000"
            },
            {
                "lightness": 29
            },
            {
                "weight": 0.2
            }
        ]
    },
    {
        "featureType": "road.arterial",
        "elementType": "geometry",
        "stylers": [
            {
                "color": "#000000"
            },
            {
                "lightness": 18
            }
        ]
    },
    {
        "featureType": "road.local",
        "elementType": "geometry",
        "stylers": [
            {
                "color": "#000000"
            },
            {
                "lightness": 16
            }
        ]
    },
    {
        "featureType": "transit",
        "elementType": "geometry",
        "stylers": [
            {
                "color": "#000000"
            },
            {
                "lightness": 19
            }
        ]
    },
    {
        "featureType": "water",
        "elementType": "geometry",
        "stylers": [
            {
                "color": "#1a1a1a"
            },
            {
                "lightness": 17
            }
        ]
    }
]
});
    const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
  const marker = new AdvancedMarkerElement({
    map,
    position: { lat: 40.73711331385601, lng: -73.99081789299093 },
  });
}

window.initMap = initMap;


I’m not asking to code the entire map for me with styles and markers but just to set me on the right path on how to make it work.

Thank you in advance.

How can I have HTML-formatted tooltips show up in dynamically generated Javascript results?

I’ve made a “random generator” tool for a tabletop RPG.

It dynamically generates some results using javascript tables.

What I want to do, is have certain words inside those tooltips get tooltip popups inside those results. And, importantly, have the tooltips get a little formatting.

Unfortunately, I’m pretty sure I’ve got things messed up.

I’ve got a bunch of HTML and work done but I’m stuck with this.

https://jetwong.neocities.org/armygens/weaseltech/goodversion/visualtest

I’ve tried a few different online suggestions that offered suggestions but I think I may have put them all in improperly, or accidentally left more than one in.

Polars DataType::Struct using Rust Napi

I am trying to convert Javascript object: { attributes: {a: "b", b: "x", x: 700} } to Polars DataType::Struct using the following Rust napi code:

#![deny(clippy::all)]

#[macro_use]
extern crate napi_derive;
use napi::{Env, JsUnknown, Result};

use polars::datatypes::Field;
use polars::prelude::{AnyValue, CompatLevel, DataType};
use polars_core::utils::arrow::array::{Array, StructArray, Utf8Array};

#[napi]
fn create_struct(env: Env, string: String) -> Result<JsUnknown> {
  let js_string = env.create_string(&string)?;
  let unknown = js_string.into_unknown();

  let fields = vec![
    Field::new("a".into(), DataType::String),
    Field::new("b".into(), DataType::String),
    Field::new("x".into(), DataType::Int32),
  ];

  println!("Fields: {:?}", fields);

  let number_of_fields: i8 = fields.len().try_into().map_err(
    |e| napi::Error::from_reason(format!("the number of `fields` cannot be larger than i8::MAX {e:?}"))
  )?;

  let mut val_vec = Vec::with_capacity(number_of_fields as usize);

  let _inner_val: napi::JsObject = unsafe { unknown.cast() };
  fields.iter().for_each(|fld| {
    // let single_val = inner_val.get::<_, napi::JsUnknown>(&fld.name).unwrap().unwrap();

    let vv = match fld.dtype {
      DataType::String =>
        {
          // Utf8Array::<i32>::from([Some(single_val.coerce_to_string().into_ok())]).boxed()
          Utf8Array::<i32>::from([Some("s")]).boxed()
        },
        _ => Utf8Array::<i32>::from([Some("o")]).boxed()
    };
    val_vec.push(vv);
  });

  println!("number_of_fields: {:?} Val vev: {:?}", number_of_fields, val_vec);

  let dtype = DataType::Struct(fields);
  let arrow_dtype = dtype.to_physical().to_arrow(CompatLevel::newest());

  // let arr = unsafe { &*(val_vec.as_slice() as *const dyn Array as *const StructArray) };

  // let arr = Box::new(StructArray::new(
  //     arrow_dtype,
  //     number_of_fields as usize,
  //     arr,
  //     None,
  // ));
  // let str = AnyValue::Struct(number_of_fields.try_into().unwrap(), &Box::new(&arr), &fields);

  Ok(js_string.into_unknown())
}

But unfortunately I am unable to create AnyValue::Struct object.
Does anyone know the correct syntax? Thx

What components within Visual Studio’s ASP.Net and Web Development Workload are necessary for web development and design in HTML, CSS and JavaScript

I am designing a website using HTML, CSS, and JavaScript and would like to use Visual Studio instead of Notepad because I will be able to organise my files in directories and use the live server to share my code.

I have downloaded the Windows form workload to design and create a website in a similar way to the one I created for coursework at college. I have however changed my mind and decided I would like to use HTML, CSS, and JavaScript to design and create the website instead.

Joi validator validateAsync remove warnings

I have been using Joi library for validation user inputs like this.

const Joi = require('joi');

const schema = Joi.object({
    username: Joi.string()
        .alphanum()
        .min(3)
        .max(30)
        .required()
});

const validationResult = await schema.validateAsync({ username: 'a' }, { abortEarly: false, warnings: true });

This works fine, the problem is later in code I would want to use this validation again.
But the warning messages are still in the local context.

And if I input he { username: ‘ba’} the error message will still display that min length of “a” needs to be 3.

Do you know how can I use the schema object again, and strip the local warnings context.

Trying to check for form errors

I’m using the code below. The script thinks the checkbox is checked. It is not checked.

if (!document.f1.SK_1.checked && document.f1.SK_Number1.value == "") {
alert("Please enter your profile link");
document.f1.SK_Number1.focus();
return false;
}

if (!document.f1.SK_2.checked && document.f1.SK_Number2.value == "") {
alert("Please enter your profile link");
document.f1.SK_Number2.focus();
return false;
}

<input class="selectRadioButtons" type="checkbox" name="SK_1"  value="$provlist[0]" > <BR>
<input class="selectClass" type="text" name="SK_Number1" value="" placeholder="$provlist[0] Profile Link"> 

FFMPEGWASM won’t load version 12 reference error

I’ve written a simple script to load FFMPEGWASM but it gives an error:

Error loading FFmpeg: ReferenceError: Can’t find variable: FFmpeg

Full code is here

<h1>FFmpeg Loading Example</h1>
<p id="message"></p>
<script src="https://cdn.jsdelivr.net/npm/@ffmpeg/[email protected]/dist/umd/ffmpeg.min.js"></script>
<script>
    document.addEventListener("DOMContentLoaded", async () => {
        const message = document.getElementById('message');
        try {
            const ffmpeg = new FFmpeg();
            message.innerText = 'Loading FFmpeg...';
            await ffmpeg.load();
            message.innerText = 'FFmpeg loaded successfully!';
        } catch (error) {
            console.error('Error loading FFmpeg:', error);
            message.innerText = 'Error loading FFmpeg.';
        }
    });
</script>