Razorpay’s Blade Design System with Next.js for Server Side Rendering

I am new to Javascript and its frameworks. I am exploring Next.js for my complex website with SEO implications. I want to use Razorpay’s Blade design System for it.

I am not able to use Blade’s component without ‘use client’. So what I understood is that Blade is using some constructs that enforce it to be used on Client Side but I am not sure(as I am beginner). I read that Server Side Rendering is beneficial for SEO and using ‘use client’ I am making my page to render on client side. So I will lose the benefits of Next.

Is there any way that I can use server side rendering with blade?

Script to pull live sports scores [closed]

Hello I need help writing a script that pulls live sports scores and displays them in a program called OBS. I also need help finding were to pull this information and formatting it to fit into OBS the way I would like it to be.

ChatGPT but I just got basic information. Nothing that would actually pull that said information.

Google Maps API – “This API project is not authorized to use this API” (REQUEST_DENIED)

I’m currently working on integrating the Google Maps API into my project and have enabled all required APIs, including:

  • Maps JavaScript API
  • Directions API
  • Geocoding API
  • Places API
  • Distance Matrix API
  • Routes API (including Polyline features)

but the polyline features not working properly as well. even i have enabled every service in google map api. please check the attached image.

other features such as auto suggestion, real time location working perfectly.

it gives this error: Google Maps API – “This API project is not authorized to use this API” (REQUEST_DENIED)

enabled service

I suspect this could be related to API restrictions, billing issues, or something else I may have overlooked.

Has anyone encountered this issue before? Any insights on how to resolve it would be greatly appreciated!

Thank you in advance!

Webpack not exposing all the package.json dependencies in the generated library ( browser code )

I have a webpack config to bundle all the node_modules dependencies mentioned in the package.json file. The following config file generates a library which exposes only the last mentioned in dependency in dependencies list.

const { webpack, ProvidePlugin } = require("webpack");
const { dependencies } = require('./package.json');
const path = require('path');

const provideConfig = {};
Object.keys(dependencies).forEach(dep=>{
    provideConfig[dep] = dep;
});

module.exports = {
   mode: "development",
   target: ['web','es5'],
   entry:{
       vendor: Object.keys(dependencies) // Create a separate entry for each dependency
   },
   output:{
      filename: 'bundle.js',
      path: path.resolve(__dirname, '.'),
      library: 'myLibrary',
      libraryTarget: 'umd'
   },
   plugins: [
      new ProvidePlugin(providePlugin)
   ],
   devtool: 'source-map'
};

I am expecting this to expose the the dependency as,
myLibrary.<dependency_name>

This is only exposing the last dependency in dependencies list of package.json

I am using webpack 5.98

How can I filter data by Query using Prisma?

I’m trying to filter papers dynamically, either using title or using publication_date or department. Or either just a single query. For example this my URL, so it means I must filter name with test that starts from 1999 to 2020.

http://localhost:3000/api/filter-papers?title=test&yearStart=1999&yearEnd=2020&department=CAHS

this is my api.


export async function GET(req: Request, res: NextResponse) {
    try {
        const { searchParams } = new URL(req.url)
        const searchTitle = searchParams.get('title')
        const yearStart = searchParams.get('year_start')
        const yearEnd = searchParams.get('year_end')
        const department = searchParams.get('department')


        const papers = await db.publish_Papers.findMany({
            where: {
                OR: {
                    title: {
                        contains: searchTitle ?? ""
                    },
                    publication_date: {
                        gte: yearStart,
                        lte: yearEnd
                    },
                    department: department
                   
                }
            }
        })

        console.log(papers)

        return NextResponse.json(papers, { status: 200 })
    } catch (error) {
        return NextResponse.json({ error: 'failed to load data' }, { status: 500 })
    }
}

This is my Schema.

model Publish_Papers {
  id                 String   @id @default(uuid())
  title              String
  description        String
  categories         String
  publication_source String
  publication_date   DateTime
  url                String
  createdAt          DateTime @default(now())
  updatedAt          DateTime @updatedAt

  authorId String
  Authors  Authors @relation(fields: [authorId], references: [id])
}

