Unable to pass values from one component to a table component in ReactJS application

I just want to transfer the data from one component to a table component. So after selecting the option from the dropdown menu, it should reflect all the details of that selected option inside the table. I have made two components:

Devdropdown.jsx:

import React, { useState, useEffect, useMemo } from "react";
import Tables from "./Tables";

const Devdropdown = () => {
  const [devices, setDevices] = useState([{}]);
  const [selected, setSelected] = useState();
  const url = "http://localhost:3000/devices";

  useEffect(() => {
    async function getDevices() {
      const response = await fetch(url);
      const body = await response.json();
      setDevices(body.data);
    }
    getDevices();
  }, []);

  const handleChange = (e) => {
    e.preventDefault();
    setSelected(e.target.value);
  };

  const uniqueDeviceIds = useMemo(
    () => Array.from(new Set(devices.map((device) => device.device_id))),
    [devices]
  );

  console.log(devices);
  return (
    <div>
      <h1>Aircraft {selected}</h1>
      <select
        value={selected}
        onChange={handleChange}
        placeholder="select an option"
      >
        {devices
          ? uniqueDeviceIds.map((deviceId) => (
              <option key={deviceId}>{deviceId}</option>
            ))
          : null}
      </select>
      <Tables data={devices[selected]} />
    </div>
  );
};

export default Devdropdown;

Tables.jsx:

import React from "react";

const Tables = (props) => {
  return (
    <div>
      <table>
        <tr>
          <th>Timestamp</th>
          <th>Location</th>
        </tr>
        <tr>
          <td>{props.data}</td>
          <td>{props.data}</td>
        </tr>
      </table>
    </div>
  );
};

export default Tables;

I just want to reflect the timsetamp and location features of the selected element , inside the table. Below is the screenshot of the devices object where I want timestamp and location attributes inside the table component.

enter image description here

Thanks and regards

typeorm throws a bson error in next.js app

I am working on adding typeorm into my Next.js app. however even though i am using the mysql2 driver and 5 data sources I cant seem to get rid of the bson error of:

./node_modules/typeorm/browser/driver/mongodb/bson.typings.js
Module parse failed: Export 'BSON' is not defined (1:9)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> export { BSON };
| 
| //# sourceMappingURL=bson.typings.js.map

Here is the main data source i am trying to use:

export const MI_Website = new DataSource({
    type: "mysql",
    host: process.env.BD_HOST as string,
    // port: process.env.DB_PORT || 3306,
    port: parseInt(process.env.DB_PORT as string) || 3306,
    username: process.env.DB_USERNAME as string,
    password: process.env.DB_PASSWORD as string,
    database: process.env.DB_DATABASE1 as string,
    entities: [__dirname + "/entity/website/*{.jsx,.tsx,.js,.ts}"],
    synchronize: true,
})

Help would be greatly appreciated. Dispite searching I have not found any fixes for this problem just yet.

How can I add quizzes to my Sphinx website?

I want to be able to create very simple single choice and multiple choice quizzes for my Sphinx website that uses the book theme. When researching I found that Sphinx has an extension for Quizdown and even though it is good, I want to try to make my own that fits more of what I exactly want (simpler style, and can display code blocks as quizdown for sphinx is very poor at doing so). I figured there is a way I can make my own directive but I am pretty new to RST I am not sure how to approach making my own quiz for Sphinx. My question is how can I create quizzes that are like quizdown for Sphinx using my own RST and possible Javascript?

SvelteKit keeping page data between pages

Is it possible to do the following:

Given a route such as /foo/[slug] with +page.js in it to load some data based on the slug, can the data be kept when navigating to /foo/[slug]/bar and available in the +page.svelte? The context of this is that there is some file being loaded to render on /foo/[slug] and that same file is used on /foo/[slug]/bar, so having the file preloaded is ideal. This approach would also require the file being loaded if /foo/[slug]/bar is visited first. I believe that load functions perform dependency checking. Reading through the docs, especially under the section about running the parent load function, it seems like this should be possible, but I can’t quite figure it out.

Some approaches that would work are to use stores, or to use the layouts option, but is there a simpler approach?

I’ve tried getting the page data on the nested page directly, but it results in an empty object instead of the content from the /foo/[slug] page, which suggests that the data is not being loaded properly.

