Pie Chart not Populating Asp.Net MVC Page

I am having trouble populating my pie chart using chart.js. The chart legend comes up but the values are undefined.

Cshml

@page
@model FinalProject.Pages.Exam.ReportModel
@{
    Layout = null;
}

<h2>Letter Grade Report</h2>
<table>
    <tr>
        <th>Exam ID</th>
        <th>Student ID</th>
        <th>Score</th>
        <th>Letter Grade</th>
    </tr>
    @foreach (var exam in Model.Exams)
    {
        <tr>
            <td>@exam.ExamId</td>
            <td>@exam.StudentID</td>
            <td>@exam.Score</td>
            <td>@FinalProject.Pages.Exam.ReportModel.CalculateLetterGrade(exam.Score)</td>
        </tr>
    }
</table>

<h2>Letter Grade Summary</h2>
<table>
    <tr>
        <th>Letter Grade</th>
        <th>Total Count</th>
    </tr>
    @foreach (var gradeSummary in Model.GradeSummary)
    {
        <tr>
            <td>@gradeSummary.LetterGrade</td>
            <td>@gradeSummary.TotalCount</td>
        </tr>
    }
</table>

<!-- Add Chart.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>

<h2>Letter Grade Distribution (Pie Chart)</h2>
<div style="max-height:300px;">
    <canvas id="gradeChart"></canvas>
</div>

<script>
    let gradeData = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.GradeSummary));

    const data = {
        labels: gradeData.map(g => g.letterGrade),
        datasets: [{
            label: 'Grade Distribution',
            data: gradeData.map(g => g.totalCount),
            backgroundColor: ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'],
            hoverOffset: 4
        }]
    };

    const config = {
        type: 'pie',
        data: data,
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    };

    new Chart(document.getElementById('gradeChart'), config);
</script>

Cshtml.cs

using Microsoft.AspNetCore.Mvc.RazorPages;
using School.DAL;
using System;
using System.Collections.Generic;
using System.Linq;

namespace FinalProject.Pages.Exam
{
    public class ReportModel : PageModel
    {
        private readonly IExamAdapter _examAdapter;

        public ReportModel(IExamAdapter examAdapter)
        {
            _examAdapter = examAdapter;
        }

        public List<School.DAL.Exam> Exams { get; set; }
        public List<GradeSummary> GradeSummary { get; set; }

        public void OnGet()
        {
            Exams = _examAdapter.GetAll().ToList();

            // Calculate letter grades and generate summary
            GradeSummary = CalculateGradeSummary(Exams);
        }

        private List<GradeSummary> CalculateGradeSummary(List<School.DAL.Exam> exams)
        {
            var gradeSummary = new List<GradeSummary>();

            var gradeGroups = exams.GroupBy(e => CalculateLetterGrade(e.Score));

            foreach (var group in gradeGroups)
            {
                gradeSummary.Add(new GradeSummary
                {
                    LetterGrade = group.Key,
                    TotalCount = group.Count()
                });
            }

            return gradeSummary;
        }

        public static string CalculateLetterGrade(string score)
        {
            if (int.TryParse(score, out int scoreValue))
            {
                if (scoreValue >= 90) return "A";
                else if (scoreValue >= 80) return "B";
                else if (scoreValue >= 70) return "C";
                else if (scoreValue >= 60) return "D";
                else return "F";
            }
            else
            {
                // Handle the case where score is not a valid integer (e.g., invalid input)
                return "Invalid";
            }
        }
    }

    public class GradeSummary
    {
        public string LetterGrade { get; set; }
        public int TotalCount { get; set; }
    }
}

here is what is currently showing:
enter image description here

I tried changing up the script and am contemplating using Adapters instead of using the method im using but I feel like its an easy fix. The data all comes from CRUD operations on the site and that I added so the data is not static. Exam scores comes from another model that has its own CRUD operation (edit.cshtml, edit.cshtml.cs, delete.cshtml…..) and this page is used for reporting and charting exams scores

Issue with Uploading image file after cropping with cropper.js in Java Springboot

