Error while requesting index.php: Error: The response is not of type JSON at fetchData

hi I would like to solve this problem, in my react app I have to receive the json data taken from an index.php, testing only the php gives me the json data correctly, while the react app tells me that they are not in the right format
your textI need to make an app that returns an ag-grid table containing the data taken from my company’s Apache server
next there is my app.js file where i wrote my code

import './App.css';
import { AgGridReact } from 'ag-grid-react';

import {useState, useEffect, useMemo} from 'react';

import 'ag-grid-community/styles/ag-grid.css'; 
import 'ag-grid-community/styles/ag-theme-alpine.css';

function App() {
 //dichiarazione tabella
 const [rowData, setRowData] = useState([
  {id: 'Ford', nome: 'Focus', cognome: 400000},
  {id: 'BMW', nome: '3 Series', cognome: 52641},
  {id: 'Audi', nome: 'A8L', cognome: 79147},
 ]);
 
 const [columnDefs,_setColumnDefs] = useState([
                { headerName: 'ID', field: 'COL 1' },
                { headerName: 'NOME', field: 'COL 2' },
                { headerName: 'COGNOME', field: 'COL 3' },
                { headerName: 'MACCHINA', field: 'COL 4' },
                { headerName: 'GIORNO', field: 'COL 5' },
                { headerName: 'LAVORO', field: 'COL 6' },
                { headerName: 'INIZIO', field: 'COL 7' },
                { headerName: 'FINE', field: 'COL 8' }
 ]);

 const defaultColDef = useMemo( ()=> ({
  sortable: true,
  filter: true
}), []);
//fetch dati dall'index ed analisi del risultato
useEffect(() => {
  let isMounted = true;

  const fetchData = async () => {
    try {
      const response = await fetch('index2.php');

      if (!response.ok) {
        throw new Error(`Errore nella richiesta: ${response.status}`);
      }

      const contentType = response.headers.get('content-type');
      if (contentType && contentType.includes('application/json')) {
        const rowData = await response.json();
        
        if (isMounted) {
          console.log('Dati ottenuti da index.php:', rowData);
          setRowData(rowData);
        }
      } else {
        throw new Error('La risposta non è di tipo JSON');
      }
    } catch (error) {
      console.error('Errore durante la richiesta a index.php:', error);
    }
  };

  fetchData();

  return () => {
    // Cleanup function, eseguita quando il componente si smonta
    isMounted = false;
  };
}, []);
//
  return (
    <div className='ag-theme-alpine-dark' style={{height: 500}}>
      <AgGridReact
        rowData={rowData}
        columnDefs={columnDefs}
        defaultColDef={defaultColDef}
        animateRows={true}
        />
    </div>
  );
}

export default App;

JavaScript/React – Currency Formatting For Canadian French

I’m attempting to write a function that says, “if the URL contains /fr, apply the french formatting to the pricing. Otherwise, if URL contains /en, keep the default pricing”.

In Canadian French, the numbers are formatted a bit differently. Example: 19 304,45 $ instead of $19,304.45.

My below attempt isn’t working. How can I correct my code to make it work properly?

formatPrice function:

export function formatPrice(price: any) {
  const language = window.location.pathname.includes("/fr") ? "fr" : "en";
  const options = {
    style: "currency",
    currency: "CAD",
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  };

  return price.toLocaleString(language, options);
}

Usage:

<Td className="align-right reg-price">
    ${formatPrice(Number(equipment["regular-price"]?.text).toLocaleString())}
</Td>
<Td className="align-right sale-price">
    <strong>${formatPrice(Number(equipment["sale-price"]?.text).toLocaleString())}</strong>
</Td>

3D Model Not Appearing in React Three.js Component

I am working on a React component using Three.js to load 3D models. However, I am facing an issue where the 3D model is not appearing in the scene. I have implemented loaders for various file formats (gltf, obj, fbx, etc.), but the model does not show up when I upload a file.

'use client'

import React, { useRef } from 'react';
import * as THREE from '@react-three/fiber';

