How can I have collision detection between array and object so they cannot pass through each other?

I am new to coding, and especially new to trying to make a game. This is for a class project. Using JavaScript, HTML, and CSS, I am trying to make a game in which, with limited visibility, the user must search for the exit (a white rectangle on the edges of the screen) while avoiding ghosts and interior walls (for the sake of ease of use, the canvas is completely visible so you can see what I am referring to). I am having trouble creating collision detection between the randomly generated interior walls and the player so that the player is unable to pass through these walls.

To be honest I am quite new to all of this, so I do not have a lot of trial and error experience since it is built off of guesses. I was trying to use if statements to detect collision before moving and repeat it for each side (see javascript lines of code 174-199). So essentially using an if statement for each side of the array shape, and if the circle is moving in the direction of collision, they won’t be able to move. This hasn’t worked though obviously, and I am feeling quite lost as to the correct step to accomplish the desired effect. My code is posted here:

var canvas;
var ctx;
var w = window.innerWidth;
var h = window.innerHeight;
var startScreen = document.querySelector("#startScreen");
var allGhosts = []
var allWalls = []
var oneDegree = 2 * Math.PI / 360;
var generate = true;
var win = false;
var lose = false;
var o1 = {
  x: w / 2,
  y: h / 2,
  w: w * 2,
  h: h * 2,
  r: w / 6,
  c: 200,
  a: 1,
  distance: 4,
  angle: rand(360),
  changeX: randn(5),
  changeY: randn(5),
}
var o2 = {
  x: rand(w),
  y: rand(h),
  w: rand(50) + 10,
  h: rand(50) + 10,
  r: w / 6,
  c: 200,
  a: 0.75,
  distance: rand(10),
  angle: rand(360),
}
var o3 = {
  x: w / 2,
  y: h / 2,
  r: 10,
  a: 1,
  speed: 7,
}
var o4 = {
  x: w / 2,
  y: h / 2,
  w: w * 2,
  h: h * 2,
  r: w / 1.90,
  c: 200,
  a: 1,
}
var exitLoc = {
  x: parseInt(Math.random() * 2) ? 0 : 1500,
  y: rand(680),
  w: 10,
  h: 50,
}

if (win != true) {
  winScreen.style.display = 'none';
}
if (lose != true) {
  loseScreen.style.display = 'none';
}
window.addEventListener("keydown", ev => {
  if (ev.keyCode === 32 && generate === true) {
    startScreen.style.display = 'none';

    generate = false;


    createGhosts(30, allGhosts);
    createGhosts(50, allWalls);
    setUpCanvas();
    animationLoop();
    document.onkeydown = move;

    function animationLoop() {
      clear();
      extWalls();
      collisionStop(o3);
      collisionStop(o4);
      exit(exitLoc);
      for (var i = 0; i < allGhosts.length; i++) {
        ghosts(allGhosts[i]);
        bounce(allGhosts[i]);
        forward(allGhosts[i]);
        updateData(o1);
      }
      for (var i = 0; i < allWalls.length; i++) {
        walls(allWalls[i]);
      }
      // circle(o4);
      player(o3);
      collisionWin(exitLoc, o3);
      collisionLose(o3, allGhosts);
      if (lose != true && win != true) {
        requestAnimationFrame(animationLoop);
      }
    }
  }
})


function collisionWin(obj1, obj2) {
  var differencex = Math.abs(obj1.x - obj2.x);
  var differencey = Math.abs(obj1.y - obj2.y);
  var hdif = Math.sqrt((differencex * differencex) + (differencey * differencey));
  if (hdif < obj1.w + obj2.r) {
    clear();
    rect();
    win = true;
  }
  if (win === true) {
    winScreen.style.display = 'block';
    loseScreen.style.display = 'none'
  }
}

function rect() {
  x = 0;
  y = 0;
  ctx.beginPath();
  ctx.moveTo(x, y);
  ctx.lineTo(x + w, y);
  ctx.lineTo(x + w, y + h);
  ctx.lineTo(x, y + h);
  ctx.closePath();
  ctx.fillStyle = "black";
  ctx.fill();
}

function collisionLose(obj, array) {
  for (var i = 0; i < array.length; i++) {
    if (obj != array[i]) {
      collisionGhost(obj, array[i]);
    }
  }
}

function collisionGhost(obj, array) {
  var differencex = Math.abs(obj.x - array.x);
  var differencey = Math.abs(obj.y - array.y);
  var hd = Math.sqrt((differencex * differencex) + (differencey * differencey));
  if (hd < obj.r + array.r) {
    clear();
    rect();
    lose = true;
  }
  if (lose === true) {
    loseScreen.style.display = 'block'
  }
}

function collisionStop(o) {
  if (o.x > w - 50) {
    o.x = w - 50;
  }
  // right of screen
  if (o.x < 15) {
    o.x = 15;
  }
  // left of screen
  if (o.y > h - 50) {
    o.y = h - 50;
  }
  // bottom of screen
  if (o.y < 15) {
    o.y = 15;
  }
  // top of screen
}

function collisionWall(obj, array) {
  for (var i = 0; i < array.length; i++) {
    if (obj != array[i]) {
      collisionIntWall(obj, array[i]);
    }
  }
}