I used cropper.js to crop and image file and upload the image file into backend(java springboot) but everytime it gives the error of 404 eventhough the url exists

 <div class="formPart">
            <div class="image_area" style="height: 100px; width: 100px">
                <label for="upload_image">
                    <img th:src="@{profilePic/default/profile.webp}" id="uploaded_image" class="img-responsive img-circle">
                    <div class="overlay">
                        <div class="text">Click to Change Profile Image</div>
                    </div>
                    <input type="file" name="image" class="image" id="upload_image" style="display:none" accept="image/*"/>
                </label>
            </div>

This is my HTML

$(document).ready(function () {
    var modal = $('#modal');

    var image = document.getElementById('sample_image');

    var cropper;

    var csrfToken = $("meta[name='_csrf']").attr("content");

    $('#upload_image').change(function (e) {
        if (cropper) {
            cropper.destroy();
            cropper = null;
        }
        var files = e.target.files;

        var done = function (url) {
            image.src = url;

            modal.modal('show');
        };

        if (files && files.length > 0) {
            reader = new FileReader();

            reader.onload = function (e) {

                done(reader.result);

            };

            reader.readAsDataURL(files[0]);
        }

    });

    modal.on('shown.bs.modal', function () {


        cropper = new Cropper(image, {
            aspectRatio: 1,
            viewMode: 3,
            preview: '.preview'
        });
    }).on('hidden.bs.modal', function () {

    });
    $('#crop').click(function () {
        canvas = cropper.getCroppedCanvas({
            width: 400,
            height: 400
        });


        $('#uploaded_image').attr('src', canvas.toDataURL("image/png"));
        modal.modal('hide');
    })


//ajax through which i upload the image

    $('#signupForm').submit(function (e) {
        e.preventDefault();

        var email = document.getElementById('Email');
        canvas.toBlob(function (blob) {
            url = URL.createObjectURL(blob);

            var formdata = new FormData();

            formdata.append('image', blob, email.value + '.jpg');

            $.ajax({
                type: "get",
                url: "/profile/upload",
                data: formdata,

// i also tried contentType: false over here
                contentType: 'application/json',
                processData: false,
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('X-CSRF-TOKEN', csrfToken);
                },
                success: function () {

                    var form = document.getElementById('signupForm');

                    form.submit();

                }
            });



        }, 'image/jpeg', 0.9);

    });


});

This is my js file

     @GetMapping("/profile/upload")
     @ResponseBody
        public void uploadProfilePic(@RequestParam("image") MultipartFile file,
                                               HttpSession session) throws IOException {
         log.info("inside profile picture uploading not inside file is empty");
         if (!file.isEmpty()) {
             String fileName = StringUtils.cleanPath(file.getOriginalFilename());
             log.info("inside profile picture uploading");

             String upload = "lenscraft/src/main/resources/static/profilePic";

             FileUploadUtil.saveFile(upload, fileName, file);

             session.setAttribute("fileName", fileName);

         }
     }

And this is the backend code.

I tried this and many other ways including just passing the image as an object but it does not seem to work. I want to know any ways how i can crop the image and upload it into the backend.

intersection of two cubes in 3d space [closed]

How do I understand that a cube intersects with another cube, or is inside it?

let firstCube = {
  a: {
    //-15 71 -34
    x: -15,
    y: 71,
    z: -34
  },
  b: {
    //-19 72 -38
    x: -19,
    y: 72,
    z: -38
  }
}

let secondCube = {
  a: {
    //-16 71 -38
    x: -16
    y:  71
    z:  -38
  },
  b: {
    //-13 71 -41
    x: -13
    y: 71
    z: -41
  }
}

/*code*/
//idk
/*----*/

I could resort to a system of taking each coordinate from a cube and testing it on another cube. But I need a system that will require a minimum load on the computer, since there are a lot of objects.

Closer to the point, I’m making a server for my project on node.js, that is, 3D mini games, but the following problem arose.

Even closer to the point, I make regions as protective zones so that unnecessary entities or objects do not get there.