import { GLTFLoader } from 'three-gltf-loader';
import { OBJLoader } from 'three-obj-loader';
import { FBXLoader } from 'three-fbx-loader';
import { STLLoader } from 'three-stl-loader';
// A few more imports with this structure

const loadModel = (modelData, fileType) => {
    // UPGRADE: Make less DRY
    let loader = null;

    switch (fileType) {
        case 'gltf':
            loader = new GLTFLoader();
            loader.parse(modelData, '', (gltf) => {
                scene.add(gltf.scene);
            });
            break;
        // Allot more cases with this structure
        case 'json':
             loader = new JSONLoader();
            loader.parse(modelData, '', (json) => {
                scene.add(json.scene);
            });
            break;
        default:
            console.log('Not Compatible')
    }
    // TODO: Temporary path
    
    return loader;
}

const Model = () => {
  const fileInputRef = useRef(null); // Provide a default model path    
  const Scene = useRef();


  const handleFileChange = (event) => {
    const file = event.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const modelData = e.target.result;
        const fileType = file.name.split('.').pop().toLowerCase();
        loadModel(Scene.current, modelData, fileType);
      };
      reader.readAsDataURL(file);
    }
  };

  return (
    <div>
      <input type='file' name="model" onChange={handleFileChange} ref={fileInputRef} />
      <THREE.Canvas>
        <scene ref={Scene} />
        
        <ambientLight intensity={0.5} />
        <pointLight position={[10, 10, 10]} />
      </THREE.Canvas>
    </div>
  );
};

export default Model;

Details:
I have ensured that the necessary loaders are imported at the beginning of my file.
The file type is correctly determined and passed to the loadModel function.
I am using the Scene ref correctly when calling the loadModel function.
Potential Areas of Concern:
Loader initialization and usage.
Proper handling of file types.
Correct usage of the Scene ref.
Scene and camera configuration.

Error Messages: None But doesn’t display content

What I’ve Tried:

Confirming loader initialization.
Checking the file type handling.
Verifying the Scene ref usage.
Ensuring proper scene and camera configuration.

I would appreciate any insights or suggestions on what might be causing the 3D model not to appear in the scene. Are there any specific areas in my code that I should review or modify?

Is FFmpegAudioDecoder supposed to reinitialize upon append of new init segment

I am attempting to switch audio tracks but when switching the FFmpegAudioDecoder never reinitializes like it does with video tracks of differing resolutions. I am not certain if this is the intended behavior of FFmpegAudioDecoder and would love to learn more about the expected behavior.

When switching audio tracks I end up calling the following operations:

if sourceBuffer.getIsUpdate() {sourceBuffer.abort()}
sourceBuffer.remove(0-videoDuration)
initSegmentDataStream = fetch init segment of new audio representation
sourceBuffer.appendBuffer(initSegmentDataStream)

These are the Media tab messages from initial video load

ChunkDemuxer
Selected FFmpegAudioDecoder for audio decoding, config: codec: aac, profile: unknown, bytes_per_channel: 2, channel_layout: STEREO, channels: 2, samples_per_second: 48000, sample_format: Signed 16-bit, bytes_per_frame: 4, seek_preroll: 0us, codec_delay: 0, has extra data: false, encryption scheme: Unencrypted, discard decoder delay: false, target_output_channel_layout: STEREO, target_output_sample_format: Unknown sample format, has aac extra data: true
Cannot select DecryptingVideoDecoder for video decoding
Cannot select VDAVideoDecoder for video decoding
Cannot select VpxVideoDecoder for video decoding
Selected Dav1dVideoDecoder for video decoding, config: codec: av1, profile: av1 profile main, level: not available, alpha_mode: is_opaque, coded size: [1280,720], visible rect: [0,0,1280,720], natural size: [1280,720], has extra data: false, encryption scheme: Unencrypted, rotation: 0°, flipped: 0, color space: {primaries:BT709, transfer:BT709, matrix:BT709, range:LIMITED}
Dropping audio frame (DTS 0us PTS -105375us,-62709us) that is outside append window [0us,9223372036854775807us).
Dropping audio frame (DTS 42666us PTS -62708us,-20042us) that is outside append window [0us,9223372036854775807us).
Truncating audio buffer which overlaps append window start. PTS -20041us frame_end_timestamp 22625us append_window_start 0us
Effective playback rate changed from 0 to 1