so when I only run findMany without any filter. I get this JSON

data.json

[
 {
        "id": "4b20caba-65cd-4db6-b1e2-ecfe247b7dc4",
        "title": "publish test",
        "description": "http://localhost:3000/admin-resource/new",
        "categories": "CASE",
        "publication_source": "idk",
        "publication_date": "2016-03-10T01:37:21.562Z",
        "url": "http://localhost:3000/admin-resource/new",
        "createdAt": "2025-03-18T01:37:35.054Z",
        "updatedAt": "2025-03-18T01:37:35.054Z",
        "authorId": "d7b32e45-b25a-41b9-bc7b-178991409af0",
    },
  
]

dexie.js show formated results

I’m starting with dexie.js and would like to display the formatted results to the user on the screen, for example…

Console Log

I try in html this result:

Josephone – 21 years

Per – 75 years

Simon – 5 years

Sara – 50 years

I don’t use frameworks, and I would like to format the results using HTML and CSS
I know how to do this with CSS, but I don’t know how to extract this information and display it to the user.

What could be causing “Rendered fewer hooks than expected” in this component?

After adding this conditional statement to fix an error:

if (el.parentNode) {}

I started getting this error:

Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement.

What could be the offending line?

import React, { useRef, useState, useEffect, useCallback } from 'react';
import ReactDOM from 'react-dom';
import { IconFileDescription, IconX, IconEdit } from '@tabler/icons-react';
import { Row } from '@/components/Row';
import { Col } from '@/components/Col';
import { cn } from '@/utils';
import { FileData } from '@/components/FileUpload';

type FilePreviewsProps = {
  files: FileData[];
  onRemoveFile?: (index: number) => void;
  onEditClick?: (index: number) => void;
  multiple?: boolean;
  className?: string;
};

/**
 * Create a portal <div> in document.body, remove on unmount.
 */
function usePortalContainer() {
  const [portalContainer, setPortalContainer] = useState<HTMLDivElement | null>(
    null,
  );

  useEffect(() => {
    const el = document.createElement('div');
    document.body.appendChild(el);
    setPortalContainer(el);

    return () => {
      if (el.parentNode) {
        document.body.removeChild(el);
      }
    };
  }, []);

  return portalContainer;
}

/**
 * RemoveButtonPortal:
 * Places the "X" in the top-right corner of the container via portal,
 * so it won't be clipped by overflow hidden or border radius.
 * We recalc on scroll/resize so it follows the container.
 */
function RemoveButtonPortal({
  index,
  onRemoveFile,
  containerRef,
  hovered,
  multiple,
}: {
  index: number;
  onRemoveFile: (index: number) => void;
  containerRef: React.RefObject<HTMLDivElement>;
  hovered: boolean;
  multiple: boolean;
}) {
  const portalContainer = usePortalContainer();
  const [coords, setCoords] = useState({ top: 0, left: 0 });

  // Tweak these values until it looks perfect for both shapes
  const borderWidth = 1;
  const offsetTop = (multiple ? 4 : 20) + borderWidth;
  const offsetRight = (multiple ? 28 : 20) + borderWidth;

  const updatePosition = useCallback(() => {
    if (!containerRef.current) return;
    const rect = containerRef.current.getBoundingClientRect();

    const top = rect.top + window.scrollY + offsetTop;
    const left = rect.right + window.scrollX - offsetRight;

    setCoords({ top, left });
  }, [containerRef, offsetTop, offsetRight]);

  useEffect(() => {
    updatePosition();
    function handleScrollResize() {
      updatePosition();
    }
    window.addEventListener('scroll', handleScrollResize);
    window.addEventListener('resize', handleScrollResize);

    return () => {
      window.removeEventListener('scroll', handleScrollResize);
      window.removeEventListener('resize', handleScrollResize);
    };
  }, [updatePosition]);

  if (!portalContainer) return null;

  return ReactDOM.createPortal(
    <div
      style={{
        position: 'absolute',
        top: coords.top,
        left: coords.left,
        zIndex: 9999,
        opacity: hovered ? 1 : 0, // fade in/out on hover
        transition: 'opacity 0.2s',
      }}
    >
      <button
        type="button"
        className="rounded-full bg-foreground p-1 text-background shadow hover:shadow-dark"
        onClick={(e) => {
          e.stopPropagation(); // Prevent triggering edit on container
          onRemoveFile(index);
        }}
      >
        <IconX size={16} />
      </button>
    </div>,
    portalContainer,
  );
}

