Material UI X Date Picker – Callback when user clicks day in calendar select

I am using the DateTimePicker in material ui, v5 (for both MUI itself and MuiX, which I know is 1 major version behind). I need to be able to hook into the callback that is fired when the user clicks a day in the calendar select:

enter image description here

While the DateTimePicker sports an onChange prop, this is fired when the user changes the date via the calendar UI, or via the text input. I need a way to capture when the user has clicked on the date buttons in the calendar view. The goal is that they should be able to select the day, and when they do, the hour should automatically be set to 00:00.

My thoughts are to capture the onClick handler of the day buttons, and within it, get the new date value, adjust the hours/minutes, and then set the state to that adjusted date. I had dug through their documentation, but there doesn’t seem to be a way to capture this. If the onChange prop had some type of reason or origin property that helped me determine where the change came from (text input vs calendar select), this would also help. Here’s a quick code sample:

 <DateTimePicker
  inputFormat="MM/dd/yyyy HH:mm"
  value={date}
  renderInput={params => (
    <TextField {...params} />
  )}
  onChange={e => {
    // fires when user types, or uses picker
    setDate(e);
  }}
  // I really only want a day picker, but need to 
  // use DateTimePicker to enable hours in the text input
  views={["day"]} 
  components={{
    ActionBar: ({ onAccept }: PickersActionBarProps) => (
      <Button
        onClick={() => {
          setDate(default);
          onAccept();
        }}
      >
        Reset to Default
      </Button>
    )
  }}
/>

Is there a way to capture just the onClick handler of the day buttons here, with the new date value?

eslint import/order: How can I separate “.styles” imports into a last group?

I’m trying to auto sort my imports. I want to separate into a last group the imports from the sibling file ending in /styles. My objective is to have 3 separate groups:

  1. External – third party libraries

  2. All internal files that do not end in .styles

  3. files ended in .styles

Expected:

import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useTheme } from '@emotion/react';

import { ROUTES } from 'features/common/routes';
import { Text } from 'features/common/components/Text';

import { NotFoundContainer, CustomButton } from './NotFound.styles';

How it’s formatted:

import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useTheme } from '@emotion/react';

import { ROUTES } from 'features/common/routes';
import { Text } from 'features/common/components/Text';
import { NotFoundContainer, CustomButton } from './NotFound.styles';

eslint config:

 "import/order": [
      "error",
      {
        "newlines-between": "always",
        "groups": [
          "external",
          ["builtin", "index", "internal", "sibling", "parent"]
        ],
        "pathGroups": [
          {
            "pattern": "@(react*)",
            "group": "external"
          },
          {
            "pattern": "assets/**",
            "group": "internal"
          },
          {
            "pattern": "features/**",
            "group": "internal"
          },
          {
            "pattern": "**/**.styles**",
            "group": "sibling",
            "position": "after"
          }
        ],
        "pathGroupsExcludedImportTypes": ["react"],
        "distinctGroup": false
      }
    ],

Thank you.

I expect the imports to be formatted as described. I tried different eslint configs, with distinctGroups true or false.

File upload Chrome Extension

I want a Chrome extension that prompts the user to upload a file and save it local chrome storage (unless previously uploaded):

chrome.storage.local.set(...)

Then upload that file to the following element on a webpage:

<input id=”kat-file-attachment” type=”file”
aria-labelledby=”select-file” title=”” accept=”image/jpg, image/jpeg,
image/png, application/pdf,
application/vnd.openxmlformats-officedocument.wordprocessingml.document,
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,
text/plain” multiple=””

Node async issue with .on function

I’m having an issue with getting the correct value returned with an async function. Here’s the code . I’m getting the signedUrls after uploading an image and that works correctly, but it is getting to that line too late after the return. The value I want to return is “signedUrls[0]” but right now it is returning something different. I’m not sure what I’m missing to get it to return the correct value. Thanks so much!

var uploadedUrl = response.data.pipe(writeStream)
      .on('finish', async () => {
           console.log('Successfully uploaded image: ');
              
           signedUrls = await file.getSignedUrl({
                action: 'read',
                expires: '03-09-2491'
           });
           console.log("signedUrls: ",signedUrls);
           return signedUrls[0];
      })
      .on('error', () => {
           console.log('Error uploading image');
           return "";
       });
console.log("uploadedURL: ",uploadedUrl);

What if setState is used to fetch API?

I was experimenting with react. and used setState as shown below.

import {useState} from 'react';
export default function App() {
  const [state,setState]=useState([]);

  const fetchApi= async()=>{
    return fetch('https://jsonplaceholder.typicode.com/posts')
                .then(response=>response.json())
                .then(data=>{console.log(data); return data})
                .catch(err=>console.log(err))
  }
  setState(fetchApi());
  return (
    <div>
    </div>
  );
}

In above code, setState is called again and again(infinitely). Can you please provide some explanation what exactly is happening behind the scene?

I know this is not the way of making an API call. One should always use useEffect to fetchdata and set the state accordingly. But I am curious about this one.

getStaticProps TypeError with Nextjs 13.4 TypeScript: Cannot read properties of undefined (reading ‘map’)