For comparison this is what I get when appending the init segment of a different video resolution / track

video decoder config changed midstream, new config: codec: av1, profile: av1 profile main, level: not available, alpha_mode: is_opaque, coded size: [1920,1080], visible rect: [0,0,1920,1080], natural size: [1920,1080], has extra data: false, encryption scheme: Unencrypted, rotation: 0°, flipped: 0, color space: {primaries:BT709, transfer:BT709, matrix:BT709, range:LIMITED}

Chrome version: Version 119.0.6045.123 (Official Build)

When appending the new init segment of an audio track I was expecting the FFmpegAudioDecoder to be reinitialized like the Dav1dVideoDecoder does for video tracks

Regex to match any 2 or 3 digit number araund certain word but not directly followed by that word

str:

“There was Amy. Amy was 16 years old and she was 167 cm tall.
And also there was Jason. Jason was 18 years old and he was 185 cm tall”

Regex to match Amy’s age and height, but not to match Jason’s.

So:

16 - match 
167 - match 
18 - no match 
185 - no match

I thought about regex to search for d{2,3} and look-around word ‘Amy’ but I can’t figure it out. Also word ‘Amy’ can’t match.

If it can’t be done in single expression I would also love to see it in Java Script with extra logic.

jquery random image arrays inside divs

I have this website where when you refresh it will bring up a random image from multiple JS array inside multiple divs (each div has its own JS array with different images). The problem is that my code is only using the last declared JS array and uses the same 2 pictures for all the divs.