Not possible to access ref’s function in the parent component: Typescript + React

I have written a wrapper that basically exposes a ref to the parent component. When I am trying to use the ref using typescript it throws the following error property does not exist on type. This is how I exposing the ref

export interface IType{
   name: string;
   age: number;
}

export type TypeRef = MutableRefObject<{ getCurrentType: () => IType }>;

Basically in the parent , I am trying to use it this way

const typeRef = useRef<TypeRef>();

// Somewhere in the code
const testFunc = () => {
  // below line throws Property 'getCurrentType' does not exist on type 'TypeRef'.ts(2339)
  typeRef?.current?.getCurrentType();
}

How can I access this getType() with proper type definitions? Basically this ref would return me a function that returns the current type

NextJS 13 middleware rewrite does not working properly on POST method

I wrote NextJS middleware that rewrites request to other internal server

import {NextRequest, NextResponse, URLPattern} from "next/server";
import {endpoint} from "@/utils";

export const config = {
    matcher: "/api/:path*"
}

const pattern = new URLPattern({pathname: "/api/:path*"})

export async function middleware(req: NextRequest) {

    const result = pattern.exec(req.url)

    console.log(result)
    if (result) {
        const path = result.pathname.groups.path

        return NextResponse.rewrite(`${endpoint}/${path}`)
    }
}

this code works for GET method but does not for POST method(internal server doesn’t receive request body)

when I wrote rewrite in next.config.js it worked

async rewrites() {
    return [
        {
            source: "/api/:path*",
            destination: `${process.env.API_ENDPOINT}/:path*`,
        },
    ]
},

How can I get it work using NextJS middleware?

I need to use NextJS middleware to append additional headers to request and that next.config.js method does not work either when I create middleware function(even if that function does nothing at all)

How to set JSON request body in JMETER variable

In my JMETER – Perfroemcne script,I have a JSON request body same request body first send for x-signature genration then send orignal request with x-signature both have differnt API end point one for x-signature genration oter for orignal call.

JSON Request:

Let requestBody = {
  "id": ${U_id},
  "username": "${U_username}",
  "firstName": "${U_firstName}",
  "lastName": "${U_lastName}",
  "email": "${U_email}",
  "password": "${U_password}",
  "phone": "${U_phone}",
  "userStatus": 1
}

vars.put("my_request",requestBody);

Following error found in Jmeter Logs:

2023-04-16 08:19:31,394 ERROR o.a.j.m.JSR223PreProcessor: Problem in JSR223 script, JSR223 PreProcessor
javax.script.ScriptException: <eval>:1:4 Expected ; but found requestBody
let requestBody ={
    ^ in <eval> at line number 1 at column number 4
    at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:477) ~[jdk.scripting.nashorn:?]
    at jdk.nashorn.api.scripting.NashornScriptEngine.asCompiledScript(NashornScriptEngine.java:503) ~[jdk.scripting.nashorn:?]
    at jdk.nashorn.api.scripting.NashornScriptEngine.compile(NashornScriptEngine.java:189) ~[jdk.scripting.nashorn:?]
    at org.apache.jmeter.util.JSR223TestElement.processFileOrScript(JSR223TestElement.java:211) ~[ApacheJMeter_core.jar:5.5]
    at org.apache.jmeter.modifiers.JSR223PreProcessor.process(JSR223PreProcessor.java:45) ~[ApacheJMeter_components.jar:5.5]
    at org.apache.jmeter.threads.JMeterThread.runPreProcessors(JMeterThread.java:978) ~[ApacheJMeter_core.jar:?]
    at org.apache.jmeter.threads.JMeterThread.executeSamplePackage(JMeterThread.java:561) ~[ApacheJMeter_core.jar:?]
    at org.apache.jmeter.threads.JMeterThread.processSampler(JMeterThread.java:501) ~[ApacheJMeter_core.jar:?]
    at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:268) ~[ApacheJMeter_core.jar:?]
    at java.lang.Thread.run(Thread.java:834) ~[?:?]

I tried above code but we got error.Can any bosy help me in this.

Save request body in one Jmeter variable and first use for x-signature then for orignal call.
one more this we set JSON body date form other Jmeter variables.