I tried to do this a long time ago using regular JS and I only managed to create a site protection system, but I couldn’t use intersections to get entities.

A little later I did it again, but only in node.js and it also worked, but I encountered another set of problems, including intersections again.

Unable to draw SVG coordinates accurately with Javascript

I’ve been struggling for days with drawing an SVG vectorscope using JavaScript. The purpose of the project is to analyze an image, plot every pixel on the scope, and draw the trace between the rendered pixels. However, I’m not able to accurately plot the reference color targets on the SVG, so something is wrong in either my code or my understanding.

Here is a link to my CodePen. And here is my code copied here:

HTML:

<div id="app">
  <div class="view" id="scope-img-ref">
    <img src="https://i.ibb.co/FYyYT0q/vectorscope-ref.png" alt="vectorscope-ref" border="0">
  </div>
  <div class="view" id="scope-svg">
    <svg viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
      <circle cx="256" cy="256" r="256" stroke="black" fill="transparent" />

      <!-- Axes -->
      <line x1="0" y1="256" x2="512" y2="256" stroke="black" stroke-width="2" />
      <line x1="256" y1="0" x2="256" y2="512" stroke="black" stroke-width="2" />

      <!-- Skin tone line -->
      <g stroke="black" stroke-width="2" id="skinToneLine">
      </g>

      <!-- Reference target areas -->
      <g id="refTargetAreas">
      </g>

      <!-- Draw tick marks -->
      <g stroke="black" stroke-width="2" id="tickMarks">
      </g>
    </svg>
  </div>
</div>

<!-- Toggle button for image underlay -->
<div>
  <button id="imgToggleBtn">Toggle Ref Image</button>
</div>

<!-- Toggle button for YCbCr representation -->
<div>
  <button id="yCbCrToggleBtn">Toggle YCbCr</button>
</div>

CSS:

body {
  margin: 0;
  padding: 0;
  
  box-sizing: border-box;
}

#app {
  position: relative;
  width: 512px;
  height: 512px;
  
  margin-bottom: 2.5%;
}

#scope-img-ref {
  width: 100%;
  height: 100%;
}

#scope-svg {
  background: rgba(255, 255, 255, 0.25);
  z-index: 10;
}

#scope-svg svg {
  width: 512px;
  height: 512px;
}

.view {
  position: absolute;
  top: 0;
  left: 0;
}

JavaScript:

// Util functions
const degToRad = (deg) => {
  return deg * (Math.PI / 180);
};

const rgbToHsv = (rgb) => {
  const r = rgb[0] / 255;
  const g = rgb[1] / 255;
  const b = rgb[2] / 255;

  const max = Math.max(r, g, b);
  const min = Math.min(r, g, b);
  const delta = max - min;

  let h, s, v;

  // Calculate hue
  if (delta === 0) {
    h = 0;
  } else if (max === r) {
    h = ((g - b) / delta) % 6;
  } else if (max === g) {
    h = (b - r) / delta + 2;
  } else {
    h = (r - g) / delta + 4;
  }

  h = (h * 60 + 360) % 360;

  // Calculate saturation
  s = max === 0 ? 0 : delta / max;

  // Calculate value
  v = max;

  return { h, s, v };
};

const rgbToYCbCr = (rgb) => {
    const r = rgb[0];
    const g = rgb[1];
    const b = rgb[2];

    // Y component (luma)
    // Using ITU-R BT.709 coefficients (need to research this further)
    const y = (0.299 * r + 0.587 * g + 0.114 * b);

    // Cb and Cr components (chroma)
    const cb = ((b - y) / 1.772 + 128.0);
    const cr = ((r - y) / 1.402 + 128.0);

    return {y, cb, cr}
}

// Rotate to correct quadrant
const getCartesianSVGCoords = (r, phi, c_off) => {
  return {
    x: (c_off * r * Math.cos(phi + 1.5 * Math.PI)) + c_off,
    y: (c_off * r * Math.sin(phi + 1.5 * Math.PI)) + c_off
  };
};