export function FilePreviews({
  files,
  onRemoveFile,
  onEditClick,
  multiple = true,
  className,
}: FilePreviewsProps) {
  // Render file name overlay if multiple
  const renderFilename = (file: FileData) =>
    multiple ? (
      <Row
        align="center"
        alignItems="center"
        className="absolute bottom-0 flex h-7 overflow-hidden border-t border-border p-2 text-xs"
        locked
      >
        <span className="truncate text-ellipsis whitespace-nowrap">
          {file.name}
        </span>
      </Row>
    ) : null;

  /**
   * Overlay:
   * - Just a semi-transparent black background (on hover).
   * - A plain IconEdit in the center (no click action).
   */
  const renderOverlay = () => (
    <div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center bg-black/40 opacity-0 transition-opacity duration-200 group-hover:opacity-100">
      <IconEdit size={40} className="text-background" />
    </div>
  );

  return (
    <div
      className={cn(
        'w-full gap-2 rounded bg-subtle p-3',
        { 'grid grid-cols-4 md:grid-cols-8': multiple },
        { 'flex justify-center': !multiple },
        className,
      )}
    >
      {files.map((file, index) => {
        const containerRef = useRef<HTMLDivElement>(null);
        const [hovered, setHovered] = useState(false);

        return (
          <div
            key={index}
            ref={containerRef}
            className={cn(
              'group relative cursor-pointer overflow-hidden border border-border bg-background',
              {
                // multiple => rectangular style
                'aspect-w-1 aspect-h-1 w-full rounded-md pb-7': multiple,
                // single => circle
                'flex h-32 w-32 items-center justify-center rounded-full':
                  !multiple,
              },
            )}
            onMouseEnter={() => setHovered(true)}
            onMouseLeave={() => setHovered(false)}
            onClick={() => {
              // Clicking anywhere in the container triggers edit (if provided)
              if (onEditClick) onEditClick(index);
            }}
          >
            {/* The "X" is in a portal, so not clipped */}
            {onRemoveFile && (
              <RemoveButtonPortal
                index={index}
                onRemoveFile={onRemoveFile}
                containerRef={containerRef}
                hovered={hovered}
                multiple={multiple}
              />
            )}

            {/* Plain overlay icon */}
            {renderOverlay()}

            {/* Image or fallback icon */}
            {file.url ? (
              multiple ? (
                <div className="relative box-border h-full w-full p-1">
                  <img
                    src={file.url}
                    alt={`Preview ${index + 1}`}
                    className="h-full w-full object-contain"
                  />
                </div>
              ) : (
                <img
                  src={file.url}
                  alt={`Preview ${index + 1}`}
                  className="h-full w-full object-cover"
                />
              )
            ) : (
              <Col
                align="center"
                alignItems="center"
                className={cn('h-full w-full', {
                  'rounded-md': multiple,
                  'rounded-full': !multiple,
                })}
              >
                <IconFileDescription size={60} stroke={1} />
              </Col>
            )}

            {/* Show file name overlay only if multiple */}
            {multiple && renderFilename(file)}
          </div>
        );
      })}
    </div>
  );
}

Unable to resolve “@sentry-internal/replay in react-native app

dependencies