function collisionIntWall(obj, array) {
  if (obj.x + obj.r > array.x - array.w / 2 && move.keyCode == 37) {
    obj.speed = 0
  }
  // right side of obj1 > left side of array AND
  // if(obj.x - obj.r    < array.x + array.w/2 && move() == 39){
  //     obj.speed = 0
  // }   
  // // left side of obj1 < right side of array AND
  // if(obj.y + obj.r    > array.y - array.h/2 && move() == 40){
  //     obj.speed = 0
  // }   
  // // bottom of obj1 > top of array AND
  // if(obj.y - obj.r    < array.y + array.h/2 && move() == 38){
  //     obj.speed = 0
  // }      
  // top of obj1 < bottom of array
}

function createGhosts(num, array) {
  for (var i = 0; i < num; i++) {
    array.push({
      x: rand(w),
      y: rand(h),
      w: rand(50) + 10,
      h: rand(50) + 10,
      r: 10,
      c: 0,
      a: 1,
      distance: rand(1) + 0.5,
      angle: rand(360),
    })
  }
}

function bounce(o) {
  if (o.x > w) {
    o.x = w - 5;
    o.angle += 180 - 2 * o.angle;
  }
  if (o.x < 0) {
    o.x = 5;
    o.angle += 180 - 2 * o.angle;
  }
  if (o.y > h) {
    o.y = h - 5;
    o.angle += 360 - 2 * o.angle;
  }
  if (o.y < 0) {
    o.y = 5;
    o.angle += 360 - 2 * o.angle;
  }
}

function updateData(o) {
  o.x += o.changeX;
  o.y += o.changeY;
}

function forward(o) {
  var cx;
  var cy;
  cx = o.distance * Math.cos(o.angle * oneDegree);
  cy = o.distance * Math.sin(o.angle * oneDegree);
  o.x += cx;
  o.y += cy;
}

function circle(o) {
  ctx.beginPath();
  ctx.arc(o.x, o.y, o.r, 0, 2 * Math.PI);
  ctx.strokeStyle = "black";
  ctx.lineWidth = 2000;
  ctx.stroke();
}

function player(o) {
  ctx.beginPath();
  ctx.arc(o.x, o.y, o.r, 0, 2 * Math.PI);
  ctx.fillStyle = "white";
  ctx.fill();
}

function ghosts(o) {
  ctx.beginPath();
  ctx.arc(o.x, o.y, o.r, 0, 2 * Math.PI);
  ctx.fillStyle = "rgb(189, 9, 9)";
  ctx.fill();
}

function walls(o) {
  o.x = o.x - o.w / 2;
  o.y = o.y - o.h / 2;
  ctx.beginPath();
  ctx.moveTo(o.x, o.y);
  ctx.lineTo(o.x + o.w, o.y);
  ctx.lineTo(o.x + o.w, o.y + o.h);
  ctx.lineTo(o.x, o.y + o.h);
  ctx.closePath();
  ctx.fillStyle = "grey";
  ctx.fill();
  o.x = o.x + o.w / 2;
  o.y = o.y + o.h / 2;
}

function exit(o) {
  o.x = o.x - o.w / 2;
  o.y = o.y - o.h / 2;
  ctx.beginPath();
  ctx.moveTo(o.x, o.y);
  ctx.lineTo(o.x + o.w, o.y);
  ctx.lineTo(o.x + o.w, o.y + o.h);
  ctx.lineTo(o.x, o.y + o.h);
  ctx.closePath();
  ctx.fillStyle = "white";
  ctx.fill();
  o.x = o.x + o.w / 2;
  o.y = o.y + o.h / 2;
}

function extWalls() {
  ctx.beginPath();
  ctx.moveTo(0, 0);
  ctx.lineTo(0, 680);
  ctx.lineTo(1500, 680);
  ctx.lineTo(1500, 0);
  ctx.closePath();
  ctx.strokeStyle = "grey";
  ctx.lineWidth = 10;
  ctx.stroke();
}

function clear() {
  ctx.clearRect(0, 0, w, h);
}

function randn(r) {
  var result = Math.random() * r - r / 2;
  return result;
}

function randi(r) {
  var result = Math.floor(Math.random() * r);
  return result;
}

function rand(r) {
  var result = Math.random() * r;
  return result;
}

function setUpCanvas() {
  canvas = document.querySelector("#myCanvas");
  ctx = canvas.getContext("2d");
  canvas.width = 1500;
  canvas.height = 680;
}

function move(e) {
  if (e.keyCode == 37) {
    o3.x -= o3.speed;
    o4.x -= o3.speed;
  }
  if (e.keyCode == 39) {
    o3.x += o3.speed;
    o4.x += o3.speed;
  }
  if (e.keyCode == 40) {
    o3.y += o3.speed;
    o4.y += o3.speed;
  }
  if (e.keyCode == 38) {
    o3.y -= o3.speed;
    o4.y -= o3.speed;
  }

}
#myCanvas {
  background-color: rgb(76, 76, 76);
}

h1 {
  color: rgb(189, 9, 9);
  text-align: center;
  font-family: Creepster, monospace;
}