Issue with setting value to ‘true’ in event listener

I have a piece of Javascript that includes an event listener for a keypress event. When the f key is pressed and certain conditions are met (such as distance being less than 5 and npc.talkedTo being falsy), I want to trigger a dialogue and set the value of an element with ID xb1TalkedTo to true. However, the value of xb1TalkedTo doesn’t seem to be updating as expected.

Here’s a simplified version of the code:

function handleInterest(event, npc) {
    if (event.key == 'f' && distance < 5 && !npc.talkedTo) {
        triggerDiablogue(currentDialogue);
        let xb1TalkedTo = document.querySelector('#xb1TalkedTo');
        xb1TalkedTo.value = true;
    }
   }

How do I take values from a radio button and display it using chart.js?

I’m trying to make a Mario kart calculator. I feel like I almost got it. but I can’t seem to get it to work. Essentially its supposed to calculate the stats and display them on a bar chart. This is the error I get, ReferenceError: getSelectedRadioValue is not definedhttps://dea30f85-b4db-45de-86bc-4dd63141dd32.id.repl.co/script.js:36.

<h1>Mario Kart 8 Calculator</h1>
  <div>
    <label for="character">Character:</label>
    <input type="radio" id="character0" name="character" value="0" checked>
    <label for="character0">Mario</label>
    <input type="radio" id="character1" name="character" value="1">
    <label for="character1">Luigi</label>
    <!-- Add more character options here -->
  </div>
  <div>
    <label for="body">Body:</label>
    <input type="radio" id="body0" name="body" value="0" checked>
    <label for="body0">Standard</label>
    <input type="radio" id="body1" name="body" value="1">
    <label for="body1">Pipe Frame</label>
    <!-- Add more body options here -->
  </div>
  <div>
    <label for="glider">Glider:</label>
    <input type="radio" id="glider0" name="glider" value="0" checked>
    <label for="glider0">Super Glider</label>
    <input type="radio" id="glider1" name="glider" value="1">
    <label for="glider1">Cloud Glider</label>
    <!-- Add more glider options here -->
  </div>
  <div>
    <label for="wheels">Wheels:</label>
    <input type="radio" id="wheels0" name="wheels" value="0" checked>
    <label for="wheels0">Standard</label>
    <input type="radio" id="wheels1" name="wheels" value="1">
    <label for="wheels1">Roller</label>
    <!-- Add more wheels options here -->
  </div>
  <button id="calculateBtn">Calculate</button>
  <canvas id="chartCanvas"></canvas>

and here is the js

// Define an object to store the stats for each character, body, glider, and wheels
var stats = {
  characters: [
    { name: 'Mario', miniTurbo: 3, acceleration: 3, speed: 4, handling: 3 },
    { name: 'Luigi', miniTurbo: 3, acceleration: 3, speed: 4, handling: 3 }
    // Add more characters here with their respective stats
  ],
  bodies: [
    { name: 'Standard', miniTurbo: 0, acceleration: 0, speed: 0, handling: 0 },
    { name: 'Pipe Frame', miniTurbo: 0, acceleration: 1, speed: 0, handling: 0 }
    // Add more bodies here with their respective stats
  ],
  gliders: [
    { name: 'Super Glider', miniTurbo: 0, acceleration: 0, speed: 0, handling: 0 },
    { name: 'Cloud Glider', miniTurbo: 1, acceleration: 0, speed: 0, handling: 0 }
    // Add more gliders here with their respective stats
  ],
  wheels: [
    { name: 'Standard', miniTurbo: 0, acceleration: 0, speed: 0, handling: 0 },
    { name: 'Roller', miniTurbo: 0, acceleration: 1, speed: 0, handling: 0 },
    { name: 'Test', miniTurbo: 0, acceleration: 0, speed: 1, handling: 0 }
    // Add more wheels here with their respective stats
  ]
};

// Get the DOM elements for the radio inputs and chart canvas
var characterRadios = document.getElementsByName('character');
var bodyRadios = document.getElementsByName('body');
var gliderRadios = document.getElementsByName('glider');
var wheelsRadios = document.getElementsByName('wheels');
var chartCanvas = document.getElementById('chartCanvas');