// Draw skin tone line along -I axis
const I_LINE_ROT = degToRad(33);

const skin_tone_line = document.createElementNS("http://www.w3.org/2000/svg","line");
skin_tone_line.setAttribute("x1", 256);
skin_tone_line.setAttribute("y1", 256);
skin_tone_line.setAttribute("x2", getCartesianSVGCoords(1, -1 * I_LINE_ROT, 256).x);
skin_tone_line.setAttribute("y2", getCartesianSVGCoords(1, -1 * I_LINE_ROT, 256).y);
document.getElementById("skinToneLine").appendChild(skin_tone_line);


// Draw red target point with HSV at 75% saturation
const red_hsv = rgbToHsv([255, 0, 0]);
const red_hsv_coords = getCartesianSVGCoords(0.75 * red_hsv.s, red_hsv.h, 256);
console.log("Red Target Coords HSV: ", red_hsv_coords);

const red_target_circle_hsv = document.createElementNS("http://www.w3.org/2000/svg","circle");
red_target_circle_hsv.setAttribute("r", 4);
red_target_circle_hsv.setAttribute("cx", red_hsv_coords.x);
red_target_circle_hsv.setAttribute("cy", red_hsv_coords.y);
red_target_circle_hsv.setAttribute("fill", "rgb(255, 0, 0)")
document.getElementById("refTargetAreas").appendChild(red_target_circle_hsv);

// Draw red target point with YCbCR representation
const red_ycbcr = rgbToYCbCr([255, 0, 0]);
const red_ycbcr_coords = {
   x: 256 - red_ycbcr.cb, // Offset by SVG origin
   y: 256 - (0.75 * red_ycbcr.cr) // Scale by 75% and offset by SVG origin
}
console.log("Red Target Coords YCbCr: ", red_ycbcr_coords);

const red_target_circle_ycbcr = document.createElementNS("http://www.w3.org/2000/svg","circle");
red_target_circle_ycbcr.setAttribute("r", 4);
red_target_circle_ycbcr.setAttribute("cx", red_ycbcr_coords.x);
red_target_circle_ycbcr.setAttribute("cy", red_ycbcr_coords.y);
red_target_circle_ycbcr.setAttribute("fill", "rgb(255, 0, 0)")
document.getElementById("refTargetAreas").appendChild(red_target_circle_ycbcr);


// Draw tick marks every 5 degrees
const drawTick = (x1, y1, x2, y2) => {
  var line = document.createElementNS("http://www.w3.org/2000/svg", "line");
  line.setAttribute("x1", x1);
  line.setAttribute("y1", y1);
  line.setAttribute("x2", x2);
  line.setAttribute("y2", y2);
  document.getElementById("tickMarks").appendChild(line);
};

for (var angle = 0; angle < 360; angle += 5) {
  var radians = (angle * Math.PI) / 180;
  var x1 = 256 + 256 * Math.cos(radians);
  var y1 = 256 + 256 * Math.sin(radians);
  var x2 = 256 + (angle % 10 === 0 ? 240 : 248) * Math.cos(radians);
  var y2 = 256 + (angle % 10 === 0 ? 240 : 248) * Math.sin(radians);

  drawTick(x1, y1, x2, y2);
}


// Handle img button toggle
const imgButtonToggleEl = document.getElementById("imgToggleBtn");

const imgRefEl = document.getElementById("scope-img-ref");
imgRefEl.style.display = "none";

imgButtonToggleEl.onclick = () => {
  if(imgRefEl.style.display === "none") {
      imgRefEl.style.display = "block" 
  } else {
       imgRefEl.style.display = "none" 
  }
}


// Handle YCbCr button toggle
const yCbCrButtonToggleEl = document.getElementById("yCbCrToggleBtn");
red_target_circle_ycbcr.setAttribute("fill", "none");

yCbCrButtonToggleEl.onclick = () => {
  if(red_target_circle_ycbcr.getAttribute("fill") === "none") {
    red_target_circle_ycbcr.setAttribute("fill", "rgb(255, 0, 0)");
  } else {
    red_target_circle_ycbcr.setAttribute("fill", "none");
  }
}