"dependencies": {
    "@expo-google-fonts/roboto": "^0.2.3",
    "@expo/config-plugins": "~9.0.0",
    "@expo/vector-icons": "^14.0.0",
    "@gorhom/bottom-sheet": "^4.4.5",
    "@react-native-async-storage/async-storage": "1.23.1",
    "@react-native-community/datetimepicker": "8.2.0",
    "@react-native-community/netinfo": "11.4.1",
    "@react-navigation/bottom-tabs": "^6.5.7",
    "@react-navigation/native": "^6.1.6",
    "@react-navigation/native-stack": "^6.9.12",
    "@react-navigation/stack": "^6.3.16",
    "@sentry/react-native": "~6.3.0",
    "@xstate/react": "^3.2.1",
    "base32.js": "^0.1.0",
    "big.js": "^5.0.3",
    "bitcoin-address-validation": "^2.1.0",
    "buffer": "^5.2.1",
    "color-alpha": "^1.1.3",
    "country-list": "^2.1.0",
    "crc": "^3.8.0",
    "deprecated-react-native-prop-types": "^4.0.0",
    "dotenv": "^16.0.3",
    "expo": "^52.0.0",
    "expo-application": "~6.0.1",
    "expo-asset": "~11.0.1",
    "expo-camera": "~16.0.10",
    "expo-clipboard": "~7.0.0",
    "expo-constants": "~17.0.3",
    "expo-contacts": "~14.0.2",
    "expo-device": "~7.0.1",
    "expo-document-picker": "~13.0.1",
    "expo-image-manipulator": "~13.0.5",
    "expo-image-picker": "~16.0.3",
    "expo-linear-gradient": "~14.0.1",
    "expo-linking": "~7.0.3",
    "expo-local-authentication": "~15.0.1",
    "expo-localization": "~16.0.0",
    "expo-location": "~18.0.4",
    "expo-notifications": "~0.29.11",
    "expo-secure-store": "~14.0.0",
    "expo-splash-screen": "~0.29.18",
    "expo-status-bar": "~2.0.0",
    "expo-system-ui": "~4.0.6",
    "expo-updates": "~0.26.10",
    "expo-web-browser": "~14.0.1",
    "formik": "^2.2.9",
    "google-libphonenumber": "^3.2.27",
    "hoist-non-react-statics": "^3.3.2",
    "i18n-js": "^3.8.0",
    "i18next": "^21.4.2",
    "is-valid-domain": "^0.1.6",
    "jssha": "^2.3.1",
    "lodash": "^4.17.21",
    "lottie-react-native": "7.1.0",
    "metro-react-native-babel-transformer": "^0.77.0",
    "moment": "^2.29.1",
    "moment-timezone": "^0.5.32",
    "node-libs-react-native": "^1.2.1",
    "patch-package": "^6.5.1",
    "postinstall-postinstall": "^2.1.0",
    "prop-types": "^15.8.1",
    "query-string": "^7.1.1",
    "react": "18.3.1",
    "react-dom": "18.3.1",
    "react-hook-form": "^7.43.9",
    "react-i18next": "^11.14.2",
    "react-native": "0.76.5",
    "react-native-animatable": "^1.3.3",
    "react-native-app-link": "^1.0.1",
    "react-native-circular-progress": "^1.3.8",
    "react-native-collapsible": "^1.6.1",
    "react-native-country-picker-modal": "^2.0.0",
    "react-native-gesture-handler": "~2.20.2",
    "react-native-markdown-display": "^7.0.0-alpha.2",
    "react-native-masked-text": "^1.13.0",
    "react-native-modal": "^13.0.1",
    "react-native-modal-datetime-picker": "^14.0.1",
    "react-native-pager-view": "6.5.1",
    "react-native-phone-number-input": "^2.1.0",
    "react-native-picker-select": "^8.0.4",
    "react-native-popover-view": "^5.1.7",
    "react-native-qrcode-svg": "^6.2.0",
    "react-native-reanimated": "~3.16.1",
    "react-native-round-flags": "^1.0.4",
    "react-native-safe-area-context": "4.12.0",
    "react-native-screens": "~4.4.0",
    "react-native-skeleton-placeholder": "^5.2.4",
    "react-native-snap-carousel": "4.0.0-beta.6",
    "react-native-super-grid": "^5.0.0",
    "react-native-svg": "15.8.0",
    "react-native-svg-transformer": "^1.0.0",
    "react-native-tab-view": "^3.5.1",
    "react-native-web": "~0.19.10",
    "react-native-webview": "13.12.5",
    "react-query": "^3.39.3",
    "react-redux": "^8.0.5",
    "redux": "^4.2.1",
    "redux-persist": "^6.0.0",
    "redux-saga": "^1.2.3",
    "redux-thunk": "^2.4.2",
    "reselect": "^4.1.7",
    "rn-material-ui-textfield": "^1.0.9",
    "stellar-sdk": "^8.2.3",
    "xstate": "^4.37.1",
    "yup": "^0.26.6"
  },