h6 {
  color: rgb(189, 9, 9);
  text-align: center;
  font-family: Creepster, monospace;
}

p {
  color: rgb(189, 9, 9);
  text-align: center;
  font-family: Creepster, monospace;
}

body {
  display: flex;
  justify-content: center;
  background-color: black;
}

#startBox {
  position: fixed;
  width: 600px;
  height: 600px;
  box-shadow: 0 1px 64px rgb(189, 9, 9);
  background-color: black;
  left: 50%;
  transform: translateX(-50%);
}

#startBox h1 {
  font-size: 100px;
}

#startBox p {
  width: 90%;
  margin: auto;
  font-size: 25px;
}

#winBox {
  position: fixed;
  width: 600px;
  height: 600px;
  box-shadow: 0 1px 64px rgb(189, 9, 9);
  background-color: black;
  left: 50%;
  transform: translateX(-50%);
}

#winBox h1 {
  font-size: 85px;
}

#winBox p {
  width: 90%;
  margin: auto;
  font-size: 25px;
}

#loseBox {
  position: fixed;
  width: 600px;
  height: 600px;
  box-shadow: 0 1px 64px rgb(189, 9, 9);
  background-color: black;
  left: 50%;
  transform: translateX(-50%);
}

#loseBox h1 {
  font-size: 100px;
}

#loseBox p {
  width: 90%;
  margin: auto;
  font-size: 25px;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ghost house</title>
  <link rel="stylesheet" type="text/css" href="test.css">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Creepster&display=swap" rel="stylesheet">

</head>

<body>
  <div id="startScreen">
    <div id="startBox">
      <h1>ghost house</h1>
      <p>The lights went out… <br> Your flashlight can only last so long. <br> Find your way out of the haunted house but beware, ghosts haunt these halls. <br><br> They do not take kindly to visitors... <br><br> use the arrow keys to control the player
        and search for a way out. the exit looks like a white rectangle somewhere along the exterior walls of the home. press the spacebar to start</p>
    </div>
  </div>


  <div id="winScreen">
    <div id="winBox">
      <h1>congratulations</h1>
      <p>you found your way out of the ghost house <br> refresh the page and try to escape again <br><br><br><br> if you dare</p>
    </div>
  </div>


  <div id="loseScreen">
    <div id="loseBox">
      <h1>game over</h1>
      <p>looks like there will be another ghost haunting this house <br> refresh the page and try to escape again <br><br><br><br> if you dare</p>
    </div>
  </div>


  <div id="canvasContainer">
    <canvas id="myCanvas"></canvas>
  </div>



  <script src="test.js"></script>
</body>

</html>

The issue code in question starts from lines 174-199. Thank you for taking the time to read through this and help me out! I really appreciate it 🙂

React-native Dragable Components

i am trying to achieve this kind of feature

A component hidden inside until the item is dragged

the box on top of this image is supposed to be a draggable component from the top to the bottom till the component is full visible, it is also suppose to be animated i am try to make a feature like this with react-native-draggable library so i my code i am using a small box to try it but all to no avail, this is my code:

import { SafeAreaView } from "react-native"
import { StatusBar } from "react-native"
import { Text } from "react-native"
import { Component } from "react"
import { View } from "react-native"
import { StyleSheet } from "react-native"
import { Dimensions } from "react-native"
import Icons from 'react-native-vector-icons/MaterialIcons';
import { useEffect } from "react"
import { useIsFocused } from "@react-navigation/native"
import { Swipeable } from 'react-native-gesture-handler';
import { Animated } from "react-native"
import Icon from "react-native-vector-icons/MaterialIcons"
import { ScrollView } from "react-native"
import { TouchableOpacity } from "react-native"
import Draggable from "react-native-draggable"
import { useState } from "react"

function FocusAwareStatusBar(props) {
  const isFocused = useIsFocused();

  return isFocused ? <StatusBar {...props} /> : null;
}

const Trading = () => {
  const [yPosition, setYPosition] = useState(10);
  const [animatedValue, setAnimatedValue] = useState(new Animated.Value(0));

  const onDragRelease = (e, gestureState) => {
    if (gestureState.moveY > 100) {
      Animated.timing(animatedValue, {
        toValue: 1,
        duration: 200,
        useNativeDriver: true,
      }).start(() => {
        setYPosition(10);
      });
    } else {
      Animated.timing(animatedValue, {
        toValue: 0,
        duration: 200,
        useNativeDriver: true,
      }).start(() => {
        setYPosition(10);
      });
    }
  };

  const animatedStyle = {
    transform: [
      {
        translateY: animatedValue.interpolate({
          inputRange: [0, 1],
          outputRange: [0, Dimensions.get("window").height / 2 - 70],
        }),
      },
    ],
  };

 return(
  <>
    <FocusAwareStatusBar barStyle={"light-content"} backgroundColor="#360061" translucent={false}/>
    <Animated.View style={[styles.draggableContainer, animatedStyle]}>
      <Draggable
        x={100}
        y={yPosition}
        onDragRelease={onDragRelease}
      >
        <View style={{width: 150, height: 150, backgroundColor: 'purple'}} />
      </Draggable>
    </Animated.View>
  </>
 )
}