I’ve placed a button that toggles on a reference image. This is a screenshot I took from DaVinci Resolve Studio showing their vectorscope. As you can see, the Red target square from the DaVinci Resolve scope is about -10deg away from where my Red target circle is and closer to the origin vertically as well.

The DaVinci Resolve image shows the trace from the SMPTE color bars, so I know the positions of the Red, Magenta, Blue, Cyan, Green, and Yellow targets are accurate – as one would expect.

Furthermore, my skin tone line lies on the same -I axis as in DaVinci Resolve, so I know that at least part of my logic is correct here.

So I think the problem lies in my conversion from RGB to HSV and/or in plotting the target on the SVG. But even converting to YCbCr and plotting those coordinates results in inaccuracy (as you can see with the toggle button at the bottom).

However, what’s making me scratch my head is that logically it seems to me that since pure red (RGB of (255, 0, 0), HSV of (0, 100, 1)) has a hue of 0, it should actually lie on the vertical axis like I have it here – since hue represents the angle from the origin in a polar representation. So why is it that a proper vectorscope, like the one used in DaVinci Resolve, has the Red target shifted to the right quadrant? What is the gap in my understanding here?

I know I still have a lot to learn in this area, so any help and resources for further research are much appreciated

Debugging a leetcode solution in javascript – coin change,

I solved a leetcode question that looks correct to me, but It’s not and I am unable to understand why it is wrong. Can someone please tell me why my solution is not working
Following is the question

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
You may assume that you have an infinite number of each kind of coin.

Here is my solution

var coinChange = function (coins, amount) {
  coins = coins.sort((a, b) => b - a)
  let cache = {}
  let result = coinChangeHelper(coins, amount, 0, cache)
  return result
};

var coinChangeHelper = (coins, amount, coinUsedTillNow, cache) => {
    if (cache[amount] !== undefined) {
        return cache[amount]
    }

  if (amount === 0) {
    cache[amount] = coinUsedTillNow
    return coinUsedTillNow
  }

  if (amount < 0) {
    return -1
  }

  for (let i = 0; i < coins.length; i++) {
    let result = coinChangeHelper(coins, amount - coins[i], coinUsedTillNow + 1, cache)
    if (result !== -1) {
        cache[amount] = result
        return result
    }
  }

  cache[amount] = -1
  return -1

Dynamic Object Generation in TypeScript with User-Specified Number of Keys

I’m currently working with TypeScript and facing a scenario where I need to dynamically generate an object with a user-specified number of keys. By “dynamically,” I mean having the flexibility to determine the number of keys. Each key should follow a specific structure, involving a common expression with an appended iteration number.

For example, I’m aiming for an object like this:

const dynamicObj = {
    "Ali-0": 35,
    "Ali-1": 66,
    "Ali-2": 50,
    "Ali-3": 79,
    "Ali-4": 33,
    "Ali-5": 62,
    "Ali-6": 30,
    "Ali-7": 52,
    "Ali-8": 89,
    "Ali-9": 16,
};

The actual numerical values for each key are not important, and I’d prefer them to be generated randomly.

I would appreciate it if you could share your opinion about my question. Thanks.

Call PHP from Cacheable Javascript

I wrote some PHP to query the live status of a Youtube channel. Instead of polling Youtube, I poll an API endpoint (JSON) of a Youtube Live Embed plugin for the “live_status” marker.

As another wrinkle to this, the result of the API polling and the current time is overwritten to a JSON file (called: LastEmbedVidioPull.json in my code below), so that on subsequent runs of the PHP, the code will check the LastEmbedVidioPull.json to see whether 5 minutes have elapsed since the last run. If not, the PHP will echo the status code from LastEmbedVidioPull.json. If 5 or more minutes have elapsed, then we poll the external API endpoint, update the internal JSON file with the new time and status code, and echo the new status code. There’s also error logging, and the default status code 0 (not live) is echoed when an error is present.

The PHP:

<?php

$now = date("Y-m-d") . "T" . date("H:i:s.000") . "Z";
$curla = curl_init();

curl_setopt_array($curla, [
    CURLOPT_URL => "[URL to LastEmbedVidioPull.json]",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET"
]);

$responsec = curl_exec($curla);
$errora = curl_error($curla);

curl_close($curla);

if ($errora) {
    $toLog = $now . " cURL error #: " . $errora . "rn";
    $Log = "EmbedVidioErrorLog.txt";
    $upload_dir = wp_get_upload_dir();
    $save_path = $upload_dir['basedir'] . '/' . $Log;
    file_put_contents($save_path, $toLog, FILE_APPEND | LOCK-EX);
    echo 0;
} else {
    $showInfoa = json_decode($responsec, true);
    $lastpull = strtotime($showInfoa["pull_time"]);
    $diff = strtotime($now) - $lastpull;
    if ($diff > 300) {

        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => "[URL to External API endpoint provided by YT Live Embed Plugin Provider]",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "GET"
        ]);

        $response = curl_exec($curl);
        $error = curl_error($curl);

        curl_close($curl);

        if ($error) {
            $toLoga = $now . " EmbedVidio API cURL error #: " . $error . "rn";
            file_put_contents($save_path, $toLoga, FILE_APPEND | LOCK-EX);
            echo 0;
            
        } else {
            ##echo $response;
            $extractInfo = str_replace('},]',"}]",$response);
            $showInfo = json_decode($extractInfo, true);
            $live_status = $showInfo["live_status"];
            $responsea = json_encode('{"live_status":"' . $live_status . '", "pull_time":"' . $now . '"}');
            file_put_contents($upload_dir['basedir'] . '/LastEmbedVidioPull.json', $responsea, LOCK-EX);
            echo $live_status;
        }
    } else {
        echo $showInfoa["live_status"];
    }
}
?>

