Custom function in AM5 heatmap for min and max color range with 0 being outside of that

I want a color range for min and max but have 0 be very light grey (or white) to make it stand out and not try to gradient from 0.

I am using a US map from AM5 charts and need the gradients to nicely transition from 1 to 100, preferably not being in a range like 1-10, 11-20, etc. Most often the number will be 20 or less.

The main issue is that the color range they choose (different from the example below) works nicely but a 0 value needs to be outside of that range specification.

The following example does NOT work but shows the intent. Does anyone know how to make this work?

External reference

polygonSeries.set("heatRules", [{
  target: polygonSeries.mapPolygons.template,
  dataField: "value",
  customFunction: function(sprite, min, max, value){
    if (value < 1) {
      sprite.set("fill", am5.color(0xffffff));
    }
    else {
      min: am5.color(0xff621f),
      max: am5.color(0x661f00)
    }
  }  
  key: "fill"
}]);

How to deal with sync and Async function results?

Hello guys i have a function that i need to calc the total duration of media preview. Media array has videos and images. If media is image, just add 5 seconds. If media is video, find it’s duration and add to the total.

Next function should return the totalPreview time. The problem is how to deal with this. If i use .then() to promise , the promise will execute after the main function and the return result will not contain this promise’s data.

 getItemsDuration(mediaArray: any) {
    let previewTime: number = 0;
    for (let media of mediaArray) {
        let isVideo = !!(
            (media.locationFile as any)?.type as string
        )?.includes('video');

        if (isVideo) {
            //Async Returns the promise, I need to add the result to previewTime
            let promise = this.getVideoDurationPromise(media.locationFile);
    
        } else {
            // If it isn't video just add 5 sec duration
            previewTime += 5;
        }
    }

    return   previewTime;
}

Here is the promise. I have the Url of the video and i use ‘loadedmetadata’ event to get it’s duration. Then i return the promise

    private getVideoDurationPromise(file: File): Promise<number> {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => {
            const media = new Audio(reader.result as string);
            media.onloadedmetadata = () => resolve(media.duration);
        };
        reader.readAsDataURL(file);
        reader.onerror = (error) => reject(error);
    });
}

I think that a solution is to transform not video file results to promises and return a promises Array, but it will be a problem to the function that this promises array will end up.

Can someone help me how to deal with that?

Why Am I getting “no such file or directory’ error in my docker container?

I have a docker container that is throwing file path error.
I can see the folder and files when I checked the docker container files but my pdfkit font pointing to that file location has refused to work. It works well on windows local dev environment but fails to work in docker container
On windows, this part works fine: const poppinsRegularFont = (‘./src/assets/fonts/Poppins-Regular.otf’);

// Create a document
const doc = new PDFDocument({margin: 50});

    doc
    .font(poppinsRegularFont)

But on docker, this same path throws this error: Error: ENOENT: no such file or directory, open ‘./src/assets/fonts/Poppins-Regular.otf’Attached image shows the files inside my docker container and the folder that I am targeting is asstes folder

I was able to assess my docker container files using docker exec -t -i backend-bookingapi-1 /bin/sh

Trouble Achieving Responsive Layout with Gridstack Version 10.x

I’m currently working on implementing a grid layout using Gridstack version 10.x in my project. I’m trying to make the layout responsive, where the number of columns and the size of grid items adjust based on different screen widths.

I’ve tried configuring the columnWidth and breakpoints options as suggested in the documentation, but I’m having trouble getting the desired responsive behavior.

Here’s a simplified version of my code:

<div class="container grid-stack-item-content bg-primary" style="height: 600px">
        <div class="row grid-stack">
            <div class="grid-stack-item bg-info p-4 col-6" gs-y="1" gs-w="6">
                <div class="grid-stack-item-content">Item 1</div>
            </div>
            <div class="grid-stack-item bg-warning p-4 col-3" gs-y="2" gs-w="3">
                <div class="grid-stack-item-content">Item 2 wider</div>
            </div>
            <div class="grid-stack-item bg-danger p-4 col-3" gs-y="2" gs-w="3">
                <div class="grid-stack-item-content">Item 3 wider</div>
            </div>
            <div class="grid-stack-item bg-info p-4 col-6" gs-y="1" gs-w="6">
                <div class="grid-stack-item-content">Item 1</div>
            </div>
            <div class="grid-stack-item bg-warning p-4 col-3" gs-y="2" gs-w="3">
                <div class="grid-stack-item-content">Item 2 wider</div>
            </div>
            <div class="grid-stack-item bg-danger p-4 col-3" gs-y="2" gs-w="3">
                <div class="grid-stack-item-content">Item 3 wider</div>
            </div>
        </div>
    </div>
     GridStack.initAll({
            width: 12,
            column: 12,
            cellHeight: "auto", // = 48px
            // sizeToContent: true,
            margin: "10px",
            resizable: false,
            // cellHeight: "auto", // see other possible values (best to do in here)
            // cellHeightThrottle: 100,
            columnOpts: {
                breakpointForWindow: true, // test window vs grid size
                breakpoints: [{
                    w: 400,
                    c: 1,
                }, {
                    w: 600,
                    c: 6,
                }, {
                    w: 850,
                    c: 6,
                }, {
                    w: 1100,
                    c: 8,
                }, ],
            },
            draggable: {
                handle: ".grid-stack-item-content",
                x: true,
                y: true,
            },
        });
    </script>

Detecting state changes when someone starts a screen share – discord bot

I’m trying to create a bot that notifies me whenever someone starts a new stream.

const streamChannelId = 'MY-channel-id';


const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildPresences] });

client.on("ready", () => {
    console.log('Bot is ready');
});



client.on("presenceUpdate", (oldPresence, newPresence) => {

    console.log('oldPresence:', oldPresence);
    console.log('newPresence:', newPresence);

    if (!newPresence.activities) return;
    
    newPresence.activities.forEach(activity => {
        if (activity.type === "STREAMING") {
            const streamChannel = newPresence.guild.channels.cache.get(streamChannelId);
            if (streamChannel) {
                streamChannel.send(`${newPresence.user.tag} started a stream at ${activity.url}.`);
            } else {
                console.log('Stream channel not found.');
            }
        }
    });
});



client.login('my-key')

This works only when I started an Activity this doesn’t work when I start a stream.
From the research I did it should work when a user streams as well but it doesn’t work.

Needless to say my bot has all of the permissions.

Thanks in advance for any kind of help!

TinyMCE 6 resulting in a data:image object over uploading via script provided

Our TinyMCE self hosted script:

const example_image_upload_handler = (blobInfo, progress) => new Promise((resolve, reject) => {
  const xhr = new XMLHttpRequest();
  xhr.withCredentials = false;
  xhr.open('POST', '/p/account/project-post-image-upload');

  xhr.upload.onprogress = (e) => {
    progress(e.loaded / e.total * 100);
  };

  xhr.onload = () => {
    if (xhr.status === 403) {
      reject({ message: 'HTTP Error: ' + xhr.status, remove: true });
      return;
    }

    if (xhr.status < 200 || xhr.status >= 300) {
      reject('HTTP Error: ' + xhr.status);
      return;
    }

    const json = JSON.parse(xhr.responseText);

    if (!json || typeof json.location != 'string') {
      reject('Invalid JSON: ' + xhr.responseText);
      return;
    }

    resolve(json.location);
  };

  xhr.onerror = () => {
    reject('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
  };

  const formData = new FormData();
  formData.append('tinymce_file_upload', blobInfo.blob(), blobInfo.filename());

  xhr.send(formData);
});
  
tinymce.init({
  selector: '.tinymce',
  model: 'dom',
  plugins: 'autoresize image link lists',
  autoresize_bottom_margin: 20,
  skin: 'theme',
  content_css: 'tinymce/skins/content/theme/content.min.css',
  min_height: 300,
  toolbar_sticky: true,
  contextmenu: 'link image paste',
  toolbar: ' undo redo|formatselect | bold italic | alignleft aligncenter alignright alignjustify | outdent indent | image link bullist numlist | hr',
  block_formats: 'Paragraph=p; Header 1=h1; Header 2=h2; Header 3=h3; Header 4=h4; Header 5=h5; Header 6=h6',
  menubar: false,
  media_dimensions: false,
  object_resizing : false,
  image_uploadtab: true,
  images_upload_handler: example_image_upload_handler,
  images_file_types: 'jpeg,jpg,png,gif',
  automatic_uploads: false,
  image_dimensions: false,
  image_class_list: [
    {title: 'Regular', value: 'tinymce_full_width img-fluid'}
  ],
  relative_urls : false,
  document_base_url: "/",
  setup: function(editor) {
    editor.on('init', function () {
      editor.getContainer().style.transition='border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out';
    }).on('focus', function(e) {
        editor.getContainer().style.boxShadow='0 0 0 .2rem rgb(54 97 11 / 25%)';
    }).on('blur', function(e){
        editor.getContainer().style.boxShadow='';
    }).on('keyup', function(e){

    });
  }
});

We have a function that uploads an image to our server, however as of recently, it ignores that script and just uploads a data:image within the src. How do we mitigate this from happening? Am I missing something that’s ignoring the upload script?

TypeError: Cannot destructure property ’email’ of ‘body’ as it is undefined

I am trying to debug it, but it is not resolving. Can anyone help me? I am getting the SyntaxError: Unexpected end of JSON input
I have tried all the possible way but again and again getting either TypeError: Cannot destructure property ’email’ of ‘body’ as it is undefined OR SyntaxError: Unexpected end of JSON input error.

Here’s my /api/send/route.js code:

    import { NextResponse } from "next/server";
    import { Resend } from "resend";
    
    const resend = new Resend(process.env.RESEND_API_KEY);
    const fromEmail = process.env.FROM_EMAIL;
    
    export async function POST(req, _res) {
      const { body } = await req.json();
    
      const { email, subject, message } = body;
      try {
        const data = await resend.emails.send({
          from: fromEmail,
          to: [email],
          subject: subject,
          react: (
            <>
              <h1>{subject}</h1>
<p>Thank you for contancting me!</p>
              <p>new message was submitted:</p>
              <p>{message}</p>
            </>
          ),
        });
    
        return Response.json(data);
      } catch (error) {
        return Response.json({ status: "fail", error });
      }
    }

And here’s my email section. jsx file code:

    /* eslint-disable react/no-unescaped-entities */
    "use client";
import React, { useState } from "react";
import Link from "next/link";
import Image from "next/image";
import GitHubIcon from "../../public/images/github.png";
import LinkedInIcon from "../../public/images/linkedin.png";
import DiscordIcon from "../../public/images/discord.png";
import XIcon from "../../public/images/X.png";

const EmailSection = () => {
  const [emailSumitted, setEmailSubmitted] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    const data = {
      email: e.target.email.value,
      subject: e.target.subject.value,
      message: e.target.message.value,
    };
    const JSONdata = JSON.stringify(data);
    const endpoint = "/api/send";

    // forming the request for sending data to the server
    const options = {
      method: "POST",

      headers: {
        "Content-Type": "application/json",
      },

      body: JSONdata,
    };

    const response = await fetch(endpoint, options);
    const resData = await response.json();
    console.log(resData);

    if (response.status === 200) {
      console.log("Message sent.");
      setEmailSubmitted(true);
    }
  };

  return (
    <section
      id="contact"
      className="grid md:grid-cols-2 my-12 md:my-12 py-24 gap-4 relative"
    >
      {/* <div className='bg-[radial-gradient(ellipse_at_center,_var(--tw-gradient-stops))] from-purple-900 to-transparent rounded-full h-80 w-80 z-0 blur-lg absolute top-3/4 -left-4 transform -translate-x-1/2 -translate-1/2'></div> */}
      <div className="z-1">
        <h5 className="text-xl font-bold text-white my-2">Let's Connect</h5>
        <p className="text-[#ADB7BE] mb-4 max-w-md">
          {" "}
          Whether it's about the latest tech trends, UI/UX design, or just a
friendly conversation, feel free to reach out!
        </p>
        <div className="socials flex flex-row gap-2">
          <Link href="https://github.com/DiyaVj">
            <Image src={GitHubIcon} className="w-10" alt="Github Icon" />
          </Link>
          <Link href="https://www.linkedin.com/in/diya-vijay/">
            <Image src={LinkedInIcon} className="w-10" alt="LinkedIn Icon" />
          </Link>
          <Link href="https://linktr.ee/Diyavj">
            <Image src={DiscordIcon} className="w-10" alt="Discord Icon" />
          </Link>
          <Link href="https://twitter.com/DiyaVijay6">
            <Image src={XIcon} className="w-10" alt="X Icon" />
          </Link>
        </div>
      </div>
      <div>
        <form className="flex flex-col" onSubmit={handleSubmit}>
          {/* Email  */}
          <div className="mb-6">
            <label
              htmlFor="email"
              className="text-white block mb-2 text-sm font-medium"
            >
              Your email
            </label>
            <input
              name="email"
              type="email"
              id="email"
              required
              className="bg-[#18191E] border border-[#33353F] placeholder-[#9CA2A9] text-gray-100 text-sm rounded-lg block with full p-2.5"
              placeholder="[email protected]"
            />
          </div>
          {/* Subject  */}
          <div className="mb-6">
            <label
              htmlFor="subject"
              className="text-white block mb-2 text-sm font-medium"
            >
              Subject
            </label>
            <input
              name="subject"
              type="text"
              id="subject"
              required
              className="bg-[#18191E] border border-[#33353F] placeholder-[#9CA2A9] text-gray-100 text-sm rounded-lg block with full p-2.5"
placeholder="Say Hi or anything you would like to..."
            />
          </div>
          {/* message  */}
          <div className="mb-6">
            <label
              htmlFor="message"
              className="text-white block text-sm mb-2 font-medium"
            >
              Message
            </label>
            <textarea
              name="message"
              id="message"
              className="bg-[#18191E] border border-[#33353F] placeholder-[#9CA2A9] text-gray-100 text-sm rounded-lg block with full p-2.5"
placeholder="Let's talk about..."
            />
          </div>
          {/* button  */}
          <button
            type="submit"
className="bg-gradient-to-r from-purple-400 to-purple-700 hover:bg-gradient-to-r hover:from-slate-800 hover:to-slate-700 text-white font-medium py-2.5 px-5 rounded-lg w-full"
          >
            Send Message
          </button>
          {emailSumitted && (
            <p className="text-green-500 text-sm mt-2">
Email sent successfully!
            </p>
          )}
        </form>
      </div>
    </section>
  );
};