// Add event listener to the calculate button
document.getElementById('calculateBtn').addEventListener('click', function() {
  // Get the selected character, body, glider, and wheels
  var character = stats.characters[getSelectedRadioValue(characterRadios)];
  var body = stats.bodies[getSelectedRadioValue(bodyRadios)];
  var glider = stats.gliders[getSelectedRadioValue(gliderRadios)];
  var wheels = stats.wheels[getSelectedRadioValue(wheelsRadios)];

  // Calculate the total stats by summing up the selected options
  var totalMiniTurbo = character.miniTurbo + body.miniTurbo + glider.miniTurbo + wheels.miniTurbo;
  var totalAcceleration = character.acceleration + body.acceleration + glider.acceleration + wheels.acceleration;
  var totalSpeed = character.speed + body.speed + glider.speed + wheels.speed;
  var totalHandling = character.handling + body.handling + glider.handling + wheels.handling;

  // Create a chart using Chart.js library
  var chart = new Chart(chartCanvas, {
    type: 'bar',
    data: {
      labels: ['Mini Turbo', 'Acceleration', 'Speed', 'Handling'],
      datasets: [{
        label: 'Total Stats',
        data: [totalMiniTurbo, totalAcceleration, totalSpeed, totalHandling],
        backgroundColor: 'rgba(75, 192, 192, 0.2)',
        borderColor: 'rgba(75, 192, 192, 0.2)',}]
    }
  })
})

How to tell if a point is visible on current OpenLayers map

Hi I’m trying to figure out if a given point is currently visible on my map. I’m using open layers 7 and have a simple map with a marker on it. User can move both the map and the marker independently. Every time the either the map or the marker are moved there as an output updated that shows the lon/lat of both the center of the map and the marker position. I would also like to output whether or not the marker is actually on the currently visible map.

I’m not sure how to go about doing this although i suspect its about capturing the boundaries of the mapview somehow.

Here’s the code I have so far and a link to the JSFiddle.

var london = [-0.1276474, 51.507321899999994];
var isOnMap = true;  

document.getElementById('marker').innerHTML = london[0].toFixed(5) + ", " + london[1].toFixed(5);
document.getElementById('center').innerHTML = london[0].toFixed(5) + ", " + london[1].toFixed(5);
    const baseMapTile = new ol.layer.Tile({
            source: new ol.source.OSM(),
            visible: true,
            title: 'OSMStandard'
    });
    
    
    const marker = new ol.Feature({
        geometry: new ol.geom.Point(ol.proj.fromLonLat(london)),
        name: 'Somewhere near Nottingham',
    });
    
    
    const map = new ol.Map({
    view: new ol.View({
            
      center: (ol.proj.fromLonLat(london)),
      zoom: 15,
    }),
        layers: [
            baseMapTile,
            new ol.layer.Vector({
                source: new ol.source.Vector({
                    features: [marker]
                }),
                style: new ol.style.Style({
                    image: new ol.style.Icon({
                        anchor: [0.5, 46],
                        anchorXUnits: 'fraction',
                        anchorYUnits: 'pixels',
                        src: 'https://openlayers.org/en/latest/examples/data/icon.png'
                    })
                })
            })
        ],
    target: 'map'
    
  });

var translate = new ol.interaction.Translate({
    features: new ol.Collection([marker])
});

map.addInteraction(translate);

translate.on('translating', function (evt) {
        var lonlat = ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326');
                document.getElementById("marker").innerHTML = lonlat[0].toFixed(5) + ", " + lonlat[1].toFixed(5);               
                
                //check here to see if marker is still visible on map and update output
                
});

map.getView().on(['change:center', 'change:resolution', 'change:rotation'], function() {
    var center = ol.proj.transform(map.getView().getCenter(), 'EPSG:3857', 'EPSG:4326');
                
            document.getElementById("center").innerHTML = center[0].toFixed(5) + ", " + center[1].toFixed(5);
            //check here to see if marker is still visible on map and update output
});
#map {
  width: 300px;
  height: 300px;
  border: 1px solid black;
  padding: 5px;
  float: left;
}

#info {
  width: calc(100% - 330px);
  margin-left: 5px;
  padding: 5px;
  height: 100px;
  border: 1px solid black;
  float: left;
}