I haven’t tried the PHP yet, so I’m not sure about performance, and I’m definitely open to suggestions. Additionally, you will see I am echoing a status code (whether a static 0 for errors or a 0 or 1 from either JSON file). But, how would I go about connecting cacheable JS to get the output from my PHP, so it can use the status code to add or remove a “we’re live” banner to the top of the webpage?

How do I get analytics data from Playable ADS?

I have added gtag to my playable ads app (javascript, single html). This works by direct link, but does not work for advertising platforms. I do not receive data (events) if the playable is launched through Unity, Applovine, Ironsource, etc. (These advertising platforms must support gtag).
What could be the problem?
Thanks.

I created a data stream, created special events, and added a default script.Next, I’m calling an event like: gtag("event", "eventName");

I think the problem is that the advertising platforms launch the Playable in the Iframe.

Error: Cannot find module ‘@tanstack/query-core’

I was trying implement a ConnectWalletButton demo with “Rainbowkit”+”wagmi”+viem” and when i try “yarn run dev”, it promoted me with this

Unhandled Runtime Error
Error: Cannot find module '@tanstack/query-core'

Call Stack
webpackMissingModule
webpack-internal:///(app-pages-browser)/./node_modules/@wagmi/core/dist/esm/query/getBalance.js (6:50)
eval
webpack-internal:///(app-pages-browser)/./node_modules/@wagmi/core/dist/esm/query/getBalance.js (6:145)
(app-pages-browser)/./node_modules/@wagmi/core/dist/esm/query/getBalance.js
file:///home/xly/web3/hh-fc/nextjs-smartcontract-lottery-fcc3/.next/static/chunks/app/page.js (7227:1)
options.factory
file:///home/xly/web3/hh-fc/nextjs-smartcontract-lottery-fcc3/.next/static/chunks/webpack.js (721:31)
__webpack_require__
file:///home/xly/web3/hh-fc/nextjs-smartcontract-lottery-fcc3/.next/static/chunks/webpack.js (37:33)
fn
file:///home/xly/web3/hh-fc/nextjs-smartcontract-lottery-fcc3/.next/static/chunks/webpack.js (376:21)
eval
webpack-internal:///(app-pages-browser)/./node_modules/wagmi/dist/esm/hooks/useBalance.js (5:75)
(app-pages-browser)/./node_modules/wagmi/dist/esm/hooks/useBalance.js
file:///home/xly/web3/hh-fc/nextjs-smartcontract-lottery-fcc3/.next/static/chunks/app/page.js (9823:1)
options.factory
file:///home/xly/web3/hh-fc/nextjs-smartcontract-lottery-fcc3/.next/static/chunks/webpack.js (721:31)
__webpack_require__
file:///home/xly/web3/hh-fc/nextjs-smartcontract-lottery-fcc3/.next/static/chunks/webpack.js (37:33)
fn
file:///home/xly/web3/hh-fc/nextjs-smartcontract-lottery-fcc3/.next/static/chunks/webpack.js (376:21)
eval
webpack-internal:///(app-pages-browser)/./node_modules/@rainbow-me/rainbowkit/dist/index.js (35:64)
(app-pages-browser)/./node_modules/@rainbow-me/rainbowkit/dist/index.js
file:///home/xly/web3/hh-fc/nextjs-smartcontract-lottery-fcc3/.next/static/chunks/app/page.js (6589:1)
options.factory
file:///home/xly/web3/hh-fc/nextjs-smartcontract-lottery-fcc3/.next/static/chunks/webpack.js (721:31)
__webpack_require__
file:///home/xly/web3/hh-fc/nextjs-smartcontract-lottery-fcc3/.next/static/chunks/webpack.js (37:33)
fn
file:///home/xly/web3/hh-fc/nextjs-smartcontract-lottery-fcc3/.next/static/chunks/webpack.js (376:21)
requireModule
node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.browser.development.js (156:22)
initializeModuleChunk
node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.browser.development.js (1357:0)
resolveModuleChunk
node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.browser.development.js (1302:0)
eval
node_modules/next/dist/compiled/react-server-dom-webpack/cjs/react-server-dom-webpack-client.browser.development.js (1774:0)