export default EmailSection;

JS modules in dev + Git

I want to use pure JS modules on a local dev. We know these modules have to be served by a server and not by local file system, otherwise CORS restrictions will apply in the browser.

So I run a server (node, LAMP/WAMP, python server…) and I have to put my files in the directory designed for that.
How do you manage all that with a Git(lab/hub) versioning management?

In safari for IOS17 audio is broken

I am developing a web site that uses a library that involves audio playback.

This playback is accompanied by an animated canva, and in the IOS17 version in safari, this does not work. The audio is muted and the canva does not animate.

However, in ios16 safari it works perfectly.

I have also tried in safari on MacOs and ipadOs and it works, which makes me see that the problem is with ios 17 safari.

The library in question is this: https://github.com/foobar404/Wave.js/

I don’t think the failure is in the library since it works as I said in all other platforms.

Specifically the code is here: https://github.com/foobar404/wave.js/blob/main/src/index.ts and makes me think that some HTML element is being incompatible.

It is necessary to emphasize that in ios17 it does not work, but it does not appear any error in console.

I would love to get help or know if this is a bug to report it.

How can I add a map to an image view in javafx using GMapsfx and also get the location of a place without getting a null pointer exception

How can I add a map to an image view in javafx using GMapsfx 2.12.0 and also get the location of a place in longitude and latitude and in name of location without getting a null pointer exception in my code at line

 map = new GoogleMap();