metro config

const { getSentryExpoConfig } = require("@sentry/react-native/metro");

const config = getSentryExpoConfig(__dirname);

const { transformer, resolver } = config;

config.transformer = {
  ...transformer,
  babelTransformerPath: require.resolve('react-native-svg-transformer'),
};
config.resolver = {
  ...resolver,
  assetExts: resolver.assetExts.filter(ext => ext !== 'svg'),
  sourceExts: [...resolver.sourceExts, 'svg'],
  extraNodeModules: require('node-libs-react-native'),
};

module.exports = config;
App.js
import App from './src';
require('node-libs-react-native/globals');
import Constants from 'expo-constants';

import * as Sentry from '@sentry/react-native';

// TODO: This constants format will change when we upgrade to the new Expo SDK.
// https://docs.expo.dev/guides/environment-variables/#reading-environment-variables
Sentry.init({
  dsn:
    Constants.expoConfig?.extra?.eas?.sentryDSN ??
    Constants.manifest2?.extra?.expoClient?.extra?.eas?.sentryDSN,
  debug: true,
});

export default Sentry.wrap(App);

Node version

v18.18.2

Expo SDK

52

in package.json

  "engines": {
    "node": ">=18"
  },

After building the project this error is showing
iOS Bundling failed 2276ms index.js (4106 modules)
Unable to resolve “@sentry-internal/replay” from “node_modules/@sentry/browser/build/npm/cjs/index.js”

@sentry/react-native internally import as this
const replay = require(‘@sentry-internal/replay’);

I tried to find the issue googling it, using GPT and stack-overflow as well.
But no solution found.

Please help me with this.

How can i extract color and link from pdf using pdfjs-dist

I am using pdfjs-dist to extract text from a PDF. I need to extract both the color of the text and any hyperlinks present in the document.

What I Have Tried
I am currently processing the PDF using pdfjs-dist and working with the operator list. Here’s my approach so far:

Extract text content using getOperatorList().
Analyze the extracted data to identify text fragments.
Check for text color and links, but I am not sure how to properly extract them.
Issues:
How can I reliably extract text color from the operator list?
How can I detect and extract hyperlinks in the document?

const loadingTask = pdfjsLib.getDocument("example.pdf");
loadingTask.promise.then(async (pdf) => {
const page = await pdf.getPage(1);
const opList = await page.getOperatorList();

   console.log(opList);
  // How do I extract text color and links from this?
});

How can I achieve this using pdfjs-dist? Any guidance or alternative approaches would be appreciated!

I am using pdfjs-dist to extract text from a PDF. I have obtained the OperatorList using getOperatorList(), which contains various drawing operations. My goal is to extract both:

Text color – I checked setFillColor and setStrokeColor operations in the operator list. However, I am not sure how to map these colors to specific text fragments.
Hyperlinks – I inspected annotations using getAnnotations(), which returns link metadata, but I am unsure how to correctly associate the links with specific text.

How do I toggle the visibility of answers of this language vocabulary list?