and then i added “@tanstack/query-core” and “@tanstack/react-query” and the error still remained.

I did see query-core in node_modules

here is my “package.json” down below

{
  "name": "nextjs-smartcontract-lottery-fcc3",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@rainbow-me/rainbowkit": "2.0.0-beta.1",
    "@tanstack/query-core": "^5.17.15",
    "@tanstack/react-query": "^5.17.15",
    "next": "14.0.4",
    "react": "^18",
    "react-dom": "^18",
    "viem": "2",
    "wagmi": "2"
  },
  "devDependencies": {
    "eslint": "^8",
    "eslint-config-next": "14.0.4"
  }
}

“next.config.js”

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  webpack: (config) => {
    config.resolve.fallback = { fs: false, net: false, tls: false };
    config.externals.push("pino-pretty", "lokijs", "encoding");
    return config;
  },
};

module.exports = nextConfig;


I’ve looked through both Rainbowkit’s and Wagmi’s community and i still don’t have any clue fixing it.
Have anyone ever met this error and ended up fixing it?
Thank you !

Weird GMT+0017 timezone

Why does

new Date(-2450995200001)

yield this weird time with a GMT+0017 timezone?

Sun May 01 1892 00:17:29 GMT+0017 (Central European Summer Time)

(One millisecond later, everything is well-behaved: Sun May 01 1892 00:00:00 GMT+0000 (Central European Summer Time))

React Js rendering blank subpage

I am coding a website for fun using react js and am trying to figure out how to use link to route between pages. I have finally added a link to the subpage using href

But when I click on it, the screen shows a blank background even though I have put text in it. Here is my code for the subpage:

const subPage = ()=>{

return(
    <section className='section'>
    <h2>subPage
    </h2> 
    </section>

);

}
export default subPage;

Why is it rendering blank?

I am expecting the text I am putting into the section to show on the screen, but its blank.

Aborting a Message Processing when RMQ Channel Closes | Node.js