hello, I just started learning typescript and I wanted to return users names with a simple fetch operation, I came to this part by researching, but this error is constantly coming up.
TypeError: Cannot read properties of undefined (reading ‘map’)
40 | {repo.map((user: Repo) => (
I think there is a version mismatch with typescript, but I couldn’t. My codes that I got in the comment line are working. can you help me?

'use client'
import React, { useEffect, useState } from 'react';
import Slider from '../components/Project/Slider';
import axios from 'axios';
import type { InferGetStaticPropsType, GetStaticProps } from 'next'
interface Repo {
  id: number;
  name: string;
}
export const getStaticProps: GetStaticProps = async (context) => {
  const res = await fetch('https://jsonplaceholder.typicode.com/users')
  const repo: Repo[] = await res.json()
  console.log(repo)
  return { props: { repo } }
}
export default function Page ({repo}: InferGetStaticPropsType<typeof getStaticProps>) {

  // const [users, setUsers] = useState<User[]>([]);
  // const [loading, setLoading] = useState(true);

  // useEffect(() => {
  //   const fetchUsers = async () => {
  //     try {
  //       const response = await axios.get('https://jsonplaceholder.typicode.com/users');
  //       setUsers(response.data);
  //       setLoading(false);
  //     } catch (error) {
  //       console.error('Error fetching data:', error);
  //       setLoading(false);
  //     }
  //   };

  //   fetchUsers();
  // }, []);

  return (
    <>
      <Slider />
      <div>
        <h1>User List</h1>
        <ul>
          {repo.map((user: Repo) => (
            <li key={user.id}>
              {user.id} - {user.name}
            </li>
          ))}
        </ul>
      </div>
     
    </>
  );
};

How to add a border to the selected Image in ImageList of the MaterialUI component?

I have displayed the images in a grid using the and components of MaterialUI. I want another functionality that when a particular image is selected/clicked on, from the displayed Image grid, i need a border to be displayed around the selected image to indicate to the user which image he has selected. I have tried using useState to store the id. But unable to complete the full code, on how to add the CSS. Need help as using MUI for the first time.
I have add the code below.

import React, { useState } from 'react';
import { ImageList, ImageListItem, Box } from '@mui/material';

export const ImageGrid = () => {
    const [selectedImage, setSelectedImage] = useState("");
    const handleClick = (id: string) => {
        console.log(id);
        console.log('Image clicked');
        setSelectedImage(id);
      };
  return (
    <div>
        <div>
            Image Grid
        </div>
        <ImageList sx={{ width: 500, height: 500 }} cols={3} rowHeight={164} gap={10}>
        {itemData.map((item) => (
            <ImageListItem key={item.img}>
            <img
                src={item.img}
                srcSet={item.img}
                alt={item.title}
                loading="lazy"
                onClick={() => handleClick(item.title)}
            />
            </ImageListItem>
        ))}
        </ImageList>
    </div>
  )
}

const itemData = [
    {
      img: 'https://images.unsplash.com/photo-1551963831-b3b1ca40c98e',
      title: 'Breakfast',
    },
    {
      img: 'https://images.unsplash.com/photo-1551782450-a2132b4ba21d',
      title: 'Burger',
    },
    {
      img: 'https://images.unsplash.com/photo-1522770179533-24471fcdba45',
      title: 'Camera',
    },
    {
      img: 'https://images.unsplash.com/photo-1444418776041-9c7e33cc5a9c',
      title: 'Coffee',
    },
    {
      img: 'https://images.unsplash.com/photo-1533827432537-70133748f5c8',
      title: 'Hats',
    },
    {
      img: 'https://images.unsplash.com/photo-1558642452-9d2a7deb7f62',
      title: 'Honey',
    },
    {
      img: 'https://images.unsplash.com/photo-1516802273409-68526ee1bdd6',
      title: 'Basketball',
    },
    {
      img: 'https://images.unsplash.com/photo-1518756131217-31eb79b20e8f',
      title: 'Fern',
    },
    {
      img: 'https://images.unsplash.com/photo-1597645587822-e99fa5d45d25',
      title: 'Mushrooms',
    },
    {
      img: 'https://images.unsplash.com/photo-1567306301408-9b74779a11af',
      title: 'Tomato basil',
    },
    {
      img: 'https://images.unsplash.com/photo-1471357674240-e1a485acb3e1',
      title: 'Sea star',
    },
    {
      img: 'https://images.unsplash.com/photo-1589118949245-7d38baf380d6',
      title: 'Bike',
    },
  ];

Multi-Dimensional Array from two Arrays where unique values match

I am trying to create my first API using Node.js (also a first). I have two arrays, “rooms” and “room_availability” I would like to add all “room_availability” to “rooms” where the room code matches. If there I didn’t provide enough code below to help, please let me know, but I think this should do it.

rooms Array:

[
  {
    "id": 61,
    "resort": "Boardwalk Villas",
    "room": "Deluxe Studio",
    "view": "Standard View",
    "roomcat": "studio",
    "roomcode": "ZA",
    "sleeps": 5,
    "sqfoot": "359",
    "description": "Views of Resort Grounds or Parking Area",
    "bedding": "1 queen-size bed, 1 full-size sleeper sofa, 1 single pull-down bed",
    "resort_link": "../boardwalk",
    "layout_img": "../images/checkavail-imgs/room_layout/bwv/bwv-studio.jpg",
    "room_img": "../images/checkavail-imgs/room_image/bwv/bwv-studio-standard.jpg",
    "roomimg_thumb": "../images/checkavail-imgs/room_thumb/bwv/bwv-studio-standard-thumb.jpg"
  },
  {
    "id": 62,
    "resort": "Boardwalk Villas",
    "room": "Deluxe Studio",
    "view": "Boardwalk View",
    "roomcat": "studio",
    "roomcode": "SZ",
    "sleeps": 5,
    "sqfoot": "359",
    "description": "Views of Boardwalk",
    "bedding": "1 queen-size bed, 1 full-size sleeper sofa, 1 single pull-down bed",
    "resort_link": "../boardwalk",
    "layout_img": "../images/checkavail-imgs/room_layout/bwv/bwv-studio.jpg",
    "room_img": "../images/checkavail-imgs/room_image/bwv/bwv-studio-boardwalk.jpg",
    "roomimg_thumb": "../images/checkavail-imgs/room_thumb/bwv/bwv-studio-boardwalk-thumb.jpg"
  },
  {
    "id": 63,
    "resort": "Boardwalk Villas",
    "room": "Deluxe Studio",
    "view": "Garden/Pool View",
    "roomcat": "studio",
    "roomcode": "AZ",
    "sleeps": 5,
    "sqfoot": "359",
    "description": "View of Pool, Water or Garden Areas",
    "bedding": "1 queen-size bed, 1 full-size sleeper sofa, 1 single pull-down bed",
    "resort_link": "../boardwalk",
    "layout_img": "../images/checkavail-imgs/room_layout/bwv/bwv-studio.jpg",
    "room_img": "../images/checkavail-imgs/room_image/bwv/bwv-studio-gardenpool.jpg",
    "roomimg_thumb": "../images/checkavail-imgs/room_thumb/bwv/bwv-studio-gardenpool-thumb.jpg"
  },
  {
    "id": 64,
    "resort": "Boardwalk Villas",
    "room": "1-Bedroom Villa",
    "view": "Standard View",
    "roomcat": "onebed",
    "roomcode": "ZB",
    "sleeps": 5,
    "sqfoot": "712",
    "description": "Views of Resort Grounds or Parking Area",
    "bedding": "1 king-size bed, 1 queen-size sleeper sofa - NO ADDITIONAL BEDDING",
    "resort_link": "../boardwalk",
    "layout_img": "../images/checkavail-imgs/room_layout/bwv/bwv-1br.jpg",
    "room_img": "../images/checkavail-imgs/room_image/bwv/bwv-1br-standard.jpg",
    "roomimg_thumb": "../images/checkavail-imgs/room_thumb/bwv/bwv-1br-standard-thumb.jpg"
  },
  {
    "id": 65,
    "resort": "Boardwalk Villas",
    "room": "1-Bedroom Villa",
    "view": "Boardwalk View",
    "roomcat": "onebed",
    "roomcode": "OZ",
    "sleeps": 5,
    "sqfoot": "712",
    "description": "Views of Boardwalk",
    "bedding": "1 king-size bed, 1 queen-size sleeper sofa - NO ADDITIONAL BEDDING",
    "resort_link": "../boardwalk",
    "layout_img": "../images/checkavail-imgs/room_layout/bwv/bwv-1br.jpg",
    "room_img": "../images/checkavail-imgs/room_image/bwv/bwv-1br-boardwalk.jpg",
    "roomimg_thumb": "../images/checkavail-imgs/room_thumb/bwv/bwv-1br-boardwalk-thumb.jpg"
  },
  {
    "id": 66,
    "resort": "Boardwalk Villas",
    "room": "1-Bedroom Villa",
    "view": "Garden/Pool View",
    "roomcat": "onebed",
    "roomcode": "BZ",
    "sleeps": 5,
    "sqfoot": "712",
    "description": "View of Pool, Water or Garden Areas",
    "bedding": "1 king-size bed, 1 queen-size sleeper sofa - NO ADDITIONAL BEDDING",
    "resort_link": "../boardwalk",
    "layout_img": "../images/checkavail-imgs/room_layout/bwv/bwv-1br.jpg",
    "room_img": "../images/checkavail-imgs/room_image/bwv/bwv-1br-gardenpool.jpg",
    "roomimg_thumb": "../images/checkavail-imgs/room_thumb/bwv/bwv-1br-gardenpool-thumb.jpg"
  },
  {
    "id": 67,
    "resort": "Boardwalk Villas",
    "room": "2-Bedroom Lock-Off Villa",
    "view": "Standard View",
    "roomcat": "twobed",
    "roomcode": "ZL",
    "sleeps": 9,
    "sqfoot": "1,072",
    "description": "Views of Resort Grounds or Parking Area",
    "bedding": "1 king-size bed, 1 queen-size bed, 1 full-size sleeper sofa, 1 queen-size sleeper sofa, 1 single pull-down bed",
    "resort_link": "../boardwalk",
    "layout_img": "../images/checkavail-imgs/room_layout/bwv/bwv-2br-lo.jpg",
    "room_img": "../images/checkavail-imgs/room_image/bwv/bwv-2br-lo-standard.jpg",
    "roomimg_thumb": "../images/checkavail-imgs/room_thumb/bwv/bwv-2br-lo-standard-thumb.jpg"
  },
  {
    "id": 68,
    "resort": "Boardwalk Villas",
    "room": "2-Bedroom Lock-Off Villa",
    "view": "Boardwalk View",
    "roomcat": "twobed",
    "roomcode": "TZ",
    "sleeps": 9,
    "sqfoot": "1,072",
    "description": "Views of Boardwalk",
    "bedding": "1 king-size bed, 1 queen-size bed, 1 full-size sleeper sofa, 1 queen-size sleeper sofa, 1 single pull-down bed",
    "resort_link": "../boardwalk",
    "layout_img": "../images/checkavail-imgs/room_layout/bwv/bwv-2br-lo.jpg",
    "room_img": "../images/checkavail-imgs/room_image/bwv/bwv-2br-lo-boardwalk.jpg",
    "roomimg_thumb": "../images/checkavail-imgs/room_thumb/bwv/bwv-2br-lo-boardwalk-thumb.jpg"
  },
  {
    "id": 69,
    "resort": "Boardwalk Villas",
    "room": "2-Bedroom Lock-Off Villa",
    "view": "Garden/Pool View",
    "roomcat": "twobed",
    "roomcode": "LZ",
    "sleeps": 9,
    "sqfoot": "1,072",
    "description": "View of Pool, Water or Garden Areas",
    "bedding": "1 king-size bed, 1 queen-size bed, 1 full-size sleeper sofa, 1 queen-size sleeper sofa, 1 single pull-down bed",
    "resort_link": "../boardwalk",
    "layout_img": "../images/checkavail-imgs/room_layout/bwv/bwv-2br-lo.jpg",
    "room_img": "../images/checkavail-imgs/room_image/bwv/bwv-2br-lo-gardenpool.jpg",
    "roomimg_thumb": "../images/checkavail-imgs/room_thumb/bwv/bwv-2br-lo-gardenpool-thumb.jpg"
  },
  {
    "id": 70,
    "resort": "Boardwalk Villas",
    "room": "3-Bedroom Grand Villa",
    "view": "Boardwalk View",
    "roomcat": "threebed",
    "roomcode": "DZ",
    "sleeps": 12,
    "sqfoot": "2,142",
    "description": "Views of Boardwalk",
    "bedding": "1 king-size bed, 4 queen-size beds, 1 queen-size sleeper sofa",
    "resort_link": "../boardwalk",
    "layout_img": "../images/checkavail-imgs/room_layout/bwv/bwv-3br.jpg",
    "room_img": "../images/checkavail-imgs/room_image/bwv/bwv-3br-boardwalk.jpg",
    "roomimg_thumb": "../images/checkavail-imgs/room_thumb/bwv/bwv-3br-boardwalk-thumb.jpg"
  }
]

room_availability Array:

[
  {
    "resort": "BWALK",
    "room": "AZ",
    "staydate": "2023-09-05T04:00:00.000Z",
    "available": 0,
    "points": 14
  },
  {
    "resort": "BWALK",
    "room": "AZ",
    "staydate": "2023-09-06T04:00:00.000Z",
    "available": 0,
    "points": 14
  },
  {
    "resort": "BWALK",
    "room": "AZ",
    "staydate": "2023-09-07T04:00:00.000Z",
    "available": 0,
    "points": 14
  },
  {
    "resort": "BWALK",
    "room": "AZ",
    "staydate": "2023-09-08T04:00:00.000Z",
    "available": 0,
    "points": 16
  },
  {
    "resort": "BWALK",
    "room": "BZ",
    "staydate": "2023-09-05T04:00:00.000Z",
    "available": 0,
    "points": 26
  },
  {
    "resort": "BWALK",
    "room": "BZ",
    "staydate": "2023-09-06T04:00:00.000Z",
    "available": 1,
    "points": 26
  },
  {
    "resort": "BWALK",
    "room": "BZ",
    "staydate": "2023-09-07T04:00:00.000Z",
    "available": 0,
    "points": 26
  },
  {
    "resort": "BWALK",
    "room": "BZ",
    "staydate": "2023-09-08T04:00:00.000Z",
    "available": 0,
    "points": 29
  },
  {
    "resort": "BWALK",
    "room": "DZ",
    "staydate": "2023-09-05T04:00:00.000Z",
    "available": 1,
    "points": 76
  },
  {
    "resort": "BWALK",
    "room": "DZ",
    "staydate": "2023-09-06T04:00:00.000Z",
    "available": 0,
    "points": 76
  },
  {
    "resort": "BWALK",
    "room": "DZ",
    "staydate": "2023-09-07T04:00:00.000Z",
    "available": 1,
    "points": 76
  },
  {
    "resort": "BWALK",
    "room": "DZ",
    "staydate": "2023-09-08T04:00:00.000Z",
    "available": 1,
    "points": 88
  },
  {
    "resort": "BWALK",
    "room": "LZ",
    "staydate": "2023-09-05T04:00:00.000Z",
    "available": 0,
    "points": 35
  },
  {
    "resort": "BWALK",
    "room": "LZ",
    "staydate": "2023-09-06T04:00:00.000Z",
    "available": 0,
    "points": 35
  },
  {
    "resort": "BWALK",
    "room": "LZ",
    "staydate": "2023-09-07T04:00:00.000Z",
    "available": 0,
    "points": 35
  },
  {
    "resort": "BWALK",
    "room": "LZ",
    "staydate": "2023-09-08T04:00:00.000Z",
    "available": 0,
    "points": 40
  },
  {
    "resort": "BWALK",
    "room": "OZ",
    "staydate": "2023-09-05T04:00:00.000Z",
    "available": 0,
    "points": 26
  },
  {
    "resort": "BWALK",
    "room": "OZ",
    "staydate": "2023-09-06T04:00:00.000Z",
    "available": 0,
    "points": 26
  },
  {
    "resort": "BWALK",
    "room": "OZ",
    "staydate": "2023-09-07T04:00:00.000Z",
    "available": 0,
    "points": 26
  },
  {
    "resort": "BWALK",
    "room": "OZ",
    "staydate": "2023-09-08T04:00:00.000Z",
    "available": 0,
    "points": 29
  },
  {
    "resort": "BWALK",
    "room": "SZ",
    "staydate": "2023-09-05T04:00:00.000Z",
    "available": 0,
    "points": 14
  },
  {
    "resort": "BWALK",
    "room": "SZ",
    "staydate": "2023-09-06T04:00:00.000Z",
    "available": 0,
    "points": 14
  },
  {
    "resort": "BWALK",
    "room": "SZ",
    "staydate": "2023-09-07T04:00:00.000Z",
    "available": 0,
    "points": 14
  },
  {
    "resort": "BWALK",
    "room": "SZ",
    "staydate": "2023-09-08T04:00:00.000Z",
    "available": 0,
    "points": 16
  },
  {
    "resort": "BWALK",
    "room": "TZ",
    "staydate": "2023-09-05T04:00:00.000Z",
    "available": 0,
    "points": 35
  },
  {
    "resort": "BWALK",
    "room": "TZ",
    "staydate": "2023-09-06T04:00:00.000Z",
    "available": 0,
    "points": 35
  },
  {
    "resort": "BWALK",
    "room": "TZ",
    "staydate": "2023-09-07T04:00:00.000Z",
    "available": 0,
    "points": 35
  },
  {
    "resort": "BWALK",
    "room": "TZ",
    "staydate": "2023-09-08T04:00:00.000Z",
    "available": 0,
    "points": 40
  },
  {
    "resort": "BWALK",
    "room": "ZA",
    "staydate": "2023-09-05T04:00:00.000Z",
    "available": 0,
    "points": 9
  },
  {
    "resort": "BWALK",
    "room": "ZA",
    "staydate": "2023-09-06T04:00:00.000Z",
    "available": 0,
    "points": 9
  },
  {
    "resort": "BWALK",
    "room": "ZA",
    "staydate": "2023-09-07T04:00:00.000Z",
    "available": 0,
    "points": 9
  },
  {
    "resort": "BWALK",
    "room": "ZA",
    "staydate": "2023-09-08T04:00:00.000Z",
    "available": 0,
    "points": 13
  },
  {
    "resort": "BWALK",
    "room": "ZB",
    "staydate": "2023-09-05T04:00:00.000Z",
    "available": 0,
    "points": 19
  },
  {
    "resort": "BWALK",
    "room": "ZB",
    "staydate": "2023-09-06T04:00:00.000Z",
    "available": 0,
    "points": 19
  },
  {
    "resort": "BWALK",
    "room": "ZB",
    "staydate": "2023-09-07T04:00:00.000Z",
    "available": 0,
    "points": 19
  },
  {
    "resort": "BWALK",
    "room": "ZB",
    "staydate": "2023-09-08T04:00:00.000Z",
    "available": 0,
    "points": 27
  },
  {
    "resort": "BWALK",
    "room": "ZL",
    "staydate": "2023-09-05T04:00:00.000Z",
    "available": 0,
    "points": 29
  },
  {
    "resort": "BWALK",
    "room": "ZL",
    "staydate": "2023-09-06T04:00:00.000Z",
    "available": 0,
    "points": 29
  },
  {
    "resort": "BWALK",
    "room": "ZL",
    "staydate": "2023-09-07T04:00:00.000Z",
    "available": 0,
    "points": 29
  },
  {
    "resort": "BWALK",
    "room": "ZL",
    "staydate": "2023-09-08T04:00:00.000Z",
    "available": 0,
    "points": 35
  }
]

My Javascript (what I have tried):

const app = express()
const PORT = process.env.PORT

app.get("/resort-info/rooms", async (req, res) => {
    const rooms = await getRooms()
    res.send(rooms);
})

app.get("/resort-info/room/:roomcode", async (req, res) => {
    const roomcode = req.params.roomcode
    const room = await getRoom(roomcode)
    res.send(room);
})

app.get("/resort-info/resort/:resort", async (req, res) => {
    const resort = req.params.resort
    const resort_rooms = await getRoomsByResort(resort)
    res.send(resort_rooms);
})

app.get("/resort-info/room-availability/start/:start/end/:end", async (req, res) => {
    const rooms = await getRooms()
    const start = req.params.start
    const end = req.params.end
    const room_availability = await getRoomAvailability(start, end)
    
    let combined = rooms.map(item => ({ ...item,
      dates: room_availability.filter(f => f.roomcode == item.roomcode)
    }));
    
    
    //res.send(room_availability);
    //res.send(rooms);
    res.send(combined);
})

Current results:

[
  {
    "id": 61,
    "resort": "Boardwalk Villas",
    "room": "Deluxe Studio",
    "view": "Standard View",
    "roomcat": "studio",
    "roomcode": "ZA",
    "sleeps": 5,
    "sqfoot": "359",
    "description": "Views of Resort Grounds or Parking Area",
    "bedding": "1 queen-size bed, 1 full-size sleeper sofa, 1 single pull-down bed",
    "resort_link": "../boardwalk",
    "layout_img": "../images/checkavail-imgs/room_layout/bwv/bwv-studio.jpg",
    "room_img": "../images/checkavail-imgs/room_image/bwv/bwv-studio-standard.jpg",
    "roomimg_thumb": "../images/checkavail-imgs/room_thumb/bwv/bwv-studio-standard-thumb.jpg",
    "dates": []
  },
  {
    "id": 62,
    "resort": "Boardwalk Villas",
    "room": "Deluxe Studio",
    "view": "Boardwalk View",
    "roomcat": "studio",
    "roomcode": "SZ",
    "sleeps": 5,
    "sqfoot": "359",
    "description": "Views of Boardwalk",
    "bedding": "1 queen-size bed, 1 full-size sleeper sofa, 1 single pull-down bed",
    "resort_link": "../boardwalk",
    "layout_img": "../images/checkavail-imgs/room_layout/bwv/bwv-studio.jpg",
    "room_img": "../images/checkavail-imgs/room_image/bwv/bwv-studio-boardwalk.jpg",
    "roomimg_thumb": "../images/checkavail-imgs/room_thumb/bwv/bwv-studio-boardwalk-thumb.jpg",
    "dates": []
  }
]

Desired results:

[
  {
    "id": 61,
    "resort": "Boardwalk Villas",
    "room": "Deluxe Studio",
    "view": "Standard View",
    "roomcat": "studio",
    "roomcode": "ZA",
    "sleeps": 5,
    "sqfoot": "359",
    "description": "Views of Resort Grounds or Parking Area",
    "bedding": "1 queen-size bed, 1 full-size sleeper sofa, 1 single pull-down bed",
    "resort_link": "../boardwalk",
    "layout_img": "../images/checkavail-imgs/room_layout/bwv/bwv-studio.jpg",
    "room_img": "../images/checkavail-imgs/room_image/bwv/bwv-studio-standard.jpg",
    "roomimg_thumb": "../images/checkavail-imgs/room_thumb/bwv/bwv-studio-standard-thumb.jpg",
    "dates": [
      {
        "resort": "BWALK",
        "room": "ZA",
        "staydate": "2023-09-05T04:00:00.000Z",
        "available": 0,
        "points": 9
      },
      {
        "resort": "BWALK",
        "room": "ZA",
        "staydate": "2023-09-06T04:00:00.000Z",
        "available": 0,
        "points": 9
      },
      {
        "resort": "BWALK",
        "room": "ZA",
        "staydate": "2023-09-07T04:00:00.000Z",
        "available": 0,
        "points": 9
      },
      {
        "resort": "BWALK",
        "room": "ZA",
        "staydate": "2023-09-08T04:00:00.000Z",
        "available": 0,
        "points": 13
      }
    ]
  },
  {
    "id": 62,
    "resort": "Boardwalk Villas",
    "room": "Deluxe Studio",
    "view": "Boardwalk View",
    "roomcat": "studio",
    "roomcode": "SZ",
    "sleeps": 5,
    "sqfoot": "359",
    "description": "Views of Boardwalk",
    "bedding": "1 queen-size bed, 1 full-size sleeper sofa, 1 single pull-down bed",
    "resort_link": "../boardwalk",
    "layout_img": "../images/checkavail-imgs/room_layout/bwv/bwv-studio.jpg",
    "room_img": "../images/checkavail-imgs/room_image/bwv/bwv-studio-boardwalk.jpg",
    "roomimg_thumb": "../images/checkavail-imgs/room_thumb/bwv/bwv-studio-boardwalk-thumb.jpg",
    "dates": [
      {
        "resort": "BWALK",
        "room": "SZ",
        "staydate": "2023-09-05T04:00:00.000Z",
        "available": 0,
        "points": 14
      },
      {
        "resort": "BWALK",
        "room": "SZ",
        "staydate": "2023-09-06T04:00:00.000Z",
        "available": 0,
        "points": 14
      },
      {
        "resort": "BWALK",
        "room": "SZ",
        "staydate": "2023-09-07T04:00:00.000Z",
        "available": 0,
        "points": 14
      },
      {
        "resort": "BWALK",
        "room": "SZ",
        "staydate": "2023-09-08T04:00:00.000Z",
        "available": 0,
        "points": 16
      }
    ]
  }
]

How do I make two series have different colors in amCharts

const createSeries = (data, color) => {
      series = am5xy.SmoothedXLineSeries.new(root, settings);
      series.set("stroke", color);
      series.bullets.push(() =>
        am5.Bullet.new(root, {
          locationY: 0,
          sprite: am5.Circle.new(root, {
            radius: 4,
            stroke: color,
            strokeWidth: 2,
            fill: am5.Color.brighten(color, -0.3),
          }),
        })
      );
      series.data.setAll(data);

      chart.series.push(series);
    };

Here is the function I use to populate the data. I want multiple series, each with their own color. However, when I set a color (set “stroke”) it just sets it for all the series. How do I set the stroke of each series?

Implementing AJAX Requests in Django and JavaScript: Issue with Data Retrieval

I’m currently working on a web application using Django and JavaScript, and I’m facing an issue with implementing AJAX requests. I hope someone can assist me in resolving this problem.

Here’s the scenario:
I have a Django backend where I’ve set up an API endpoint to retrieve data from the server. On the client-side, I’m using JavaScript to send AJAX requests to this endpoint and update the webpage dynamically with the received data.

I’ve tried the following steps:

Defined the necessary URL patterns and views in Django to handle the AJAX request.
Created the JavaScript code to send the AJAX request using the Fetch API or XMLHttpRequest.
Configured the server-side code to respond with the required data in JSON format.
However, when I execute the AJAX request and attempt to retrieve the data, I encounter an issue. The request is successful, and I can see the response in the Network tab of the browser’s developer tools. However, I’m having trouble accessing and displaying the data on the webpage.

Here is the sample code I’ve tried:

On the server side (Django):

# views.py
from django.http import JsonResponse

def data_api(request):
    data = {
        'name': 'John Doe',
        'age': 25,
        # ...
    }
    return JsonResponse(data)

On the client side (JavaScript):

// main.js
fetch('/api/data/')
    .then(response => response.json())
    .then(data => {
        // Process the retrieved data and update the webpage
    })
    .catch(error => console.error(error));

I suspect that there might be an issue with how I’m handling the response data on the client-side, but I haven’t been able to identify the exact problem. I’m not sure if it’s a parsing issue or if I’m missing something in the JavaScript code.

Could someone please review the code and point out any potential issues or improvements? Is there anything specific I should consider when handling the response data in JavaScript? Any suggestions or sample code would be highly appreciated.

.NET7 running IIS with Windows Authentication CORS Error

My project is .NET7 running IIS 10 with Windows Authentication enabled. Anonymous authentication is disabled.

I have read the Microsoft documentation extensively.

I’m at a loss for what is required to clear this error:

Access to XMLHttpRequest at ‘http://myAPIurl’ from origin
‘http://localhost:port’ has been blocked by CORS policy: Response to
preflight request doesn’t pass access control check: No
‘Access-Control-Allow-Origin’ header is present on the requested
resource.

I can make the CORS settings work when Windows Authentication is disabled and Anonymous authentication is enabled. But I cannot run my project this way.

How do I get my .NET project to respond without this error? Looking for some help. I’ve tried every combination I can imagine with no success.


launchSettings.json

{
  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:22222/",
      "sslPort": 11111
    }
  }
}

Program.cs

I’ve added this just below where builder is defined:

builder.Services.AddCors();

Then further down I’ve added UseCors between UseRouting and UseAuthorization as the documentation says.

app.UseRouting();

app.UseCors(builder =>
{
    builder.WithOrigins("http://localhost:22222") //I would like to use a list of specific origins
           //.AllowAnyOrigin() //I tried this together with AllowCredentials the project fails to start.
           .AllowAnyMethod()
           .AllowAnyHeader()
           .AllowCredentials();
});

app.UseAuthorization();

Frontend JavaScript is a standard .ajax call.

$.ajax({
    type: 'GET',
    contentType: 'application/json; charset=utf-8', accepts: 'application/json', dataType: 'json', 
    url: urlString,
    success: (data, textStatus, jqXHR) => { /*Do stuff*/ },
    error: (jqXHR, textStatus, errorThrown) => { debugger; }
});

I’ve even tried adding these to the ajax and still receive the error message.

crossDomain: true,
xhrFields: {
    withCredentials: true
},

How to change background on every button of virtual keyboard?

Can you help me with my virtual keyboard? I need to add keydown event with changing background into orange color on each button. in HTML I use buttons with classes .letter and .symbol.

`your text window.addEventListener(‘keydown’, function(event) {
console.log(‘Event’, event)

if(event.keyCode) {
  myButton.style.backgroundColor = 'orange';  
}

})

window.addEventListener(‘keyup’, function(event){
myButton.style.backgroundColor = ‘white’
}) `

     `

Only first block works in a series in Blockly

Description
I tried making my own custom blocks in google blockly and made them generate C++ code. They work, but only when separated and aren’t attached. However, when they are connected together in a series, only the first block generates code and the rest connected to it don’t generate any code at all.
Script:

const toolbox = {
...
}

const cppGenerator = new Blockly.Generator('cppGenerator');

Blockly.Blocks['start_of_file'] = {
    init: function() {
        this.appendDummyInput()
            .appendField("File name:")
            .appendField(new Blockly.FieldTextInput("main"), "filename");
        this.appendDummyInput()
            .appendField("Description: ")
            .appendField(new Blockly.FieldTextInput("The main file"), "description");
        this.setNextStatement(true, null);
        this.setColour(230);
        this.setTooltip("");
        this.setHelpUrl("");
    }
};

Blockly.Blocks['include'] = {
    init: function() {
        this.appendDummyInput()
            .appendField("use the")
            .appendField(new Blockly.FieldTextInput("iostream"), "header")
            .appendField("header");
        this.setPreviousStatement(true, null);
        this.setNextStatement(true, null);
        this.setColour(230);
        this.setTooltip("");
        this.setHelpUrl("");
    }
};

cppGenerator.forBlock['start_of_file'] = function(block, generator) {
    var filename = block.getFieldValue('filename');
    if (filename.slice(-4) != ".cpp") {
        filename += ".cpp"
    }

    var description = block.getFieldValue('description');

    console.log(block)

    return `// ${filename}n// ${description}`;
}