const styles = StyleSheet.create({
  draggableContainer: {
    position: 'absolute',
    top: Dimensions.get("window").height / 2 - 75,
    left: Dimensions.get("window").width / 2 - 75,
    zIndex: 1,
    width: Dimensions.get("window").width,
    height: Dimensions.get("window").height / 2 + 75,
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default Trading;

i discovered in my cold that the box still drags to left and right, i don’t want that, i have tried react-native-interactable but its not working. please ignore my spellings incase there are some typos and just render your help thanks in advance.

function is being called automatically in JS [duplicate]

I was trying to create a parameterized function using JS, I started code with a window.onload=()=>{},
and the syntax for my function is function name(arg){}.

I want to call this function on a click event. so my statement goes btn.onclick=function_name(arg); . but, the function gets called as soon as the page loads, without a click. What can i do to solve this problem?

window.onload = () => {
  var btn .....

  btn.onclick = func(arg..);

  function func(arg){
  }
}

My calculator doesn’t show me zero as a result [closed]

Help, I created a calculator with html, javascript and css, but when the result is zero it doesn’t show me the number zero, ex: 5-5=5, 8×0=8. Help please. I don’t understand much about programming, I made the calculator based on a video I saw on youtube, so if you can be specific and explicit with the explanation I would appreciate it.

This is the first thing I try.

Stuck trying to play a WAV/PCM audio stream from a DLink IP Camera with HTML / JS. It’s the file header! :(

Ive been learning and programming a site in html/js that captures and displays online streams from ip cameras and all is working great, except the audio on this one. I’m stuck. I havent been able to figure it out. Ive done everything I could to make it work but this just goes above my level of understanding on how to read it to play it.

I found this Q&A InitAudio function that definitely goes in the right direction, but unfortunately I couldnt make it work.
Using it, I can see the stream starts downloading kb but the html5 audio player doesnt start, I believe, as it does not read the audio file correctly.

In essence, I want to play an audio stream in WAV/PCM (G711) raw format that comes from an online D-Link IP Camera DCS-2230 with JS. Stream URL is:

http://IP:PORT/audio/ACAS.cgi?profileid=1

I read the manual that explains how the specific audio stream works.

This is what it indicates:

ACAS audio stream explained

This is the specific header file/structure:

**Advanced ip-Camera Stream Audio (ACS) header**

**ACS Audio header**
typedef struct _ACS_AudioHeader
{
unsigned long ulHdrID; //Header ID
unsigned long ulHdrLength;
unsigned long ulDataLength;
unsigned long ulSequenceNumber;
unsigned long ulTimeSec;
unsigned long ulTimeUSec;
unsigned long ulDataCheckSum;
unsigned short usFormat;
unsigned short usChannels;
unsigned short usSampleRate;
unsigned short usSampleBits;
unsigned long ulReserved;
}ACS_AudioHeader, *PACS_AudioHeader;

Description:
The byte order of this header is little-endian

**ulHdrID**: Special id for identifying ACS header. For audio: the value of this id is 0xF6010000 (since our header is in
little-endian so the byte array of this id is ‟00 00 01 F6‟).
**ulHdrLength**: Header length. (32 bytes in current version)
**ulDataLength**: Payload data length.
**ulSequenceNumber**: Sequence number.
**ulTimeSec**: Time stamp in sec since 1970/01/01 00:00.
**ulTimeUSec**: Microsecond part of time stamp
**ulDataCheckSum**: Store last 4 bytes of payload data.
**usFormat**: Audio data format. The possible value:
AFMT_MS_ADPCM: 0
AFMT_MU_LAW: 1
AFMT_A_LAW: 2
AFMT_IMA_ADPCM: 4
AFMT_U8: 8
AFMT_S16_LE: 0x10 /* Little endian signed 16 */
AFMT_S16_BE: 0x20 /* Big endian signed 16 */
AFMT_S8: 0x40
AFMT_U16_LE: 0x80 /* Little endian U16 */
AFMT_U16_BE: 0x100 /* Big endian U16 */
AFMT_MPEG: 0x200 /* MPEG (2) audio */
AFMT_AC3: 0x400
AFMT_AMR: 0x800
**usChannels**: Audio channels number: mono(1) or stereo(2).
**usSampleRate**: Sample rate.
**usSampleBits**: Bits count per sample.
**ulReserved**: Reserved.

This is the code so far

<script>
async function initAudio() {
// specify your file and its audio properties

const url = 'http://IP:PORT/audio/ACAS.cgi?profileid=1'
const sampleRate = 8000
const numChannels = 1 // mono or stereo
const isFloat = false  // integer or floating point

const buffer = await (await fetch(url, {method: 'GET', headers: {'Content-Type': 'audio/ACAS','Authorization': 'Basic YWRtaW46cGFzc3dvcmQ='}
})).arrayBuffer()

// create WAV header
const [type, format] = isFloat ? [Float32Array, 3] : [Uint8Array, 1]
const wavHeader = new Uint8Array(buildWaveHeader({
numFrames: buffer.byteLength / type.BYTES_PER_ELEMENT,
bytesPerSample: type.BYTES_PER_ELEMENT,
sampleRate,
numChannels,
format
}))

// create WAV file with header and downloaded PCM audio
const wavBytes = new Uint8Array(wavHeader.length + buffer.byteLength)
wavBytes.set(wavHeader, 0)
wavBytes.set(new Uint8Array(buffer), wavHeader.length)

// show audio player
const audio = document.getElementById('myLiveAudio');
const blob = new Blob([wavBytes], { type: 'audio/wav' });
audio.src = URL.createObjectURL(blob);
audio.play();

}

// **I dont know how to build the proper ACAS header**
// adapted from https://gist.github.com/also/900023
function buildWaveHeader(opts) {
const numFrames =      opts.numFrames;
const numChannels =    opts.numChannels || 2;
const sampleRate =     opts.sampleRate || 44100;
const bytesPerSample = opts.bytesPerSample || 2;
const format =         opts.format

const blockAlign = numChannels * bytesPerSample;
const byteRate = sampleRate * blockAlign;
const dataSize = numFrames * blockAlign;

const buffer = new ArrayBuffer(44);
const dv = new DataView(buffer);

let p = 0;

function writeString(s) {
for (let i = 0; i < s.length; i++) {
dv.setUint8(p + i, s.charCodeAt(i));
}
p += s.length;
}

function writeUint32(d) {
dv.setUint32(p, d, true);
p += 4;
}

function writeUint16(d) {
dv.setUint16(p, d, true);
p += 2;
}

writeString('RIFF');              // ChunkID
writeUint32(dataSize + 36);       // ChunkSize
writeString('WAVE');              // Format
writeString('fmt ');              // Subchunk1ID
writeUint32(16);                  // Subchunk1Size
writeUint16(format);              // AudioFormat
writeUint16(numChannels);         // NumChannels
writeUint32(sampleRate);          // SampleRate
writeUint32(byteRate);            // ByteRate
writeUint16(blockAlign);          // BlockAlign
writeUint16(bytesPerSample * 8);  // BitsPerSample
writeString('data');              // Subchunk2ID
writeUint32(dataSize);            // Subchunk2Size

return buffer;
}
</script>

<audio type="audio/wav" preload ="none" volume="1" id="myLiveAudio" controls></audio>

<span class="speaker" id="speaker" alt="Live sound" title="Live sound" onclick="initAudio();">&#128360</span>

Thanks for reading!!

Sending data to an API using javascript [duplicate]

const sql = require('mssql');
const jwt = require('jsonwebtoken');
const axios = require('axios');

// create a configuration object for the database connection
const config = {
    user: 'leo',
    password: 'Leocoronel24',
    server:'192.168.13.33',
    database:'TKMANAGER',
    port: 1433,
    options: {
        encrypt: false,
        trustServerCertificate: true
    }
};

// create a function to connect to the database and retrieve data
async function getData() {
  try {
    // connect to the database
    await sql.connect(config);
    console.log('Connected to the database');

    // create a request object to retrieve data
    let sqlquery = `SELECT TOP 1 Employeenum, DTRDATE, COMPANYID, FUNCTIONKEY, 
    CASE WHEN FunctionKey = 1 THEN DTRTIMEIN ELSE DTRTIMEOUT END AS TRANSACTIONTIME,
    [NAME], SeqID
    FROM viewDTR1 
    WHERE DTRDATE BETWEEN '2023-03-01' AND '2023-03-15'`;

    //sqlquery = `SELECT TOP 1 * FROM viewDTR1`;
    //sqlquery = `SELECT * FROM NGAC_AUTHLOG1 WHERE IndexKey = 8203154`;

    const result = await sql.query(sqlquery);

    const payload = {
      user: config.user,
      password: config.password,
      isAdmin: false
    };

    const token = jwt.sign(payload, 'avada-kedavra');

    //console.log(token);

    let entries = result.recordset.map(row => ({
      dtrdate:row.DTRDATE,
      datetime:row.TRANSACTIONTIME,
      type:row.FUNCTIONKEY,
      location:row.NAME,
      company:row.COMPANYID,
      cardno:row.Employeenum,
      ipaddress:'192.168.1.1'
    }));

    let data = { entries: entries };

    //console.log(result.recordset)

    console.log(JSON.stringify(data));

    const response = await axios.post('http://dev.megaworldcorp.com:8000/tkserve/uptk.php', {
      token: token,
      data:{
        entries
      }
       
    });

    console.log(response.data);

  } catch (error) {
    console.log(error);
  } finally {
    sql.close();
    console.log('Disconnected from the database');
  }
}

getData();
`

I’m getting this error when I send data to an API using POST method:

Warning: Undefined array key “entries” in /var/www/html/tkserve/uptk.php on line 53

Warning: Trying to access array offset on value of type null in /var/www/html/tkserve/uptk.php on line 17

Warning: Trying to access array offset on value of type null in /var/www/html/tkserve/uptk.php on line 18

Warning: Trying to access array offset on value of type null in /var/www/html/tkserve/uptk.php on line 19

Warning: Trying to access array offset on value of type null in /var/www/html/tkserve/uptk.php on line 20

Warning: Trying to access array offset on value of type null in /var/www/html/tkserve/uptk.php on line 21

Warning: Trying to access array offset on value of type null in /var/www/html/tkserve/uptk.php on line 22

Warning: Trying to access array offset on value of type null in /var/www/html/tkserve/uptk.php on line 23

Warning: Cannot modify header information – headers already sent by (output started at /var/www/html/tkserve/uptk.php:53) in /var/www/html/tkserve/uptk.php on line 58
{“result”:”Error: All fields are required.”}

Quiz consists of two sections

I created a code that represents a quiz consists of two sections, and print the result of the user after answering, but when thee user clicks on the options of section two, his answers of section 1 disappear.
here’s the code:

<!DOCTYPE html>
<html lang="ar">
<head>
  <title>Quiz</title>
  <link rel="Stylesheet" href="form1.css"> 
</head>
<body>
  <form id="quiz-form">
    <h3>القسم الوجداني</h3>
    <div>
      <p>السؤال الأول</p>
      <input type="radio" name="q1" value="الإجابة الصحيحة" required>
      <label for="q1">الإجابة الصحيحة</label><br>
      <input type="radio" name="q1" value="الإجابة الخاطئة">
      <label for="q1">إجابة خاطئة</label><br>
      <input type="radio" name="q1" value="الإجابة الخاطئة2">
      <label for="q1">إجابة خاطئة2</label><br>
    </div>
    <div>
      <p>السؤال الثاني</p>
      <input type="radio" name="q2" value="الإجابة الصحيحة" required>
      <label for="q2">الإجابة الصحيحة</label><br>
      <input type="radio" name="q2" value="الإجابة الخاطئة">
      <label for="q2">الإجابة الخاطئة 1</label><br>
      <input type="radio" name="q2" value="الإجابة الخاطئة2">
      <label for="q2">الإجابة الخاطئة 2</label><br>
    </div>
    <div>
      <p>السؤال الثالث</p>
      <input type="radio" name="q3" value="الإجابة الصحيحة" required>
      <label for="q3">الإجابة الصحيحة</label><br>
      <input type="radio" name="q3" value="الإجابة الخاطئة1">
      <label for="q3">الإجابة الخاطئة1</label><br>
      <input type="radio" name="q3" value="الإجابة الخاطئة2">
      <label for="q3">الإجابة الخاطئة2</label><br>
    </div>
    
    <!--section two -->
    <h3>القسم المعرفي</h3>
    <div>
      <p> السؤال الأول في القسم المعرفي</p>
      <input type="radio" name="q1" value="الإجابة الصحيحة" required>
      <label for="q1">الإجابة الصحيحة</label><br>
      <input type="radio" name="q1" value="الإجابة الخاطئة">
      <label for="q1">إجابة خاطئة</label><br>
      <input type="radio" name="q1" value="الإجابة الخاطئة2">
      <label for="q1">إجابة خاطئة2</label><br>
    </div>

    <div>
      <p>السؤال الثاني في القسم المعرفي</p>
      <input type="radio" name="q2" value="الإجابة الصحيحة" required>
      <label for="q2">الإجابة الصحيحة</label><br>
      <input type="radio" name="q2" value="الإجابة الخاطئة">
      <label for="q2">الإجابة الخاطئة 1</label><br>
      <input type="radio" name="q2" value="الإجابة الخاطئة2">
      <label for="q2">الإجابة الخاطئة 2</label><br>
    </div>

    <div>
      <p>السؤال الثالث في القسم المعرفي</p>
      <input type="radio" name="q3" value="الإجابة الصحيحة" required>
      <label for="q3">الإجابة الصحيحة</label><br>
      <input type="radio" name="q3" value="الإجابة الخاطئة1">
      <label for="q3">الإجابة الخاطئة1</label><br>
      <input type="radio" name="q3" value="الإجابة الخاطئة2">
      <label for="q3">الإجابة الخاطئة2</label><br>
    </div>
    <button type="submit">Submit</button>
  </form>
  <div id="score"></div> <!-- scoring of section 1  -->
  <div id="score2"></div> <!-- Scoring of section 2 -->
  <script>
    // Define the questions and their respective correct answers
    // Define the questions and their respective correct answers
const quizQuestions = [
  { question: "What is the capital of France?", answers: ["الإجابة الصحيحة"], correctIndex: 0 },
  { question: "What is the largest continent?", answers: ["الإجابة الصحيحة"], correctIndex: 0 },
  { question: "What is the smallest country in the world?", answers: ["الإجابة الصحيحة"], correctIndex: 0 }
];

const quizQuestions2 = [
  { question: "What is the capital of France?", answers: ["الإجابة الصحيحة"], correctIndex: 0 },
  { question: "What is the largest continent?", answers: ["الإجابة الصحيحة"], correctIndex: 0 },
  { question: "What is the smallest country in the world?", answers: ["الإجابة الصحيحة"], correctIndex: 0 }
];
// Create an array to store the user's answers
let userAnswers = [];
let userAnswers2 = [];

// Define a function to check the user's answers and calculate the score
function calculateScore() {
  let score = 0;
  for (let i = 0; i < quizQuestions.length; i++) {
    if (userAnswers[i] === quizQuestions[i].answers[quizQuestions[i].correctIndex]) {
      score++;
    }
  }
  const percentage = (score / quizQuestions.length) * 100;
  return percentage.toFixed(2);
}
// calculate answers of section 2
function calculateScore2() {
  let score2 = 0;
  for (let k = 0; k < quizQuestions2.length; k++) {
    if (userAnswers2[k] === quizQuestions2[k].answers[quizQuestions2[k].correctIndex]) {
      score2++;
    }
  }
  const percentage2 = (score2 / quizQuestions2.length) * 100;
  return percentage2.toFixed(2);
}``your text``
// Use DOM manipulation to display the score to the user
const quizForm = document.getElementById("quiz-form");`your text`
quizForm.addEventListener("submit", function(event) {
  event.preventDefault();
  const answerInputs = document.querySelectorAll("input[type='radio']:checked");
  answerInputs.forEach(function(input) {`your text`
    userAnswers.push(input.value);
  });`your text`
  const percentage = calculateScore();
  const percentage2 = calculateScore2();
  const scoreDisplay = document.getElementById("score");
  const scoreDisplay2 = document.getElementById("score2");
  console.log(scoreDisplay);
  console.log(scoreDisplay2);
  scoreDisplay.innerHTML = `درجتك في القسم الوجداني ${percentage}% (${Math.floor(percentage / 100 * quizQuestions.length)} إجابات من  ${quizQuestions.length} صحيحة).`;
  scoreDisplay2.innerHTML = `درجتك في القسم المعرفي ${percentage2}% (${Math.floor(percentage2 / 100 * quizQuestions2.length)} إجابات من  ${quizQuestions2.length} صحيحة).`;
});
</script>
</body>
</html>

I want the user to enter his answers in the two section, and the marks printed for the two sections individually.

Remove Prettier round brackets around arrow function statements

I’ve written an arrow function and for some reason Prettier thinks it’s nice to add some random brackets around the function statement. I like Prettier, but this is bugging the hell out of me due to OCD.

my code:

const write = (id, content) =>
  document.getElementById(id).innerHTML = content;

after Prettier decided to make it uglier:

const write = (id, content) =>
  (document.getElementById(id).innerHTML = content);

I couldn’t find anything in the extension settings that removes it, is there a way or am I doomed?

How do I export data from a fetch call to another js file?

I am novice web developer working on a project for my portfolio. I have a get request from an api in a file called data.js. I am having trouble logging the response from the fetch call although I can see the response object when I log the call variable in data.js and when I log the function variable in index.js. How could I access the response object and export it for use in index.js? Thanks!

data.js

function getMatchingStocks(search) {
    var xhrGetMatchingStocks = new XMLHttpRequest();

    xhrGetMatchingStocks.open('GET', `https://www.alphavantage.co/query?function=SYMBOL_SEARCH&keywords=${search}&apikey=XXXXXXXXXXXXXXXXX`);
    xhrGetMatchingStocks.responseType = 'json';
    xhrGetMatchingStocks.send()

    console.log(xhrGetMatchingStocks.response)
    
    return xhrGetMatchingStocks
  }

export { getMatchingStocks }

index.js

import { getMatchingStocks } from "../js/data.js"

function findBestMatches() {
    
    var search = "apple"
    var bestMatches = getMatchingStocks(search)

    console.log(bestMatches)

}

findBestMatches()

get http //localhost/ 500 (internal server error) laravel

Trying to ‘get’ the value from local database, but it doesn’t work.

create.blade.php ajax script

<script>
    $('#viajes').on('change', function() {
        
            var opcionSeleccionada = this.value;
            $.ajax({
                url: '/admin/viajes/' + opcionSeleccionada,
                type: 'GET',
                dataType: 'json',
                success: function(data) {
                    console.log(data);
                    document.getElementById('dia1').value = data.dia1;
                    document.getElementById('salida').value = data.salida;
                    document.getElementById('observacion').value = '';
                    document.getElementById('dia2').value = data.dia2;
                    document.getElementById('llegada').value = data.llegada;
                    document.getElementById('observacion2').value = '';
                },
                error: function(xhr, textStatus, error) {
                    console.error('Error en la petición AJAX: ' + error);
                    alert('Ocurrió un error al obtener los datos del viaje seleccionado. Por favor, intenta nuevamente más tarde.');
                }
            });
        });
</script>

Route

    Route::get('viajes/{id}', [DashboardController::class, 'getInfo'])
        ->middleware('auth:admin')
        ->name('create3');  

Controller

    public function getInfo($id)
    {      
        $viaje_inicial = ViajeInicial::find($id);
       
        if ($viaje_inicial) {
            // Construye la respuesta HTTP con los datos del viaje
            return response()->json([
                'success' => true,
                'data' => $viaje_inicial
            ]);
        } else {
            // Si no se encontró el viaje, devuelve una respuesta de error
            return response()->json([
                'success' => false,
                'message' => 'El viaje no fue encontrado.'
            ], 404);
        }
    }

It seems to me that the route is correct, however I get this:
enter image description here

How can i export/import an ES module with a certain folder path?

I have created a React library, and i export all of my modules in a single .js file:

import { Component } from './components/Component';

export { Component };

And then i import it like:

import { Component } from 'my-library';

But what if i want to import it like:

import { Component } from 'my-library/components';

How can i achieve that?

How to apply a texture to an imported GLTF model in three.js?

I am currently tring to map a texture in three.js on a imported GLTF model. I tried the texture on a cube and the result is what I want, but when I try to apply the same texture to the imported model, the texture doesn’t seem to apply and there is only a change in color without any of the texture’s details :
picture
.You can see on this picture that at the bottom, the cube has more details than the vest.

Here is the code for the cube :

const textureLoader = new THREE.TextureLoader();
const tilesBaseColor = textureLoader.load('Fabric_Knitted_006_basecolor.jpg');
const plane2 = new THREE.Mesh(new THREE.BoxGeometry(3,3,3),
new THREE.MeshStandardMaterial(
  {
    map: tilesBaseColor,
  }
));
plane2.position.y = 3;
plane2.rotation.x = 0;
scene.add(plane2);

Here is the code for the vest :

const textureLoader2 = new THREE.TextureLoader();
const newTexture2 = textureLoader2.load('Fabric_Knitted_006_basecolor.jpg');
newTexture2.flipY = false;
const gltfLoader = new GLTFLoader();
gltfLoader.load('prom_suit/scene.gltf', (gltf) => {
  gltf.scene.scale.set(0.1*gltf.scene.scale.x, 0.1*gltf.scene.scale.y,0.1*gltf.scene.scale.z);
  const model = gltf.scene;
  const mesh = gltf.scene.getObjectByName('Object_212');
  mesh.material.map = newTexture2;
  mesh.material.needsUpdate = true;
  scene.add(model);

Thanks in advance

The code for the vest does make a change, since the color turns into the color of the texture, but the details don’t seem to apply.

using javascript list .contains in th:checked – thymeleaf html

I am trying to set the th:checked attribute of a checkbox to checked or unchecked, depending if it was checked previously before the page reload. I have a javascript function setPreChecked(dropdown) that already adds the prechecked options to a list but thymeleaf doesn’t seem to allow me to do something like this:

th:checked="${setPreChecked(dropdownName).contains(dropdownName) ? 'checked': ''}"

is there another way to use javascript functions in thymeleaf th:checked to determine if it’s checked or not?

In Monaco Editor, how to get the actual value from a Token?

I used monaco.editor.tokenize and received a result of token[][].

var tokens = monaco.editor.tokenize(text, "myLanguage");

I but the token only contains properties of language, offset and type. I would like to know how can I get the actual value of each token? Or is there any other ways of find the values of tokenized tokens?

I looked around the documentaiton of Monaco but I don’t find any way that will help.

Don’t load HTML template on first load

I have a basic HTML template that is populated by cards through a search bar given some conditions. This works fine, the only problem is that on first load all the cards are shown and I want none shown until the conditions are met.

This is my code: https://jsfiddle.net/barkwegn/6/

HTML

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <script src="script.js" defer></script>
    <title>Document</title>
  </head>

  <body>
    <div class="search-wrapper">
      <input type="search" id="search"  placeholder="Search the catalogue" data-search>
    </div>
    <div class="user-cards" data-user-cards-container></div>
    <template data-user-template>
      <div class="card">
        <a href="https://www.url.com/#">
          <div class="header" data-header></div>
        </a>
        <div class="body" data-body></div>
      </div>
    </template>
  </body>

Javascript

const userCardTemplate = document.querySelector("[data-user-template]")
const userCardContainer = document.querySelector("[data-user-cards-container]")
const searchInput = document.querySelector("[data-search]")

let users = []

searchInput.addEventListener("input", e => {

  const value = e.target.value.toLowerCase()
  const xy = value.split(' ')

  users.forEach(user => {

    if (parseFloat(value.length) < 3) {
      user.element.classList.toggle("hide", true)
    } else {
      var distance = Math.sqrt(
        Math.pow(parseFloat(xy[0]) - parseFloat(user.x), 2) +
        Math.pow(parseFloat(xy[1]) - parseFloat(user.y), 2))
      const isVisible =
        user.name.toLowerCase().includes(value) || distance <= 10
      user.element.classList.toggle("hide", !isVisible)
    }
  })
})

fetch("https://ucc.ar/_clusters/test.json")
  .then(res => res.json())
  .then(data => {
    users = data.map(user => {
      const card = userCardTemplate.content.cloneNode(true).children[0]
      const header = card.querySelector("[data-header]")
      const body = card.querySelector("[data-body]")
      header.textContent = user.name
      body.textContent = user.company
      userCardContainer.append(card)
      return {
        name: user.name,
        x: user.x,
        y: user.y,
        element: card
      }
    })
  })

CSS

.search-wrapper {
  display: flex;
  flex-direction: column;
  gap: .25rem;
}

input {
  width: 80%;
  margin: 0 auto;
  display: block;
  padding: 12px 20px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  font-size: 18px;
  background-color: #ffffff;
}

.user-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: .25rem;
  margin-top: 1rem;
}

.card {
  border: 1px solid black;
  background-color: white;
  padding: .5rem;
  text-align: center;
}

.card > .header {
  margin-bottom: .25rem;
}

.card > .body {
  font-size: .8rem;
  color: #777;
  font-weight: bold;
}

.hide {
  display: none;
}