$('.random-image-container').each(function() {
  var container = $(this)
  $('<img class="random-image" src="' + images[Math.floor(Math.random() * images.length)] + '">').appendTo(container);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<article class="grid-item">
  <div class="random-image-container">
    <script>
      var images = ['IMG/1.jpg', 'IMG/2.jpg'];
    </script>
  </div>
</article>
<article class="grid-item">
  <div class="random-image-container">
    <script>
      var images = ['IMG/3.jpg', 'IMG/4.jpg'];
    </script>
  </div>
</article>
<article class="grid-item">
  <div class="random-image-container">
    <script>
      var images = ['IMG/5.jpg', 'IMG/6.jpg'];
    </script>
  </div>
</article>
<article class="grid-item">
  <div class="random-image-container">
    <script>
      var images = ['IMG/7.jpg', 'IMG/8.jpg'];
    </script>
  </div>
</article>

can someone help me with this ?

Nuxt3 testing problem with useLazyAsyncData using vitest

How do you test Nuxt 3 page with useLazyAsyncData? For example

<script setup lang="ts">
import { getData } from '@/api'
const { data, pending, error } = await useLazyAsyncData('test', getData);
</script>

<template>
<div v-if="error">error</div>
<div v-else-if="pending">loading...</div>
<div v-else>somepage data...</div>
<template>

I’m using vtest for vite, but solution for jest should work too, I guess.
Right now I’m stuck. The test is showing 0 error, but component not even rendering

Accessing Radio Button Values in DataTable with multiple page (Shiny)

I can’t access radio button values when they’re embedded in a data table in shiny with the paging = TRUE option. I base my code on this example : Radio Buttons in DT

This works well for the first page, but not for input on other pages.

Here is the code for the example :

library(shiny)
library(DT)

shinyApp(
  ui = fluidPage(
    title = 'Radio buttons in a table',
    DT::dataTableOutput('foo'),
    verbatimTextOutput('sel')
  ),
  server = function(input, output, session) {
    m = matrix(
      as.character(1:5), nrow = 12, ncol = 5, byrow = TRUE,
      dimnames = list(month.abb, LETTERS[1:5])
    )
    for (i in seq_len(nrow(m))) {
      m[i, ] = sprintf(
        '<input type="radio" name="%s" value="%s"/>',
        month.abb[i], m[i, ]
      )
    }
    m
    output$foo = DT::renderDataTable(
      m, escape = FALSE, selection = 'none', server = FALSE,
      options = list(dom = 'Bfrtip', 
                     paging = TRUE, 
                     pageLength = 6,
                     ordering = FALSE),
      callback = JS("table.rows().every(function(i, tab, row) {
          var $this = $(this.node());
          $this.attr('id', this.data()[0]);
          $this.addClass('shiny-input-radiogroup');
        });
        Shiny.unbindAll(table.table().node());
        Shiny.bindAll(table.table().node());")
    )
    output$sel = renderPrint({
      str(sapply(month.abb, function(i) input[[i]]))
    })
  }
)

In this example, I can’t access the values of the radio buttons for the months of ‘Jul’ to ‘Dec’.
In fact, I have a table with more than 100 rows, and I need to access the input values of the various pages.

How to correct the render output of my reactjs TreeGraph component

I’m having issues with getting my TreeGraph to render properly.

Issues:

  1. Lines go to the wrong location
  2. Circles Render on top of each other
  3. Spacing is wrong

Is there perhaps a free open source chart/tree library which will allow me to do this on a canvas, and allow me to make each circle clickable

Example Output (tree listed below)

enter image description here

Code and Samples

Tree Type

export default class Tree {
    details:any = {};
    children:Tree[] = [];

    constructor(_details:any, _children:Tree[]){
        this.details = _details;
        this.children = _children;
    }
}

Tree Data

let data = new Tree(
        { id: "XXXXXX1", name: "A", onClick: ()=>{ console.log("A")}},
        [
            new Tree({ id: "XXXXXX2", name: "B", onClick: ()=>{ console.log("B")}}, [
                new Tree({ id: "XXXXXX4", name: "D", onClick: ()=>{ console.log("D")}}, [])
            ]),
            new Tree({ id: "XXXXXX3", name: "C", onClick: ()=>{ console.log("C")}}, [
                new Tree({ id: "XXXXXX5", name: "E", onClick: ()=>{ console.log("E")}}, []),
                new Tree({ id: "XXXXXX6", name: "F", onClick: ()=>{ console.log("F")}}, []),
                new Tree({ id: "XXXXXX7", name: "G", onClick: ()=>{ console.log("G")}}, [])
            ]),
            new Tree({ id: "XXXXXX8", name: "H", onClick: ()=>{ console.log("H")}}, [
                new Tree({ id: "XXXXXX9", name: "I", onClick: ()=>{ console.log("I")}}, []),
                new Tree({ id: "XXXXX10", name: "J", onClick: ()=>{ console.log("J")}}, []),
                new Tree({ id: "XXXXX11", name: "K", onClick: ()=>{ console.log("K")}}, [])
            ]),
        ]
    );

Renderer Functional Component (ReactJS)


export default function TreeRenderer(props:any){
    // Props
    const { width, height, data, styleOverrides } = props;
    // States
    const [ canvasID, setCanvasID ] = useState<string>("");
    const canvasRef = useRef<any>(null);
    // Functions
    function getTreeWidth(root: Tree): number {
        const queue: Tree[] = [root];
        let maxWidth = 0;
        while (queue.length > 0) {
          const levelSize = queue.length;
          // Update the maximum width if the current level is wider
          maxWidth = Math.max(maxWidth, levelSize);
          for (let i = 0; i < levelSize; i++) {
            const node = queue.shift()!; // Non-null assertion for simplicity
            // Enqueue the children for the next level
            if (node.children) {
              queue.push(...node.children);
            }
          }
        }
        return maxWidth;
      }
    function getMaxChildrenCount(node: Tree): number {
        if (!node.children || node.children.length === 0) {
          return 0;
        }      
        let maxChildrenCount = node.children.length;
        for (const child of node.children) {
          const childMaxChildrenCount = getMaxChildrenCount(child);
          if (childMaxChildrenCount > maxChildrenCount) {
            maxChildrenCount = childMaxChildrenCount;
          }
        }      
        return maxChildrenCount;
      }
      // Handles Drawing the lines, and then returns the circles (just doing it like this so the lines are drawn under the circles)
      const drawParentAndChild = (
        context: any,
        parent: Tree,
        depth: number,
        sibling: number,
        parentX: number,
        parentY: number
      ): any[] => {
        let circles: any[] = [];
        let radius = 18;
        let basePaddingY = 18;
        let basePaddingX = 18;
      
        // Adjust spacing based on depth
        let paddingY = basePaddingY;// + depth * 10;
        let paddingX = basePaddingX;// + depth * 10;
      
        let y = depth * (2 * radius + paddingY) + paddingY;
        let x = sibling * (2 * radius + paddingX) + paddingX;
        let centerX = x + radius;
        let centerY = y + radius;
      
        // Draw Line to Parent
        if (depth >= 1) {
          context.beginPath();
          context.moveTo(centerX, centerY);
          context.lineTo(parentX, parentY);
          context.strokeStyle = '#1E1E1E';
          context.stroke();
          context.closePath();
        }
      
        // various stuff
        let fillColor = '';
        if (depth === 0 && sibling === 0) {
          fillColor = '#1E1E1E';
        } else if (parent.details.isActive ?? false) {
          fillColor = 'red';
        } else {
          fillColor = 'green';
        }
      
        // reusable font style
        const fontFamily = 'Poppins, sans-serif';
        const fontSize = 20;
        const fontWeight = 'bold';
      
        circles.push({
          a: centerX,
          b: centerY,
          c: radius,
          d: 0,
          e: 2 * Math.PI,
          f: false,
          g: fillColor,
          h: `${fontWeight} ${fontSize}px ${fontFamily}`,
          i: '#FFFFFF',
          j: parent.details.name,
          k: x + radius / 2 + 2,
          l: y + radius + 8,
        });
      
        // Draw Children into Array (only draw the lines)
        for (let i = 0; i < parent.children.length; i++) {
          let ret = drawParentAndChild(context, parent.children[i], depth + 1, sibling + i, centerX, centerY);
          circles.push(...(ret as any[]));
        }
      
        return circles;
      };
    // Effects
    useEffect(()=>{
        // if no data, don't render
        if(!data) return;
        // Acquire Canvas
        let canvas = canvasRef ? canvasRef.current : document.getElementById(canvasID);
        // Get Width and Height of Tree
        let tWidth = getTreeWidth(data);
        let tHeight = getMaxChildrenCount(data);
        // Calculate Sizes
        let maxWidth = tWidth;
        let maxHeight = tHeight;
        // Setup Canvas
        canvas.width = maxWidth * 2024;
        canvas.height = maxHeight * 2024;
        // Get Canvas Context
        var context = canvas.getContext('2d');
        // Clear Canvas
        context.fillStyle = '#FFF';
        context.fillRect(0, 0, maxWidth, maxHeight);
        // Generate Tree Lines and return circles to draw
        let circlesAndText = drawParentAndChild(context, data, 0, 0, 18, 18);
        for(let circle of circlesAndText){
            context.beginPath();
            context.arc(circle['a'], circle['b'], circle['c'], circle['d'], circle['e'], circle['f']);
            context.fillStyle = circle['g'];
            context.fill();
            context.lineWidth = 1;
            context.strokeStyle = '#1E1E1E';
            context.stroke();
            context.closePath();
            context.font = circle['h'];
            context.fillStyle = circle['i'];
            context.fillText(circle['j'], circle['k'], circle['l']);
        }
        // Loop through
        // TODO: Go through each circle here and create a click handler, based on the circle['a'] and circle['b']
    }, [data]);
    // Render
    return <canvas className='tree-renderer-element' ref={canvasRef} style={styleOverrides} id={canvasID} width={0} height={0}></canvas>
}

How can I sync the pagination with a filtering pipe in this Angular app?

I am working on a “Users app” with Angular and the Random User API.

In services/user.service.ts I fetch the users:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/internal/Observable';

@Injectable()
export class UserService {
  apiURL: string =
    'https://randomuser.me/api/?&results=60&inc=id,name,location,picture';

  constructor(private httpClient: HttpClient) {}

  public getUsers(): Observable<any[]> {
    return this.httpClient.get<any[]>(`${this.apiURL}`);
  }
}

I use the above service in the pagination-basic component:

import { Component } from '@angular/core';
import { UserService } from './services/user.service';
import { Countries } from './data/countries';

@Component({
  selector: 'ngbd-pagination-basic',
  styleUrls: ['./pagination-basic.css'],
  templateUrl: './pagination-basic.html',
  providers: [UserService],
})
export class NgbdPaginationBasic {
  public page: number = 1;
  public pageSize: number = 10;
  public totalRecords: number = 0;

  public users: any[] = [];
  public countries: any[] = [];
  public country: string = '';

  constructor(private userService: UserService) {}

  public getCountries() {
    this.countries = Countries;
  }

  public getUsers() {
    this.userService.getUsers().subscribe((response) => {
      this.users = response.results;
      this.totalRecords = this.users?.length;
    });
  }

  ngOnInit(): void {
    this.getCountries();
    this.getUsers();
  }
}

I display the users in the form of a table in pagination-basic.html:

<div class="container">
  <h1 class="display-4">Users</h1>

  <select [(ngModel)]="country" class="form-control my-2">
    <option selected value="">Filter by country</option>
    <option *ngFor="let c of countries" [value]="c.name">{{ c.name }}</option>
  </select>

  <div *ngIf="users?.length" class="card my-3">
    <div class="card-body p-0">
      <table class="m-0 table table-striped">
        <tr>
          <th>Name</th>
          <th>Country</th>
          <th>City</th>
        </tr>
        <tr
          *ngFor="let user of users | usersFilter: country | slice: (page - 1) * pageSize : (page-1) * pageSize + pageSize"
        >
          <td class="text-nowrap">
            {{ user.name.first }} {{ user.name.last }}
          </td>
          <td>{{user.location.country}}</td>
          <td>{{user.location.city}}</td>
        </tr>
      </table>
    </div>

    <div class="card-footer bg-white d-flex justify-content-center">
      <ngb-pagination
        size="sm"
        [pageSize]="pageSize"
        [collectionSize]="totalRecords"
        [(page)]="page"
        class="m-0"
      ></ngb-pagination>
    </div>
  </div>

  <p class="text-center" *ngIf="!users?.length">No users found! :(</p>
</div>

As can be observed, the results are paginated and filtered by country.

There is a StackBlitz with all the code.

The problem

When I filter the results by country, I get a number of results small enough that the number of pagination items should change, but it does not.

For example, I pick Canada and get 1 user. The pagination should have one item, yet it has two. The pagination and filter are not in sync.

Questions

  1. What am I doing wrong?
  2. What is the most reliable way to sync the pagination with the filter?

Add an option in Exporting Menu of amCharts 4 to average data

I’m trying to find a way to quickly average data either weekly or monthly using the Exporting Menu in amCharts 4. I made this codePen but it doesn’t work.

Can someone have a look to see what I am doing wrong?

The Exporting menu part looks like this:

chart.exporting.menu = new am4core.ExportMenu();
chart.exporting.menu.align = "right";
chart.exporting.menu.verticalAlign = "top";
chart.exporting.menu.items = [{
        "label": "<i class='fa fa-bars' ></i>",
        "menu": [
            { 
                "label": "Average",
                "menu": [
                    { "type": "custom", "label": "All", "options":
                        { "callback":
                            function() {
                                dateAxis.groupData = false;
                            }
                        }
                    },
                    { "type": "custom", "label": "Week", "options":
                        { "callback":
                            function() {
                                dateAxis.groupData = true;
                                lineSeries.groupFields.valueY = "average";
                                lineSeries.groupInterval = { timeUnit: "week", count: 1 };
                            }
                        }
                    },
                    { "type": "custom", "label": "Month", "options":
                        { "callback":
                            function() {
                                dateAxis.groupData = true;
                                lineSeries.groupFields.valueY = "average";
                                lineSeries.groupInterval = { timeUnit: "month", count: 1 };
                            }
                        }
                    }
                ]
            }

        ]
}];

Thanks a lot for your time.

Error: redirect count exceeded with many fetch and Promise.all() in a firebase callable function

When I’m doing this inside a firebase callable function:

    for (const origin of originList) {
      for (const destiny of destinyList) {
        // mount the url

        const respPromise = fetch(url)
        .then((resp) => resp.json())
        .then((data) => {
          // manipulate a big JSON (2000 lines or more each one)
        })

        fetchPromises.push(respPromise)
      }
    }

    await Promise.all(fetchPromises)

Both list can have more the 10 registers, so the fetch will run hundreds of time.
It’s very unstable, sometimes I get the right result, but most of time I get:

Unhandled error TypeError: fetch failed
...
cause: Error: redirect count exceeded
      at makeNetworkError (node:internal/deps/undici/undici:4801:35)
      at httpRedirectFetch (node:internal/deps/undici/undici:9659:16)
      at httpFetch (node:internal/deps/undici/undici:9632:28)
      at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
      at async schemeFetch (node:internal/deps/undici/undici:9535:18)
      at async node:internal/deps/undici/undici:9409:20
      at async mainFetch (node:internal/deps/undici/undici:9399:20)
      at async httpFetch (node:internal/deps/undici/undici:9632:22)
      at async schemeFetch (node:internal/deps/undici/undici:9535:18)
      at async node:internal/deps/undici/undici:9409:20

I don’t know if it’s a pure javascript code and I can fi but refactoring the code or firebase can’t call so many fetch’s inside a callable function.

Any suggestions?

Github pages não mostra imagens

olá, fiz meu primeiro deploy de um site em React no github pages, o site ta funcionando normalmente, mas somente as imagens que não estam aparecendo, se inspecionar a pagina da um erro 404 e verifiquei os diretorios para ver se estavam todos coretos e não encontrei problemas. Quem souber agradeço a ajuda.

as imagens sao exibidas em um componente chamado CardProject, que as são buscadas no diretorio src/assets/img/certificado. O caminho que eu estou usando para buscar as imagens é “../../src/assets/img/certificados/nomeDaImg.png”

repositorio: https://github.com/EduardoPinheiroMiranda/Portifolio
site: https://eduardopinheiromiranda.github.io/Portifolio/

Tic-Tac-Toe with minimax can be beaten in middle row or middle column. How to fix it so it becomes unbeatable?

Part of a course, I tried to implement minimax in a game of Tic-Tac-Toe in which the human player plays first (marker ‘X’, adds 1 to array) and the computer plays second (marker ‘0’, adds -1 to array). The minimax sort of works, in the sense that I cannot win the game except if I play middle row or middle column.

I created a codepen https://codepen.io/aadriaan/pen/ExrvjxM and the relevant code for the Human Player vs Minimax starts at line 103. These are the functions where I think the problem is:

function playUnbeatableAI(choice, player, array, cells) {
    board = array;
    gameboardCells = cells;
    player = 1;
    // player vs. easy AI game
    // human clicks + computer pushes in random available cell
    // get available cells
    gameboardCells.forEach(cell => {
      cell.addEventListener('click', (event) => {
        const index = event.target.dataset.index;
        let arrayColumn = index % 3;
        let arrayRow = (index - arrayColumn) / 3;
        if (board[arrayRow][arrayColumn] === 0 && gameOver === false) {
          board[arrayRow][arrayColumn] = player;
          renderUI.addMarker(board);
          checkWinningCombinations(board);
          const aiMove = getBestMove(board);
          console.log(aiMove);
          board[aiMove.row][aiMove.col] = -1; // Set the AI move on the board
          //renderUI.addMarker(board);
          //checkWinningCombinations(board);
        } else {
          return
        }
        // checkWinningCombinations(board) to see if human player wins
        // so that computer does not play after human won
        /*
        checkWinningCombinations(board);
        if (board[arrayRow][arrayColumn] === 0 && gameOver === false) {
          const aiMove = getBestMove(board);
          board[arrayRow][arrayColumn] = aiMove;
          console.log(aiMove);
        } else {
          return
        }
        */
        renderUI.addMarker(board);
        checkWinningCombinations(board);
      });
    });
  }

  function minimax(board, depth, isMaximizing) {
    // Evaluate the board and return a score if the game is over
    const result = evaluate(board);
    const HUMAN_PLAYER = 1;
    const AI_PLAYER = -1;
    if (result !== 0) {
      return result;
    }
    // If it's the AI's turn (maximizing player)
    if (isMaximizing) {
      let bestScore = -Infinity;
      for (let row = 0; row < 3; row++) {
        for (let col = 0; col < 3; col++) {
          // If the cell is empty
          if (board[row][col] === 0) {
            board[row][col] = HUMAN_PLAYER;
            const score = minimax(board, depth + 1, false);
            board[row][col] = 0; // Undo the move
            bestScore = Math.max(score, bestScore);
          }
        }
      }
      return bestScore;
    } else {
      // If it's the human's turn (minimizing player)
      let bestScore = Infinity;
      for (let row = 0; row < 3; row++) {
        for (let col = 0; col < 3; col++) {
          // If the cell is empty
          if (board[row][col] === 0) {
            board[row][col] = AI_PLAYER;
            const score = minimax(board, depth + 1, true);
            board[row][col] = 0; // Undo the move
            bestScore = Math.min(score, bestScore);
          }
        }
      }
      return bestScore;
    }
  }

  function getBestMove(board) {
    let bestMove = { row: -1, col: -1 };
    let bestScore = -Infinity;
    const HUMAN_PLAYER = 1;
    const AI_PLAYER = -1;
    for (let row = 0; row < 3; row++) {
      for (let col = 0; col < 3; col++) {
        if (board[row][col] === 0 && gameOver === false) {
          board[row][col] = AI_PLAYER;
          const score = minimax(board, 0, true);
          board[row][col] = 0; // Undo the move

          if (score > bestScore) {
            bestScore = score;
            bestMove = { row, col };
          }
        }
      }
    }
    return bestMove;
  }

  function evaluate(board) {
    for (let row = 0; row < 3; row++) {
      if (board[row][0] === board[row][1] && board[row][1] === board[row][2]) {
        if (board[row][0] === 1)
          return -10;
        else if (board[row][0] === -1)
          return +10;
      }
    }
    for (let col = 0; col < 3; col++) {
      if (board[0][col] === board[1][col] && board[1][col] === board[2][col]) {
        if (board[0][col] === 1)
          return -10;
        else if (board[0][col] === -1)
          return +10;
      }
    }
    if (board[0][0] === board[1][1] && board[1][1] === board[2][2]) {
      if (board[0][0] === 1)
        return -10;
      else if (board[0][0] === -1)
        return +10;
    }
    if (board[0][2] === board[1][1] && board[1][1] === board[2][0]) {
      if (board[0][2] === 1)
        return -10;
      else if (board[0][2] === -1)
        return +10;
    }
    return 0;
  }

Unable to Access Custom Property in Fastify Request Object

I’m facing an issue with Fastify where I’m unable to access a custom property I’ve set in the request object. Here’s a minimal example of my Fastify server setup:

const app = Fastify();

app.use(async (req, res, next) => {
  req.test = "test2"; // Set test property
  next();
});

// Other middleware and registrations...

app.register(mercurius, {
  // Mercurius options...
  context: (req, res) => buildContext({
    res,
    req,
    dataSources: req.dataSources,
  }),
  // Other options...
});

I’ve set req.test to “test2” in my middleware, but when I try to access it inside my buildContext function, it’s undefined:

export default async ({ res, req, dataSources }) => {
  console.log(req.test); // This logs undefined
}

I expect req.test to have the value “test2” when accessed within buildContext, but it’s not working as expected. Can someone help me understand why this property is undefined in my context function?

Additional Information:

I’m using Fastify with Middie.
Any insights or suggestions would be greatly appreciated. Thank you!

When I log the req object instead of req.test, I see that test property is present inside the req object, but it’s not in the root of the object but it’s inside of something from fastify that I don’t understand and that I don’t know how to access:

[Symbol(fastify.RequestPayloadStream)]: IncomingMessage {