I started learning semi-recently, I want to make the Korean translation appear when I click the corresponding English word. I’m unfamiliar with JQuery and => notation so please keep any solution relatively basic (if there is a basic one) Thank you!

html:

    <div class="Words-container">
        <div id="Verbs">
            <div><h2 class="Word-title">Verbs</h2></div>
            <div><ul id="List-words">
                <li class = "english">To fall--<span class = "answer hideMe">넘어지다</span></li>
                <li class = "english">To be young--<span class = "answer hideMe">젊다</span></li>
                <li class = "english">To be anxious--<span class = "answer hideMe">불안하다</span></li>
                <li class = "english">To be sensitive--<span class = "answer hideMe">예민하다</span></li>
                <li class = "english">To translate--<span class = "answer hideMe">번역하다</span></li>
                <li class = "english">To give an example--<span class = "answer hideMe">예를 들어 주다</span></li>
                <li class = "english">To be perfect--<span class = "answer hideMe">완벽하다</span></li>
                <li class = "english">To be efficient--<span class = "answer hideMe">효율적이다</span></li>
            </ul></div>
        </div>

Javascript:

//add hover event listener to english word
for(x = 0; x < document.querySelectorAll(".english").length; x++){
    document.querySelectorAll(".english")[x].addEventListener("click", function(){//fn to show answer when click english word

//this function is wrong but I'm unsure of how to target the Korean when clicking the English
        this.closest("span").classlist.toggle(".hideMe");//toggle hideMe class when english clicked
    })
}

CSS

.hideMe{
    visibility: hidden;
}

ConnectError “tcp connect error” code: 111 connection refused

I’m encountering an error when running dfx deploy. After executing the command, an error appears. I’m new to this and still learning. I’d appreciate any help!

binding to: 127.0.0.1:34643
Mar 18 00:15:44.563 INFO ic-starter. Configuration: ValidatedConfig { replica_path: Some("/home/johnk/.cache/dfinity/versions/0.9.3/replica"), replica_version: "0.8.0", log_level: Warning, cargo_bin: "cargo", cargo_opts: "", state_dir: "/home/johnk/ic-project/hello5/.dfx/state/replicated_state", http_listen_addr: 127.0.0.1:0, http_port_file: Some("/home/johnk/ic-project/hello5/.dfx/replica-configuration/replica-1.port"), metrics_addr: None, provisional_whitelist: Some(All), artifact_pool_dir: "/home/johnk/ic-project/hello5/.dfx/state/replicated_state/node-100/ic_consensus_pool", crypto_root: "/home/johnk/ic-project/hello5/.dfx/state/replicated_state/node-100/crypto", state_manager_root: "/home/johnk/ic-project/hello5/.dfx/state/replicated_state/node-100/state", registry_local_store_path: "/home/johnk/ic-project/hello5/.dfx/state/replicated_state/ic_registry_local_store", unit_delay: None, initial_notary_delay: Some(600ms), dkg_interval_length: None, detect_consensus_starvation: None, consensus_pool_backend: Some("rocksdb"), subnet_features: SubnetFeatures { ecdsa_signatures: false, canister_sandboxing: false, http_requests: false, bitcoin_testnet_feature: None }, subnet_type: System, _state_dir_holder: None }, Application: starter
Mar 18 00:15:44.564 INFO Initialize replica configuration "/home/johnk/ic-project/hello5/.dfx/state/replicated_state/ic.json5", Application: starter
Mar 18 00:15:45.294 INFO Executing "/home/johnk/.cache/dfinity/versions/0.9.3/replica" "--replica-version" "0.8.0" "--config-file" "/home/johnk/ic-project/hello5/.dfx/state/replicated_state/ic.json5", Application: starter
Mar 18 00:15:47.537 WARN s:xbfln-jtge2-khab4-a2frw-ng7it-h6l44-gczgl-tn5yh-wynzi-ieqif-oae/n:ikgwu-bhrdw-c33x7-7sbrw-dvrv7-k2euw-gahmb-sxcvr-3r4b5-t2rks-yqe/ic_p2p/advert_utils AdvertRequestBuilder::new(): advert_config = Some(GossipAdvertConfig { best_effort_percentage: 20 })
version: 0.8.1
 Mar 18 08:15:47.589 INFO Log Level: INFO
 Mar 18 08:15:47.589 INFO Starting server. Listening on http://127.0.0.1:8002/
 Mar 18 08:15:48.627 WARN Internal Error during request:
hyper::Error(
    Connect,
    ConnectError(
        "tcp connect error",
        Os {
            code: 111,
            kind: ConnectionRefused,
            message: "Connection refused",
        },
    ),
)

I tried running dfx start --clean, changing the port, and checking if it’s in use, but the error still persists. I also attempted to unblock it through the firewall, but it’s still not working. I’m not sure what else to do—can anyone help me

How can code running inside a Docker container, connect to a Windows service?

I am running Docker 27.4.0 under Windows. The Windows version is 11 (24H2 OS Build 26100.3476). The solutions in question 24319662 don’t seem to work for me (maybe). What does work is connecting to 192.168.4.198. 192.168.4.198 just happens to be the IP address of host.docker.internal. I tried using net/network host in my run command and with docker compose. Those approaches did not work. Maybe they only work under Linux? Am I using the best solution? Is connecting to 192.168.4.198 the best solution?

I have a service running on my Windows machine that listens on port 443 (WebSockets). I created the service by running some Java code under Eclipse. I would like to use that service from inside a Docker container. If I try to connect to 127.0.0.1:443 from inside a Docker container to my service, I get the container’s 127.0.0.1:443 (which is not listening). I would like to have the code inside the Docket container use the “real” 127.0.0.1:443, not the one inside the Docker container. How do I do this? What should be in the compose file? What should the run command specify?

How do I change background color/image based on currently viewed month? Full Calendar Jquery

I am building a calendar using Full calendar. I have a specific background that I want for each month. The color changes according to the current day correctly. If it is currently march 17, it will show the march background.

I cannot figure out how to make the background change whenever I browse to look at future/past months. It stays the same. I want the background to change when I look at a different month.

Thanks in advance! I’m scratching my head at this one!

My code correctly sets the current months background initially.

Today’s date with the correct background color

When I browse to another month it doesn’t change.

Browsing to new months keeps the same color when it should be changing

If i change my PC’s time to another month, the background is different, so that part works.

Image when i change my computer time to a different time

My Current Code:

<script>
  $(document).ready(function() {
    var monthColors = [
            "#FF5733",   // January - Red-Orange
            "#33B5E5",   // February - Blue
            "#A569BD",   // March - Purple
            "#58D68D",   // April - Green
            "#F4D03F",   // May - Yellow
            "#FF8C00",   // June - Orange
            "#4682B4",   // July - Steel Blue
            "#DC143C",   // August - Crimson
            "#20B2AA",   // September - Light Sea Green
            "#FF6347",   // October - Tomato
            "#2E8B57",  // November - Sea Green
            "#B22222"   // December - Fire Brick
        ];       
        function updateBackground(date) {
            var month = date.getMonth(); // Get displayed month
            console.log("Updating background for month:", month + 1); // Debugging log
            $("body").css("background-color", monthColors[month]);
        }

  $('#calendar').fullCalendar(
    {
      header:
      {
        left: '',
        center: 'title'
      },
      events:
      [
        {
          title: 'Marriage',
          start: '2025-03-17',
          color: 'transparent',
          textColor: 'black',
          imageurl: 'birthday.png'
          },
          {
          title: 'Marriage',
          start: '2025-03-19',
          end: '2025-03-20',
          color: '#8E9A75',
          textColor: 'white',
          imageurl: 'birthday.png'
          }
      ],
      eventRender: function(event, eventElement) {
      if (event.imageurl) {
        eventElement.prepend("<img src='" + event.imageurl + "' width='80' height='80' >");
      }  return ['all', event.tags].indexOf($('#event_selector option:selected').val()) >= 0;
      },
      datesSet: function(info) {
        var currentMonth = calendar.getDate().getMonth() + 1;
            console.log("Currently viewed month:", currentMonth);
      },

      
  }); 

  setTimeout(function() {
            updateBackground(new Date());
        }, 100);

});