.

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import com.lynden.gmapsfx.GoogleMapView;
import com.lynden.gmapsfx.MapComponentInitializedListener;
import com.lynden.gmapsfx.javascript.object.GoogleMap;
import com.lynden.gmapsfx.javascript.object.LatLong;
import com.lynden.gmapsfx.javascript.object.MapOptions;
import com.lynden.gmapsfx.javascript.object.MapTypeIdEnum;
import com.lynden.gmapsfx.javascript.object.Marker;
import com.lynden.gmapsfx.javascript.object.MarkerOptions;
import com.lynden.gmapsfx.GoogleMapView.MapLibraryLoadBridge;
import javafx.scene.Scene;
import javafx.stage.Stage;
import com.lynden.gmapsfx.javascript.JavascriptRuntime;
import com.lynden.gmapsfx.javascript.JavascriptObject;
//import static com.sun.org.apache.xalan.internal.lib.ExsltDynamic.map;
//import static jdk.nashorn.internal.objects.NativeArray.map;
//import static jdk.nashorn.internal.objects.NativeDebug.map;

/**
 *
 * @author
 */
public class SecurityGUIController implements Initializable {
    
    @FXML
    private Label label;
    @FXML
    private RadioButton locationradiobtn;
    @FXML
    private TextField locationtxt;
    @FXML
    private ImageView MapImageView;
    @FXML
    private Button emmergencyButton;
    
    private GoogleMapView mapView;
    