cppGenerator.forBlock['include'] = function(block, generator) {
    var header = block.getFieldValue('header');

    return `#include <${header}>`
}

const workspace = Blockly.inject('blocklyDiv', { toolbox: toolbox });

function updateCode(event) {
    const code = cppGenerator.workspaceToCode(workspace);
    document.getElementById('textarea').value = code;
}
// workspace.addChangeListener(Blockly.Events.disableOrphans);
workspace.addChangeListener(updateCode);

Screenshots:

Current result:
image
Expected Result:
image

Trying to print diamond pattern with spaces in between but ends up skewed

Been trying to print a diamond pattern with spaces in between, however it ends up getting skewed:

function printDiamond(input) {
    if (typeof input === 'number' && input <= 100) {
        //printing columns
        for (var i = 1; i <= input; i++) { //upside pyramid
            for (var b = 1; b <= (input - i); b++) { //prints spaces to position stars
                document.write("&nbsp");
            }
            console.log(document.write, "1")
            for (var a = 1; a <= i; a++) {
                document.write(" ", "*"); //prints space + stars
            }
            document.write("<br>");
        }
        for (var i = input - 1; i >= 1; i--) { //downside pyramid
            for (var b = 1; b <= input - i; b++) { //prints spaces to position stars
                document.write("&nbsp");
            }
            for (var a = 1; a <= i; a++) {
                document.write(" ", "*"); //prints space + stars
            }
            document.write("<br>");
        }
}
printDiamond(5);

Output:
Skewed diamond

I tried fixing by using ” ” instead of “&nbsp” for the positioning so that the spacing will even out.

function printDiamond(input) {

    if (typeof input === 'number' && input <= 100) {
        //printing columns
        for (var i = 1; i <= input; i++) { //upside pyramid
            for (var b = 1; b <= (input - i); b++) { //prints spaces to position stars
                document.write(" ");
            }
            console.log(document.write, "1")
            for (var a = 1; a <= i; a++) {
                document.write(" ", "*"); //prints space + stars
            }
            document.write("<br>");
        }
        for (var i = input - 1; i >= 1; i--) { //downside pyramid
            for (var b = 1; b <= input - i; b++) { //prints spaces to position stars
                document.write(" ");
            }
            for (var a = 1; a <= i; a++) {
                document.write(" ", "*"); //prints space + stars
            }
            document.write("<br>");
        }
}
printDiamond(5);

But the first nested loops (used for positioning) of upper and lower pryramid seems not to be working with ” “.

Output: Stars without positioning

Using number to check spaces: space check

Advices will be much appreciated! Tried a lot of trial and error on this but to no avail..

Mirroring a checkbox and select when weither are selected or clicked

I have a select and a checkbox that I want to work in tandem. The select has four options with values null, Yes, No, and Maybe.

When the select is either Yes or Maybe, the checkbox should be checked.

When the checkbox is unchecked and the select should be set back to null and the .text() set as an empty string.

Everything seems to work except I’m losing the text for the options in the select when I uncheck the checkbox. When I check the options, the selected .text() is empty, and the selected .prop("null") is set to Yes which is now blank.

The snippet shows what’s happening.

$(function() {
    $("#test-1").blur(function() {
        if($("#test-1").val() == "Yes" || $("#test-1").val() == "Maybe" ) {
            $("#result").html("<p>The SELECT is 'YES' and the CHECKBOX is checked. This is intended.<br>Now uncheck CHECKBOX<p>");
            $("#test-2").prop("checked", true);
        } else {
            $("#result").html("<p>The SELECT is 'NO' and the CHECKBOX is unchecked<br>Now SELECT 'YES'<p>");        
            //$("#test-1").text("");
            $("#test-1").prop("null");
            $("#test-2").prop("checked", false);
        } 
    });
});

$(function() {
    $("#test-2").click(function() {
        if($(this).is(":checked")) {
            $("#result").html("Hello World 3")
            $("#test-1 option:selected").text("Yes");
            $("#test-1 option:selected").prop("Yes");
        } else {
            $("#result").html("<p>The CHECKBOX is unchecked and the SELECT is empty, but some SELECT options are missing. Check SELECT.<p>")
            $("#test-1 option:selected").text("");
            $("#test-1 option:selected").prop("null");
        }
    });
});
.test {
    display: flex;
    flex-direction: column;
    width: 50%;
    line-height: 22px;
}
#test-2 {
    border: 12px solid red;
    padding-left: 25px;
}
#result {
    margin-top: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Select <span style="font-weight:600;color:red">YES</span>. Click outside to lose focus.</p>
<div class="test">
    <div>
        Test 1: 
        <select id="test-1" name="test-1">
            <option selected value="null"></option>
            <option value="Yes">Yes</option>
            <option value="No">No</option>
            <option value="Maybe">Maybe</option>
        </select>
    </div>
    <div>
        <br>Test 2:
        <input id="test-2" type="checkbox" name="test-2">
    </div>
</div>

<div id="result">{results appear here}</div>