We are using AMQPlib in Node.js to consume the messages from RMQ. In my case some times consumer takes longer than 30 mins to complete the process. But RabbitMQ server will close channel after 30 mins ( configurable at server level ), but my Node.js consumer continues to process the request which is bad, because i cannot recreate the channel now, because if recreate the same message which got timed out will be back to the consumer once again which will end up duplicate processing.

I would like to know

  1. Is it possible to configure the channel timeout for each message or queue basis ?
  2. Is it possible to listen for channel close and abort the already processing request in Node.js ? Because processing is not simple functions, its function of functions & even it makes database calls/redis calls internally.

Aborting a Request Processing in Server when client disconnects | Node.js

We have multiple micro-service running in our infra, we have also configured time outs to each API.

Let say Service A calls Service B, but Service B takes longer to respond Service A timed out/client disconnect, the request processing in Service A continue to process the request, this is really affecting the server performance. Is it possible to abort the server processing when client disconnects ? I know it is not straight forward & not a ideal design. But i want to implement the solution i’m getting here in case by case basis.

I read about Abort Controller, but it seems we have to pass the Signal across full stack of the handler and listen for Abort event at each function and throw error, which is not ideal i guess.

Node.js: Uncaught TypeError: Cannot read properties of undefined (reading ‘TokenType’)

I have a simple node.js application that have basic login page and for user1 it embed private power bi report. everything working as expected except when user1 actually login, a blank page shown with the following error in the console:

dashboard:19 Uncaught TypeError: Cannot read properties of undefined (reading 'TokenType')
    at HTMLDocument.

Where the error is refer to this in my dashboard.ejs:

tokenType: powerbi.models.TokenType.Embed,

The server side, has this server.js:

app.get('/dashboard', async (req, res) => {
    const user = req.session.user;

    if (user === 'user1') {
        try {
            const accessToken = [Hidden]
            console.log(`nn your token is >>>n  ${accessToken} nn`);
    
            const apiUrl = `https://api.powerbi.com/v1.0/myorg/groups/[Hidden]/reports/${encodeURIComponent('[Hidden]')}/GenerateToken`;
            console.log(`your api url is >>>  ${apiUrl} nn`);

            const apiResponse = await axios.post(apiUrl, {
                accessLevel: 'view'
            }, {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${accessToken}`
                }
            });
            console.log(`your response is >>>  ${apiResponse} nn`);

            const embedToken = apiResponse.data.token;
            console.log(`your embed token is  ${embedToken} nn`);
            res.render('dashboard', { embedURL: 'https://app.powerbi.com/reportEmbed?reportId=[Hidden]&autoAuth=true&ctid=[Hidden]', embedToken });
        } catch (error) {
            console.error('Error generating Power BI embed token:', error);
            res.redirect('/');
        }
    } else if (user === 'user2') {
        res.render('dashboard', { welcomeMessage: 'Welcome, User 2!' });
    } else {
        res.redirect('/');
    }
});

And my client side dashboard.ejs:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard</title>
    <script src="/powerbi.js"></script>
</head>
<body>
    <% if (embedURL && embedToken) { %>
        <div id="reportContainer" style="height: 600px;"></div>
        <script>
            // Make sure powerbi object is available before using it
            document.addEventListener("DOMContentLoaded", function () {
                var embedConfiguration = {
                    type: 'report',
                    id: '<%= embedURL %>',
                    embedUrl: '<%= embedURL %>',
                    tokenType: powerbi.models.TokenType.Embed, // Use powerbi.models.TokenType.Embed
                    accessToken: '<%= embedToken %>',
                    settings: {
                        filterPaneEnabled: false,
                        navContentPaneEnabled: false
                    }
                };

                // Embed the report
                var reportContainer = document.getElementById('reportContainer');
                var report = powerbi.embed(reportContainer, embedConfiguration);
            });
        </script>
    <% } else if (welcomeMessage) { %>
        <h2><%= welcomeMessage %></h2>
    <% } %>
    <a href="/logout">Logout</a>
</body>
</html>