.info h2 {
  font-size: small;
  text-decoration: underline;
  font-weight: 600;
  margin: 0 0 10px 0;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/ol.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/ol.js"></script>

<div id="map" class="map"></div>
<div id="info" class="info">
  <h2>Map Info Output</h2>
  Center: <span id=center></span><br> Marker: <span id=marker></span><br>
  <span id=update>*update if the marker is on the map or not here.</span>
</div>

Any help is always appreciated. Thanks.

HTTPOnly Cookie isn’t send with Ajax request

When my user logs in I set an HTTPonly cookie access_token. I have a middleware auth that verifies the value of the cookie access_token to authorize or not the user.
It works well when request are made directly from the server side and the cookies is successfully retrieved by the middleware.

But when I call some routes on my app (same domain and same port) via Ajax, the middleware doesn’t find the cookie access_token (so refuses the connection) and on the Web inspector, I don’t see any cookie send with the request.

It seems that Ajax request should send all copies (even HTTPonly cookies), but I don’t know why it doesn’t with my app.
Do you have any idea why ?

Thank you a lot !
Louie

Loosing Access to navigator.gpu in Popup Window

As part of a small personal project I would like to render a scene using webgpu and display it on a canvas on a popped out window. I have been slowly learning webgpu and have no trouble setting up a basic scene. However, when I move from the original window that loads my HTML file to that one the one that I create as a pop-up, I seem to loose access to the navigator.gpu, and thus am unable to render anything.

Is there any way that I can access navigator.gpu in a popped out window or am a stuck? Reading around I can’t find any source that explicitly tells me that I can’t have acess in a pop-up. Here is a really basic HTML file illustrating my problem: the first console.log(navigator.gpu) occurs in the pop-up window, and the second in the main window.

<!DOCTYPE html>
<script>
let my_popup_html = 
`
<script>
console.log(navigator.gpu) // undefined
</script>  
<!DOCTYPE html>
<html>
<body>
I am a popup window
<body>
</html>
    `
    let my_popup = document.addEventListener(`DOMContentLoaded`,async () => window.open(URL.createObjectURL(new Blob([my_popup_html],{ type:"text/html"})),"Test","directories=false","popup=true","status=false","toolbar=false","menubar=false","replace=false"));
    console.log(navigator.gpu) // is defined and I can use to access the webgpu API
</script>
<html>
</html>

I am running the latest chromium for context. I suspect there is something going on with security and the fact that my pop-up html is sourced from a blob. However, I am not certain that this is the problem, and am unsure of how to proceed in that case anyhow.
Can anyone offer concrete info on to what the problem is and if it is possible to work around this issue?

Cannot use import statement outside a module for npm package

I am trying to use the npm package editly.

import Editly from "editly"

However when i try to import it i get this error.

SyntaxError: Cannot use import statement outside a module
at internalCompileFunction (node:internal/vm:73:18)
at wrapSafe (node:internal/modules/cjs/loader:1176:20)
at Module._compile (node:internal/modules/cjs/loader:1218:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
at Module.load (node:internal/modules/cjs/loader:1117:32)
at Module._load (node:internal/modules/cjs/loader:958:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47

All the solutions i have viewed say to add “type”: “module” to package.json but it already has it

find the smallest value of array [closed]

You are given an array of numbers arr as an argument. You need to implement the function findSmallest which will return the smallest number in the array.
Hint 1: Iterate through all the elements using a loop. Keep track of the smallest number.
Hint 2: Compare the current element in the loop to the smallest found so far and update the smallest if required.
Hint 3: Length of the array will be always greater than or equal to 1.
Sample Input 1
4, 2, 3, 1, 5
Sample Output 1
1
Explanation
1 is the smallest number amongst 4, 2, 3, 1, 5. Thus the returned number is 1.enter image description here

How do I build interactive chess web app?

I’m new to programming. I want to build a web page or web app on which users can play or interact with fractions or parts of chess games.

The functionality would include buttons to move pieces, which would be “visible” on screen. The “annotations” for each move would be visible as users click and play along.

Any tips? or ideas? about fundamentals on getting started would be greatly appreciated.

I’m new to programming so looking for a little bit of orientation or guidance from more experienced folk.