</script>

I am getting a GET 404 error and can’t find the problem

I am working on a project and can’t seem to fix this GET 404 error. In the console it looks like there it is messing up somewhere in between the javascript and html file, but I haven’t been able to pinpoint the issue. If anyone has any advice it’d be super appreciated.

HTML code:
file name > index.html

<html>
<head>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="../static/mywebscript.js"></script>
    <style>
        .center-heading {
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="card">
        <div class="card-body">
            <h1 class="center-heading">NLP - Emotion Detection</h1> 
            <div style="padding: 25px 25px 25px 25px;">
            <h2 class="mb-3">
                <label class="form-label">Please enter the text to be analyzed</label>
                <input type="textarea" class="form-control" id="textToAnalyze">
            </h2>

            <div style="padding: 25px 25px 25px 25px;">
                <button onclick="RunSentimentAnalysis()" class="btn btn-secondary">Run Sentiment Analysis</button>
            </div>
            <div style="padding: 25px 25px 25px 25px;"></div>
            <h2 class="mb-3">
                <label class="form-label">Result of Emotion Detection</label>
            </h2>

            <div id="system_response" style="padding: 25px 25px 25px 25px;"></div>
        </div>
    </div>
</body>
</html>

JavaScript code:
file name > mywebscript.js

let RunSentimentAnalysis = ()=>{
    textToAnalyze = document.getElementById("textToAnalyze").value;

    let xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("system_response").innerHTML = xhttp.responseText;
        }
    };
    xhttp.open("GET", "emotionDetector?textToAnalyze"+"="+textToAnalyze, true);
    xhttp.send();
}

Python code:
file name > emotion_detection.py

import requests
import json

def emotion_detector(text_to_analyze):
    url ='https://sn-watson-emotion.labs.skills.network/v1/watson.runtime.nlp.v1/NlpService/EmotionPredict'
    header = {"grpc-metadata-mm-model-id": "emotion_aggregated-workflow_lang_en_stock"}
    input_json = { "raw_document": { "text": text_to_analyze } }
    response = requests.post(url, json=input_json, headers=header)
    status_code = response.status_code

    emotions = {}

    if status_code == 200:
        formatted_response = json.loads(response.text)
        emotions = formatted_response['emotionPredictions'][0]['emotion']
        dominant_emotion = max(emotions.items(), key=lambda x: x[1])
        emotions['dominant_emotion'] = dominant_emotion[0]
    elif status_code == 400:
        emotions['anger'] = None
        emotions['disgust'] = None
        emotions['fear'] = None
        emotions['joy'] = None
        emotions['sadness'] = None
        emotions['dominant_emotion'] = None
    return emotions

and
file name > server.py

from flask import Flask, request, render_template
from EmotionDetection.emotion_detection import emotion_detector

app = Flask("Emotion Detector")

@app.route("/emotionDetector")
def emotion_analyzer():
    text_to_analyse = request.args.get('textToAnalyze')
    emotion_result = emotion_detector(text_to_analyse)
    anger = emotion_result['anger']
    disgust = emotion_result['disgust']
    fear = emotion_result['fear']
    joy = emotion_result['joy']
    sadness = emotion_result['sadness']
    dominant_emotion = emotion_result['dominant_emotion']

    if dominant_emotion is None:
        return "Invalid text! Please try again"

    response_str = f"""For the given statement, the system response is
    'anger': {anger}, 'disgust': {disgust}, 'fear': {fear}, 'joy': {joy}, 'sadness': {sadness}.
    The dominant emotion is <strong>{dominant_emotion}</strong>."""
    return response_str

@app.route("/")
def render_index_page():
    return render_template('index.html')

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)