    private GoogleMap map;

@FXML
    private void GetLocation(ActionEvent event) {
        double latposbtn = 0.0, longposbtn = 0.0;
mapView = new GoogleMapView();
        
        map = new GoogleMap();
latposbtn = map.getCenter().getLatitude();
        longposbtn = map.getCenter().getLongitude();
 if (locationradiobtn.isSelected()){
        
        System.out.println(latposbtn);
        //locationtxt.setText("latposbtn, longposbtn");
        
    }    
    }

Infinite Scrolling in Swiggy

I am currently creating Swiggy Clone but I am struck by a place where Swiggy will do infinite scrolling whenever we scroll new restaurants are added every time and in the network tab, an API name update is added which is a Post API. How do you think it should particularly work can anyone tell me?

I have seen so many things but no getting exactly how this is done exactly.

HuePicker bar from react-color is not visible

I am trying to make a react component with color picker using ‘react-color’ library.

The picker works in the sense that i can move the picker’s dot and handleColorChange is triggered (I see it thanks to logs), but the gradient bar is not visible.

My component:

import PropTypes from 'prop-types';
import './AddBoard.css'
import React, { useState } from 'react';
import { HuePicker } from 'react-color';

function AddBoard({ onClose }) {
    const [color, setColor] = useState('#ffffff');

    function handleColorChange(newColor) {
        console.log(newColor);
        setColor(newColor.hex);
    }

    return (
        <>
            <div>
                <p>Board name: </p>
                <input type="text" id="boardName" className="boardNameInput" />
                <HuePicker color={color} onChange={handleColorChange}/>
                <button>Submit!</button> <button onClick={onClose}>Cancel</button>
            </div>
        </>
    )
}

AddBoard.propTypes = {
    onClose: PropTypes.func.isRequired
}

export default AddBoard;

the css file:

.AddBoardPopup {
    border: 5px solid snow;
    background-color: #271a38;
    margin: 0 auto;
    height: 300px;
    width: 300px;
}

trying to change color of square in grid on html canvas but not working and no clue as to why, double checked a hundred times at this point

game of life project in react, trying to change cell color onClick but it just won’t work; I literally have no clue why not. stack overflow seems to want me to be more specific but I literally have no clue what the issue could be; it is referencing my array coordinates just fine(console.log confirmed) but it tells me that theres a type error on the y axis grid[x][y] and I dont know whether the type error is referring to the value at that index or whether it is trying to use the index itself; ive just been staring at it forever and I cant figure it out.

My canvas component(havent begun to split it down just yet; not commented too well yet)

import { useRef, useEffect } from "react";

export default function GameOfLifeCanvas() {
  //! component wide variables
  //! create reference to canvas
  const canvasRef = useRef(null);
  const resolution = 20;
  const width = 400;
  const height = 400;
  const cellTypes = [
    {
      name: "standardCell",
      liveRepresentation: 1,
      color: "",
      behavior: {},
    },
  ];
  //! cellTypeCount is the number of cell types; alive, x, y, z = 4;; + 1 for dead cell
  const cellTypeCount = cellTypes.length + 1;

  //! run when component mounts
  useEffect(() => {
    const columns = width / resolution;
    const rows = height / resolution;
    const canvas = canvasRef.current;
    const context = canvas.getContext("2d");

    let grid = () => {
      //! start with empty array
      const grd = [];
      //! for every row
      for (let i = 0; i < rows; i++) {
        const row = [];
        //! for every column
        for (let ii = 0; ii < columns; ii++) {
          //! push 0 to row
          row.push(Math.floor(Math.random() * cellTypeCount));
        }
        //! push row to columns for every column
        grd.push(row);
      }
      return grd;
    };

    function mouseClick(e) {
      let mouseX, mouseY;

      if (e.offsetX) {
        mouseX = e.offsetX;
        mouseY = e.offsetY;
      } else if (e.layerX) {
        mouseX = e.layerX;
        mouseY = e.layerY;
      }
      let gridX = Math.floor(mouseX / resolution);
      let gridY = Math.floor(mouseY / resolution);
      console.log(gridX, gridY);

      let xy = grid[gridX][gridY];
      if (xy == 0) {
        grid[gridX][gridY] = 1;
        console.log("white");
      } else if (xy === 1) {
        grid[gridX][gridY] = 0;
        console.log("black");
      }

      render(grid);
    }

    canvas.addEventListener("mousedown", mouseClick, false);

    render(grid());
    function render(grid) {
      for (let col = 0; col < grid.length; col++) {
        for (let row = 0; row < grid[col].length; row++) {
          const cell = grid[col][row];

          context.beginPath();
          //   context.rect(
          //     col * resolution,
          //     row * resolution,
          //     resolution,
          //     resolution
          //   );
          //! truthy is black falsy is white
          context.fillStyle = cell ? "black" : "white";
          context.fillRect(
            col * resolution,
            row * resolution,
            resolution,
            resolution
          );
          context.stroke();
        }
      }
      console.log(grid);
    }
  }, []);
  return (
    <>
      <canvas ref={canvasRef} width={width} height={height}></canvas>
    </>
  );
}

I am trying to make javascript bookmark that automatically clicks on the “Add Gift Option” when checking out on Amazon

I am trying to make a bookmark using javascript that automatically clicks the “Add a gift options” and then enters a preset message and sender, and then clicks “Save gift options and continue”. Mainly because I am new to Java and thought this would be a fun little project. It’s proven more difficult than I anticipated. Below is the snipped of code I have tried and also the buttons I am trying to click and the HTML code that identifies them. Any help would be much appreciated.

The button
Amazon’s button code
The popup I want to populate and click enter

Tried the following code among others but it doesn’t seem to do anything.

[Last attempt](https://i.stack.imgur.com/KnF5B.png)