Issues with my player and enemy not being drawn on to the canvas, any ideas?

This is the only issue im having currently with my scripts, im not sure if its the drawing order but ive tried to rearrange my drawing. If y’all can help me so that I can fix this issue that would be greatly appreciated .


function gameloop() {
  // Clear the canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Draw background elements
// Set timeout to hide symbols after 5 seconds
  bg.draw();
  cloudBig.update(ctx);
  cloudBig2.update(ctx);

  backgroundLevel1.draw();

  water.draw();
  waterSmall.draw();
  waterSmallTwo.draw();
  palmTree.draw();
  palmTree2.draw();
  palmTreeSide.draw();
  palmTreeSide2.draw();

  // Draw the p1Symbol

  playerUpdate();
  p1Symbol.draw(); // Update game objects
  p1Symbolp.draw(); // Update game objects

  // p1update();
  // p1pupdate();
  p2Symbol.draw(); // Update game objects
  p2Symbolp.draw(); // Update game objects

  




  enemy.enemyMovement();
  player.movement();

  // Update hurtboxes
  player.updateHurtbox();
  enemy.updateHurtbox();

  // Draw game objects
  player.update();
  player.draw();
  enemy.update();
  enemy.draw();

  // Check collisions
  attackCollision();
  enemyAttackCollision();
  // CollisionBlocks.forEach(block => {
  //   block.draw();
  // });

  // Request the next frame
  window.requestAnimationFrame(gameloop);
}

// Start the game loop
gameloop();

I mentioned that ive tried rearranging my drawings. So not sure what’s causing this issue.

Social share with helmet does not provide card

I’m trying to get social share cards to populate across discord, facebook, etc and I’ve not had success in getting the card to populate.

This is my import
import { Helmet } from 'react-helmet-async';

In my view component I have the following

export default function SharePage({ }) {
const [images, setImages] = useState([]);

  return (
    <Box>
      <Helmet>
        <title>Hots&Cots</title>
        <meta name="description" content="Hots&Cots: Your source for Barracks and DFAC Reviews" />
        <meta name="keywords" content="military, barracks, dfac" />
        <meta name="author" content="Hots&Cots" />
        <meta property="og:title" content={`${renderFacilityType(hash, shareData)}`} />
        <meta property="og:description" content="Hots&Cots: Your source for Barracks and DFAC Reviews" />
        <meta property="og:image" content={`${images[0]}`} />
        <meta property="og:url" content="https://feed.hotscots.app/" />
        <meta name="twitter:title" content={`${renderFacilityType(hash, shareData)}`} />
        <meta name="twitter:description" content="Hots&Cots: Your source for Barracks and DFAC Reviews" />
        <meta name="twitter:image" content={`${images[0]}`} />
        <meta name="twitter:card" content={`${images[0]}`} />
      </Helmet>
</Box>
);


}

Social share does give me the following, but not sure how to resolve this especially since og:description is present.

Image
 og:image can't be found at the defined URL
 The ratio of your og:image isn't optimal 
 Image size is optimal (<8mb)

 The og:description metatag missing

Any suggestions to move forward?

Adsense Script From Functions.php

Can someone please advise how to call adsense script in a certain place of the body of the page? For example, after a specific class or tag (after title tag) ?

This is the function I’m using in child themes function.php file.

    function adsense_script() {

    $path = $_SERVER['REQUEST_URI'];
    $find = 'sdm';
    $pos = strpos($path, $find);
    if ($pos !== false) {

    <Script> 
    //adsense script
    </Script>
    <?php
    }
    }

I tried following, but it does not display the ads properly.

   add_action( 'wp_body_open', 'adsense_script' );

How to show the specific item to indicator position in spin wheel roll method

I want to show the given index item after rotate animation at top center where the indicator was located .

this is the method to get the result but its still show wrong item. Here is my component written in vue.js application. Help me to fix this problem.

``
roll(index, list, duration = 4000) {
            // Step 1: Find the item in the list by index and log it
            const item = list[index];
            console.log("Index:", index);
            console.log("Item:", item);

            // Step 2: Calculate the degree of the segment that the item occupies
            const segmentDegree = 360 / list.length; // Degree per segment
            const itemSegmentDegree = segmentDegree * index;
            console.log("Segment Degree of Item:", itemSegmentDegree);

            // Step 3: Calculate the top center segment degree
            const topCenterSegmentDegree = 0; // Top center is assumed to be 0 degrees

            // Step 4: Calculate the rotation needed
            // To have the item at the top center, adjust by subtracting itemSegmentDegree from 360
            const totalDegrees = 360 * 6; // Number of full rotations
            const rotationToAlignItemAtTop = (360 - itemSegmentDegree) % 360;
            const newEndDegree = totalDegrees + rotationToAlignItemAtTop;

            console.log(
                "Rotation to Align Item at Top:",
                rotationToAlignItemAtTop
            );
            console.log("New End Degree:", newEndDegree);

            // Get the wheel element
            const wheel = this.$refs.wheel;
            if (!wheel) {
                console.error("Wheel element is not available.");
                return;
            }

            // Reset previousEndDegree for a new spin
            this.previousEndDegree = this.previousEndDegree % 360;

            // Cancel any previous animation
            if (this.animation) {
                this.animation.cancel();
            }

            // Perform the animation
            this.animation = wheel.animate(
                [
                    { transform: `rotate(${this.previousEndDegree}deg)` },
                    { transform: `rotate(${newEndDegree}deg)` }
                ],
                {
                    duration: duration, // Use the provided duration
                    direction: "normal",
                    easing: "cubic-bezier(0.440, -0.205, 0.000, 1.130)", // Use a smooth easing function
                    fill: "forwards",
                    iterations: 1
                }
            );

            // Update the rolling state and handle the reward box
            setTimeout(() => {
                this.rolling = false;
                console.log("done rolling");
                this.rewardBox = true;
            }, duration);

            // Update previousEndDegree to the new end degree
            this.previousEndDegree = newEndDegree;
        },
``

How I suppose to change the method which part is wrong

Array.includes(…) not working as expected in typescript code

Here is some typescript code that I have in a NexJS app:

const holeSet:any[] = [];
.....

let xx = 1, yy = 2;
holeSet.push({x:xx,y:yy});

xx = 3;
yy = 4;
holeSet.push({x:xx,y:yy});

holeSet.map((e) => {
  console.log("element ::"+JSON.stringify(e));
});

const a = 1;
const b = 2;

if (holeSet.includes({x:a.toString(),y:b.toString()}))
  console.log("Value {1;2} FOUND !");

Here is the output produced when running the code above:

element ::{“x”:1,”y”:2}
element ::{“x”:3,”y”:4}

My problem is that I do not know what I am doing wrong.

I expect the message: Value {1;2} FOUND !

to show up, but it does not happen. Why is that ?

A bad syntax in the if statement I assume ??

How can I get the Stripe test payment to complete?

I’m erroring out with this

IntegrationError: We could not retrieve data from the specified Element. Please make sure the Element you are attempting to use is still mounted.

The stripe transactions shows the payment but incomplete and when I hover over the tooltip it says The customer has not entered their payment method. See Image. But I am using their test card numbers so I’m not sure what they mean by that

Here the checkout component

import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { loadStripe } from '@stripe/stripe-js';
import { Elements } from '@stripe/react-stripe-js';
import PageTitleHero from '../components/PageTitleHero';
import { useCart } from '../context/cartContext';
import { useAuth } from '../context/authContext'; 
import PropTypes from 'prop-types';
import Loading from '../components/Loading';
import UserInformation from '../components/checkout/UserInformation';
import StripePaymentForm from '../components/checkout/StripePaymentForm'; 

const stripePromise = loadStripe(import.meta.env.VITE_STRIPE_PUBLIC_KEY);

const Checkout = () => {
  const { cart, setCart } = useCart();
  const { currentUser } = useAuth(); 
  const [useShippingAsBilling, setUseShippingAsBilling] = useState(true);
  const [formData, setFormData] = useState({});
  const [loading, setLoading] = useState(false); 
  const navigate = useNavigate();

  useEffect(() => {
    const savedCart = localStorage.getItem('cart');
    if (savedCart) {
      setCart(JSON.parse(savedCart));
    }

    if (currentUser) {
      setFormData({
        firstName: currentUser.firstName || '',
        lastName: currentUser.lastName || '',
        email: currentUser.email || '',
        address: currentUser.address || '',
        city: currentUser.city || '',
        state: currentUser.state || '',
        zip: currentUser.zip || '',
        'shipping-address': currentUser.shippingAddress || '',
        'shipping-city': currentUser.shippingCity || '',
        'shipping-state': currentUser.shippingState || '',
        'shipping-postal-code': currentUser.shippingPostalCode || '',
        'billing-address': currentUser.billingAddress || currentUser.shippingAddress || '',
        'billing-city': currentUser.billingCity || currentUser.shippingCity || '',
        'billing-state': currentUser.billingState || currentUser.shippingState || '',
        'billing-postal-code': currentUser.billingPostalCode || currentUser.shippingPostalCode || '',
      });
    }
  }, [setCart, currentUser]);

  const handleUseShippingAsBilling = (event) => {
    setUseShippingAsBilling(event.target.checked);
    setFormData((prevData) => ({
      ...prevData,
      'billing-address': event.target.checked ? prevData['shipping-address'] : '',
      'billing-city': event.target.checked ? prevData['shipping-city'] : '',
      'billing-state': event.target.checked ? prevData['shipping-state'] : '',
      'billing-postal-code': event.target.checked ? prevData['shipping-postal-code'] : '',
    }));
  };

  const handleFormChange = (event) => {
    const { name, value } = event.target;
    setFormData((prevData) => ({ ...prevData, [name]: value }));
  };

  const total = cart.reduce((sum, product) => sum + product.price * product.quantity, 0) + 30;

  if (loading) {
    return <Loading />;
  }

  if (cart.length === 0) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <p className="text-lg font-semibold">Your cart is empty. Please add items to your cart before proceeding to checkout.</p>
      </div>
    );
  }

  return (
    <>
      <PageTitleHero text="Checkout" />
      <div className="relative mx-auto grid max-w-7xl grid-cols-1 gap-x-16 lg:grid-cols-2 lg:px-8 lg:pt-16">
        <OrderSummary total={total} cart={cart} />
        <PaymentAndShipping
          useShippingAsBilling={useShippingAsBilling}
          handleUseShippingAsBilling={handleUseShippingAsBilling}
          handleFormChange={handleFormChange}
          formData={formData}
          total={total}
          setLoading={setLoading}
          navigate={navigate}
          cart={cart}
        />
      </div>
    </>
  );
};

const OrderSummary = ({ total, cart }) => (
  <section aria-labelledby="summary-heading" className="py-12 md:px-10 lg:col-start-2 lg:row-start-1 lg:mx-auto lg:w-full lg:max-w-lg lg:bg-transparent lg:px-0 lg:pb-24 lg:pt-0">
    <div className="rounded-lg border border-gray-200 dark:border-gray-600 bg-white dark:bg-black shadow-sm p-12">
      <h2 id="summary-heading" className="sr-only">Order summary</h2>
      <dl>
        <dt className="text-sm font-bold text-indigo-500">Amount due</dt>
        <dd className="mt-1 text-3xl font-bold tracking-tight text-black dark:text-white">${total.toFixed(2)}</dd>
      </dl>
      <ul role="list" className="divide-y divide-gray-200 dark:divide-gray-600 text-sm font-medium">
        {cart.map((product, index) => (
          <li key={index} className="flex items-start space-x-4 py-6">
            <img alt={product.name} src={product.imageSrc} className="h-20 w-20 flex-none rounded-md object-cover object-center bg-slate-200 dark:bg-slate-800" />
            <div className="flex-auto space-y-1">
              <h3 className="text-slate-800 dark:text-slate-300">{product.name}</h3>
              <p className="text-slate-500 dark:text-slate-400">{product.quantity} x ${product.price}</p>
            </div>
            <p className="flex-none text-base font-medium text-slate-800 dark:text-slate-300">${product.price * product.quantity}</p>
          </li>
        ))}
      </ul>
      <dl className="space-y-6 border-t border-gray-300 dark:border-gray-600 pt-6 text-sm font-medium">
        <div className="flex items-center justify-between">
          <dt>Subtotal</dt>
          <dd>${cart.reduce((sum, product) => sum + product.price * product.quantity, 0).toFixed(2)}</dd>
        </div>
        <div className="flex items-center justify-between">
          <dt>Shipping (Flat Rate)</dt>
          <dd>$30.00</dd>
        </div>
        <div className="flex items-center justify-between border-t border-gray-300 dark:border-gray-600 pt-6 font-bold text-black dark:text-white">
          <dt className="text-base">Total</dt>
          <dd className="text-base">${total.toFixed(2)}</dd>
        </div>
      </dl>
    </div>
  </section>
);

const PaymentAndShipping = ({ 
  useShippingAsBilling, 
  handleUseShippingAsBilling, 
  handleFormChange, 
  formData, 
  total, 
  setLoading, 
  navigate, 
}) => (
  <section aria-labelledby="payment-and-shipping-heading" className="py-16 lg:col-start-1 lg:row-start-1 lg:mx-auto lg:w-full lg:max-w-lg lg:pb-24 lg:pt-0">
    <h2 id="payment-and-shipping-heading" className="sr-only">Payment and shipping details</h2>
    <div>
      <div className="mx-auto max-w-2xl px-4 lg:max-w-none lg:px-0">
        <UserInformation 
          useShippingAsBilling={useShippingAsBilling} 
          setUseShippingAsBilling={handleUseShippingAsBilling} 
          handleFormChange={handleFormChange} 
          formData={formData}
        />
        <Elements stripe={stripePromise}>
          <StripePaymentForm 
            total={parseFloat(total)} 
            formData={formData} 
            setLoading={setLoading} 
            navigate={navigate} 
          />
        </Elements>
      </div>
    </div>
  </section>
);

OrderSummary.propTypes = {
  total: PropTypes.number.isRequired,
  cart: PropTypes.array.isRequired,
};

PaymentAndShipping.propTypes = {
  useShippingAsBilling: PropTypes.bool.isRequired,
  handleUseShippingAsBilling: PropTypes.func.isRequired,
  handleFormChange: PropTypes.func.isRequired,
  formData: PropTypes.object.isRequired,
  total: PropTypes.number.isRequired,
  setLoading: PropTypes.func.isRequired,
  navigate: PropTypes.func.isRequired,
  cart: PropTypes.array.isRequired,
};

export default Checkout;

And the StripePaymentForm.jsx

import { useStripe, useElements, CardElement } from '@stripe/react-stripe-js';
import axios from 'axios';
import PropTypes from 'prop-types';
import PrimaryButton from '../PrimaryButton';

const StripePaymentForm = ({ total, formData, setLoading, navigate }) => {
  const stripe = useStripe();
  const elements = useElements();

  const secret_key = import.meta.env.VITE_STRIPE_SECRET_KEY;

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);

    if (!stripe || !elements) {
      setLoading(false);
      return;
    }

    const cardElement = elements.getElement(CardElement);

    try {
      // Create a PaymentIntent on the client side
      const { data: paymentIntent } = await axios.post(
        'https://api.stripe.com/v1/payment_intents',
        new URLSearchParams({
          amount: Math.round(total * 100),  // Ensure the amount is correctly rounded and converted to cents
          currency: 'usd',
          'payment_method_types[]': 'card',
        }),
        {
          headers: {
            'Authorization': `Bearer ${secret_key}`,
            'Content-Type': 'application/x-www-form-urlencoded',
          }
        }
      );

      const clientSecret = paymentIntent.client_secret;

      const paymentResult = await stripe.confirmCardPayment(clientSecret, {
        payment_method: {
          card: cardElement,
          billing_details: {
            name: `${formData.firstName} ${formData.lastName}`,
            email: formData.email,
            address: {
              line1: formData.address,
              city: formData.city,
              state: formData.state,
              postal_code: formData.zip,
            },
          },
        },
      });

      if (paymentResult.error) {
        console.error('Payment failed:', paymentResult.error);
        setLoading(false);
        return;
      }

      if (paymentResult.paymentIntent.status === 'succeeded') {
        navigate('/confirmation');
      }
    } catch (error) {
      console.error('Error processing payment:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className='grid grid-cols-1 gap-4 items-center mt-4'>
      <div className='col-span-1'>
        <h3 className='text-xl font-bold text-indigo-500'>Payment Information</h3>
        <CardElement className="mt-1 p-2 border border-gray-300 bg-white dark:bg-black rounded" />
      </div>
      <div className='col-span-1'>
        <PrimaryButton
          text={`Pay $${total.toFixed(2)}`}
          onClick={handleSubmit}
          disabled={!stripe}
          className={`w-full ${!stripe ? 'opacity-50 cursor-not-allowed' : ''}`}
        />
      </div>      
    </div>
  );
};

StripePaymentForm.propTypes = {
  total: PropTypes.number.isRequired,
  formData: PropTypes.object.isRequired,
  setLoading: PropTypes.func.isRequired,
  navigate: PropTypes.func.isRequired,
};

export default StripePaymentForm;

Any help is very much appreciated.

enter image description here

Get dynamic form inputs as JSON [closed]

I have HTML form with many inputs, after submitting the form I should get these values as JSON format, the challenge here is that the form has dynamic fields that can be increased/decreased during form filling. I’m trying to handle these inputs but I couldn’t reach the desired result which is to put each of group of the dynamic fields inside an array.
I am posting this JSON using AJAX but if there is PHP approach to achieve this it’s ok.

This is the output that I get:
output example

This is the desired result:
desired example

This is the JS code that I use:

function convertFormToJSON() {

    var data = $('#editForm');
    const array = $(data).serializeArray();
    const json = {};
    const tempItems = {};

        $.each(array, function () {
            if (this.name.includes('items')){
                tempItems[this.name] = this.value || "";
            }else{
                json[this.name] = this.value || "";
            }
        });

    json['items'] = tempItems;
    console.log(json);
}

running into a problem using local.storage while building a real time text editor in react

i have this little project where i built a text editor and i want it that when i select any part of the text it goes automatically to a form in the sidebar where the selected text can be edited then parsed back real time on the text editor

im using local storage in this

my problem is that once i select the text it goes to the form then it immediately disappears

what did i miss?

here’s my code for the editor


import Quill from 'quill'
import 'quill/dist/quill.snow.css'
import{io} from 'socket.io-client'
import{useParams} from 'react-router-dom'
import AdminProfile from './componets/AdminProfile'
import Coment from './componets/Coment'
import TextSelector from "text-selection-react";
import{ Button, Textarea} from 'flowbite-react'
import{UserContext} from './context/UserContext'


const SAVE_INTERVAL_MS = 2000

const TOOLBAR_OPTIONS = [
    [{ header: [1, 2, 3, 4, 5, 6, false] }],
    [{ font: [] }],
    [{ list: "ordered" }, { list: "bullet" }],
    ["bold", "italic", "underline"],
    [{ color: [] }, { background: ["red", "blue", "yellow"] }],
    [{ script: "sub" }, { script: "super" }],
    [{ align: [] }],
    ["image", "blockquote", "code-block"],
    ["clean"],
  ]

// eslint-disable-next-line react/prop-types
const TextEditor = () => {
  const {id:documentId} = useParams()
  const[socket,setSocket] = useState()
  const[quill,setQuill] = useState()
  const[show,setShow] = useState([])
    const[apply,setApply] = useState(true)
    const[comment,setComment] = useState("")
   
   
  
  
  
   
    const {user}=useContext(UserContext)
  useEffect(() => {
    const s = io("http://localhost:5000",{transports: ['websocket'],})
     setSocket(s)
     
     return () => {
      s.disconnect()
    }
  },[])
  
  
  
 
  useEffect(() => {
    if (socket == null || quill == null) return

    const interval = setInterval(() => {
      socket.emit("save-document", quill.getContents())
    }, SAVE_INTERVAL_MS)

    return () => {
      clearInterval(interval)
    }
  }, [socket, quill])
 
 
 
 
 
 
 
 
 
 
 
  useEffect(() => {

   

    if(socket == null || quill == null) return 

    const handler = (delta,oldDelta,source) => {
  if(source !== 'user') return 
  socket.emit("send-changes",delta)
}
  quill.on("text-change",handler)
  
return () => {
    quill.off("text-change",handler) 
}

},[socket,quill])




useEffect(() => {

  if(socket == null || quill == null) return 
    
      const handler = (delta) => {
     quill.updateContents(delta)
  }
   socket.on("receive-changes",handler)
  return () => {
      socket.off("receive-changes",handler) 
  }
  
  },[socket,quill])





useEffect(() => {

  if(socket == null || quill == null) return 

socket.on("load-document",document => {
  quill.setContents(document)
  quill.enable()
})

  socket.emit('get-document',documentId)

},[socket,quill,documentId])







  
  
  
  
 
  
  const wrapperRef = useCallback(wrapper => {
    if(wrapper == null) return

   
wrapper.innerHTML =""
   
   
    const editor = document.createElement("div")
    wrapper.append(editor)
   const q = new Quill(editor,{theme:"snow",modules: { toolbar: TOOLBAR_OPTIONS },})
   
   

   
 
   q.disable()
  q.setText('loading...')

   setQuill(q)
  },[])


 

  
  const handleaply = () => {

  }

 
 
 

  
  useEffect(() => {
    if (quill) {
      quill.on('text-change', () => {
        const text = quill.getText();
       setShow(text);
      });
    }
  }, [quill]);
  
  const[select,setSelect] = useState([])
  
 

 

   useEffect(() => {
    document.onmouseup = () => {
  
      const me = window.getSelection(show).toString() 
      setSelect(me)
    
    
    }

    localStorage.setItem('items', JSON.stringify(select));

   },[select])



 
  
  
 
  
  return (
   
   <div className="flex justify-between">
    
    
    
    
    
    
    
   
   
   
   
    <div className="w-full ">
      
      <div onClick={handleaply}>accept</div>
      
      <AdminProfile/>
    
    
    
    </div>
  
  
  <div className="container" ref={wrapperRef}>

      </div>
  
  <div className="w-full">
 
 
  <Coment select={select} />

 
  <div  >
   
 
    
   
         
  </div>
 
 
  </div>
 

  
   
   
   
   
   
   </div>
 
 
 

 
 
  )
}

export default TextEditor

here is my form in the sidebar code where it receives the selected text

import React,{useState,useContext,useEffect} from 'react'
import{ Button, Textarea} from 'flowbite-react'
import{UserContext} from '../context/UserContext'
import CommentScroll from './CommentScroll'
import TextSelector from "text-selection-react";


const Coment = ({item,select,position}) => {
 


 const {user}=useContext(UserContext)
 
  const[comment,setComment] = useState("")

  
  
  const [items, setItems] = useState([]);

useEffect(() => {
  const items = JSON.parse(localStorage.getItem('items'));
 
   setItems(items);

}, [items]);
  
  
  
  
  
  console.log(items)
  
  
  
  const handleSubmit = async(e) => {
    e.preventDefault() 

    if(comment.length >  200){
     return
    }
     
    try{
     const res = await fetch(`http://localhost:5000/api/coment/create`,{
       credentials: "include",
     method:"POST",
    
       headers:{
         "Content-Type" : "application/json",
         'x-auth-token': "JWT_SECRET",
       },
      
       body:JSON.stringify({content:comment,userId:user._id,username:user.username,profilePicture:user.profilePicture})
      })
     
     
       const data = await res.json()
       if(res.ok){
         setComment('')
      
       }
    }
    catch(error){
     console.log(error)
    
    }
   
}
  
  
  


  
  
 








const handlerSubmit = () => {

}






return (
   
   <div className="flex w-full mt-20 flex-col fixed ">
   
   {item && <div>hi</div>}


   <div className="w-[330px] ">
  

   
 <CommentScroll/>
  
  </div>
   

   
  
   
   
   
   
   <div className=" w-[330px]  ">
    
    
      
  
    
     <form className='border border-teal-500  rounded-md p-3' onSubmit={handleSubmit}
      
      
      >


<Textarea 
    placeholder='add a Comment...'
    rows='3'
    maxLength='200'
    onChange={(e) => setComment(e.target.value)}
    value={items}
  
  />


<div className='flex justify-between mt-5 items-center'>
        <p className='text-gray-500 text-sm'>{200 - comment.length}charector left</p>
        
        <Button outline gradientDuoTone='purpleToBlue' type="submit">
          Submit
        </Button>
      </div>


      </form>
    
    
      </div>
    
    </div>
  )
}

export default Coment

How can I make a button populate a field of a form on the same page?

I have a website which offers repairs for 3 products.

I have a row of images of each one and a button for each one of them.

I also have a form at the bottom of the page that asks them for the personal info and the product that needs repaired.

I want to make the buttons from the images auto-complete the field where it asks what product needs repaired and scroll to the form that is at the bottom of the page.

I think I need a javascript function but I don’t know what to include in it.

I suppose I need a ‘value’ attribute and an id to the form field.

Sending JSON strings from ESP32 web client to Apache web server

I’m trying to perform a POST operation from a web client application running on an ESP32-WROOM-32 to a web server running on Windows 11 using Apache. On the backend I’m trying to use JavaScript to handle the received data (JSON string). The problem is that I can’t see/receive the JSON string sent by the ESP32, although on the VS Code terminal(from the ESP32 side) I get:

I (79753440) HTTP_CLIENT: HTTP POST Status = 200, content_length = 334
I (79753440) HTTP_CLIENT: HTTP_EVENT_DISCONNECTED

So, I assume the data has been successfuly sent. I’m using the esp_http_client example.

I have already

1. Activated the reverse proxy on Apache using the mod_proxy module:

ProxyPass /post http://192.168.0.101:8000/
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

2. Written JavaScript and html codes to handle the sent data(I’m really a newbie in js/html):

const intervalID = setInterval(get_user_ID,1000);

function get_user_ID()
{
 
    var xhr = new XMLHttpRequest();
    var requestURL = "/post";
    xhr.open('GET', requestURL);
    xhr.send();

    if (xhr.readyState == 4 && xhr.status == 200) 
    {       

        var response = JSON.parse(xhr.responseText);

        console.log(response);

        document.getElementById("esp_response").innerHTML = response.User;        

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

    <head>
        <meta charset="utf-8"/>
        <script async src='serverJS.js'></script>
    </head>

    <body>
        <h1>ESP32 get data</h1>
            <label id="esp_response_label">ESP32 response: </label>
            <div id="esp_response"></div> 
</body>
</html>

As a result, my html labels are printed correctly but I still get no data on the web browser console. Tried out the fetch API but no success. In one of the approaches I was getting response = null on the console. What could I be missging?

Just in case, I leave my esp_http_client piece of code as well:

#define HTTP_ENDPOINT “192.168.0.101”

static void http_rest_with_url(void)
{

esp_http_client_config_t config = {
    .host = HTTP_ENDPOINT,
    .path = "/",
    .query = "esp",
    .event_handler = _http_event_handler,
    .user_data = local_response_buffer,    
    .disable_auto_redirect = true,
};
esp_http_client_handle_t client = esp_http_client_init(&config);

// POST
const char *post_data = "{"User":"User1-1919"}";
esp_http_client_set_url(client, "http://"HTTP_ENDPOINT"/post");
esp_http_client_set_method(client, HTTP_METHOD_POST);
esp_http_client_set_header(client, "Content-Type", "application/json");
esp_http_client_set_post_field(client, post_data, strlen(post_data));
err = esp_http_client_perform(client);
if (err == ESP_OK) {
    ESP_LOGI(TAG, "HTTP POST Status = %d, content_length = %"PRId64,
            esp_http_client_get_status_code(client),
            esp_http_client_get_content_length(client));
} else {
    ESP_LOGE(TAG, "HTTP POST request failed: %s", esp_err_to_name(err));
}

esp_http_client_cleanup(client);

}

Citation-JS not using the specified CSL template

This question is about the JavaScript library [{citation.js}](https://citation.js.org/). I need to be able to generate in-text citations in various formats. For example:

AMA

Lorem Ipsum is simply dummy text of the printing and typesetting industry (Loomes et al., 2017; Mantzalas et al, 2022).

APA

Lorem Ipsum is simply dummy text of the printing and typesetting industry 1-2.

Although Cite.format allows you to specify a template, it doesn’t seem to use it. My sample code shows me specifying different template values and obtaining the same generic result.

I assume that means that it uses code from {citeproc-js}. Citation-JS has plugins. Is one of them used for formatting the citations via CSL? I can’t find any examples.

There is a tutorial for Outputs, but it contains almost no information.

        const Cite = require('citation-js');

        // Sample BibTeX string for demonstration
        const bibtex = `
        @article{Loomes2017,
            title = {Loomes Title},
            author = {Loomes, Rachel and Hull, Laura and Mandy, William Polmear Locke},
            date = {2017-06},
            journaltitle = {Journal of the American Academy of Child and Adolescent Psychiatry},
            volume = {56},
            number = {6},
            pages = {466--474},
            doi = {10.1016/j.jaac.2017.03.013}
        }
        @article{Mantzalas2022,
            title = {Mantzalas Title},
            author = {Mantzalas, Jane and Richdale, Amanda L. and Adikari, Achini and Lowe, Jennifer and Dissanayake, Cheryl},
            date = {2022-03},
            journaltitle = {Autism in Adulthood},
            volume = {4},
            number = {1},
            pages = {52--65},
            doi = {10.1089/aut.2021.0021}
        }
        `;

        // Create the citation-js object
        const library = new Cite(bibtex);

        let single_citation = "Loomes2017";
        let double_citation = "Loomes2017,Mantzalas2022";

        let single_inline_apa = library.format('citation', {
            entry: single_citation,
            format: 'html',
            template: "apa",
            lang: 'en-US'
        });

        console.log(`single inline APA: ${single_inline_apa}`);

        let double_inline_apa = 
            double_citation
            .split(",")
            .map(x => x.trim())
            .map(x => library.format('citation', {
                entry: x,
                format: 'html',
                template: "apa",
                lang: 'en-US'
                })
            )
            .join(",")

        console.log(`double inline APA: ${double_inline_apa}`);

        let single_inline_ama = library.format('citation', {
            entry: single_citation,
            format: 'html',
            template: "apa",
            lang: 'en-US'
        });

        console.log(`single inline AMA: ${single_inline_ama}`);

        let double_inline_ama = 
            double_citation
            .split(",")
            .map(x => x.trim())
            .map(x => library.format('citation', {
                entry: x,
                format: 'html',
                template: "ama",
                lang: 'en-US'
                })
            )
            .join(",")

        console.log(`double inline AMA: ${double_inline_ama}`);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Citation-JS Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/citation-js/0.7.14/citation.js"></script>
</head>
<body>
    <div id="content"></div>
</body>
</html>

Logic for Tournament Bracket Matchups

I am making an eight team double-elimination tournament bracket and am currently working on the logic side of things.

I have eight teams and I am tracking their wins and losses. My goal is to separate teams with 0 losses (winners), 1 loss (losers), and 2 losses (eliminated-ers) – and create matchups within their category (teams with 0 losses would only play teams with 0 losses, teams with 1 loss would only play teams with 1 loss, and so on), until the championship which would obviously be between a “winner” team and a “loser” team with the first to 2 losses being eliminated.

I am currently thinking about using arrays to hold each category, but I don’t know if there is anything else out there that I can use so I am open to suggestions πŸ™‚

Since wins and losses are determined by button clicks, I have a simple button program I created πŸ™‚ (Currently it does have a bug where a team without a matchup after the first click is unclickable and considered undefined)

const teams = [{
  name: "Chaos Coordinators",
  wins: 0,
  losses: 0
}, {
  name: "Sofa King Awesome",
  wins: 0,
  losses: 0
}, {
  name: "The Nerd Herd",
  wins: 0,
  losses: 0
}, {
  name: "The Laughing Stock",
  wins: 0,
  losses: 0
}, {
  name: "Brainy Bunch Gone Wild",
  wins: 0,
  losses: 0
}, {
  name: "Cereal Killers",
  wins: 0,
  losses: 0
}, {
  name: "Jimmie Crickets",
  wins: 0,
  losses: 0
}, {
  name: "The Mismatched Socks",
  wins: 0,
  losses: 0
}];

// DOM helpers 
const el = (sel, par = document) => par.querySelector(sel);
const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);

// App
const maxLosses = 2; // Max losses
const elTeamButtons = el("#team-buttons");
let winners = [];
let losers = [];
let eliminated = [];

const updateButton = (team) => {
  console.log("Updating button for team:", team.name); // Log button update
  const text = team.losses >= maxLosses ? "Eliminated" : `Wins: ${team.wins} - Losses: ${team.losses}`;
  team.button.textContent = `${team.name} - ${text}`;
  team.button.disabled = team.losses >= maxLosses;
  team.button.classList.toggle("is-eliminated", team.losses >= maxLosses);

  // Update color based on status
  if (team.losses === 0) {
    team.button.style.backgroundColor = "green"; // Winner
    team.button.style.color = "white"; // Ensure text is visible
  } else if (team.losses === 1) {
    team.button.style.backgroundColor = "yellow"; // Loser
    team.button.style.color = "black"; // Ensure text is visible
  } else {
    team.button.style.backgroundColor = "red"; // Eliminated
    team.button.style.color = "white"; // Ensure text is visible
  }
};

const updateScore = (team, win, loss) => {
  console.log("Updating score for:", team.name); // Check if this logs correctly
  team.wins += win;
  team.losses += loss;
  console.log("Wins:", team.wins, "Losses:", team.losses); // Log new values
  updateButton(team);

  if (team.opponent) {
    team.opponent.losses += 1;
    console.log("Opponent losses:", team.opponent.losses); // Log opponent's losses
    updateButton(team.opponent);
  }
  groupTeams(teams);
  makeMatches();
};

const groupTeams = (array) => {
  winners = [];
  losers = [];
  eliminated = [];

  array.forEach(team => {
    if (team.losses === 0) {
      winners.push(team);
    } else if (team.losses === 1) {
      losers.push(team);
    } else {
      eliminated.push(team);
    }
  });

  console.log("Winners:", winners);
  console.log("Losers:", losers);
  console.log("Eliminated:", eliminated);
};

const makeMatches = () => {
  elTeamButtons.innerHTML = ""; // Cleanup
  console.log("Creating matches for:", winners, losers); // Log teams before creating buttons

  const logMatches = (group) => {
    group.forEach((team, i, teams) => {
      team.opponent = teams[i + (i % 2 === 0 ? 1 : -1)];
      if (i % 2 === 0) {
        console.log(`Match: ${team.name} vs ${team.opponent.name}`);
      }
    });
  };

  // Create buttons for winners
  winners.forEach((team, i, teams) => {
    team.opponent = teams[i + (i % 2 === 0 ? 1 : -1)];
    console.log("Creating button for winner:", team.name); // Log team info
    team.button = elNew("button", {
      className: "team-button",
      onclick() {
        console.log("Button clicked for team:", team.name); // Log button click
        if (team.opponent) {
          // Assume each button click represents a win for the clicked team and a loss for the opponent
          updateScore(team, 1, 0); // 1 win, 0 loss for the clicked team
        }
      }
    });
    updateButton(team); // Initial button text
    elTeamButtons.append(team.button);
  });

  // Create buttons for losers
  losers.forEach((team, i, teams) => {
    team.opponent = teams[i + (i % 2 === 0 ? 1 : -1)];
    console.log("Creating button for loser:", team.name); // Log team info
    team.button = elNew("button", {
      className: "team-button",
      onclick() {
        console.log("Button clicked for team:", team.name); // Log button click
        if (team.opponent) {
          // Assume each button click represents a win for the clicked team and a loss for the opponent
          updateScore(team, 1, 0); // 1 win, 0 loss for the clicked team
        }
      }
    });
    updateButton(team); // Initial button text
    elTeamButtons.append(team.button);
  });

  // Log current matches and waiting teams
  console.log("Current matches:");
  logMatches(winners);
  logMatches(losers);

  const waitingTeams = winners.concat(losers).filter((_, i, teams) => i % 2 !== 0);
  console.log("Teams waiting for a matchup:", waitingTeams.map(team => team.name));
};

// Function to Reset Teams to Initial State
function resetTeams() {
  // Reset wins and losses to their initial state if needed
  teams.forEach(team => {
    team.wins = 0;
    team.losses = 0;
  });  
  // Recreate matches with updated state
  groupTeams(teams);
  makeMatches();
}

// Initialize and Setup Event Listeners
console.log("Initializing matches...");
groupTeams(teams);
makeMatches();
console.log("Matches initialized.");

el("#resetButton").addEventListener("click", resetTeams);
* {
  margin: 0;
  box-sizing: border-box;
}

#team-buttons {
  position: relative;
  border: 1px solid #888;
  display: flex;
  flex-flow: row wrap;
  padding: 0.5em;
  gap: 0.5em;

  & .team-button {
    flex: 0 0 calc(50% - 0.3em);
    padding: 1em;

  &.is-eliminated {
      /* color: #f008; */
      color: red;
      cursor: not-allowed;
    }
  }
}
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Styled Buttons</title>
  </head>

  <body>
     <button id="resetButton">RESET</button>
<div id="team-buttons"></div>
  </body>

So I guess my question is three-fold:

What is the best way to separate the different types of teams (eliminated-ers, winners, and losers)?

What is the best way to push these types of teams into “rounds” based on the combined number of wins and losses (so I can have separate rules for a championship)?

And finally, am I going about this completely the wrong way? Any programming concepts I should look in to?

P.S. please please please do not write code for me. I am just starting programming and I want to learn πŸ™‚ so any nudge in the right direction whether it be documentation or other posts on the overflow or any other resources would be greatly appreciated πŸ™‚ this post has no intention of fleecing answers off of people.

How to discontinue video using Mediasource(MSE)?

I have 2 different videos or video 1 and video 2, using the mse as a lamp or buffer properly so that the video 2 is played, they have mpegts-2, I am using the muxjs to make the conversation, so everything works fine using the appendbuffer, to make it clearer, you will create this array of two segments of video1: let video_1_segs = ['path1/1.ts','path1/2.ts','path1/3.ts'];
and here’s video 2:
let video_2_segs = ['path2/1.ts','path2/2.ts','path2/3.ts'];
now how to make a safe sequence when or or segment 3 for played completely? Quaisquer duvida or more parts of the code is only talk

Why does VITE_ENV on my project throw an error

I am working on a project and I want to use VITE_ENV to access environmental variables instead of dotenv, I have the dotenv package installed though.

I have used the same exact illustration in vite’s docs

#.env file

VITE_SOME_KEY=123
DB_PASSWORD=foobar
#main.js file

console.log(import.meta.env.VITE_SOME_KEY); //I am expecting > "123"
console.log(import.meta.env.DB_PASSWORD); //I am expecting > undefined

but I get the error

console.log(import.meta.env.VITE_SOME_KEY); // "123"
                            ^

TypeError: Cannot read properties of undefined (reading 'VITE_SOME_KEY')
    at file:///Users/oluwajolasun/Documents/Software%20Engineering/Projects/env%20test/env-test/main.js:1:29
    at ModuleJob.run (node:internal/modules/esm/module_job:262:25)
    at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:485:26)
    at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:109:5)

Node.js v22.5.1

My example project folder structure

My example project folder structure

How to animate the background and the card in React?

I am building a page which includes some animations. I have a bit of challenge on this one. The animation itself is in brainsave.ai and I cannot really recreate the same effect (or cannot think of a way to make it like that).

I will create a React snippet so it is more clear.

// Get a hook function
const { useState } = React;

const Example = ({ }) => {
    const services = [
        {
            id: 1,
            title: 'training & education',
            description: 'creation of workshops and educational materials to guide brands through a fast-paced industry',
            image: 'https://i.imgur.com/XVtwOQH.png',
        },
        {
            id: 2,
            title: 'development',
            description: 'development and deployment of comprehensive gaming experiences',
            image: 'https://i.imgur.com/XVtwOQH.png',
        },
        {
            id: 3,
            title: 'NFT plug-n-play',
            description: "creation of web3 solutions built around customers' business, technical, and legal need",
            image: 'https://i.imgur.com/XVtwOQH.png',
        },
        {
            id: 4,
            title: 'concept creation',
            description: 'conception of creative engagement formats embedded in innovative storytelling',
            image: 'https://i.imgur.com/XVtwOQH.png',
        },
        {
            id: 5,
            title: 'strategic consulting',
            description: 'definition of go-to-market strategies & long-term roadmaps for gaming initiatives based on clients’ strategic objectives',
            image: 'https://i.imgur.com/XVtwOQH.png',
        },
    ];

    return (
        <div className="container">
            <div className="services">
                {
                    services.map((service) => (<div className="card_item" key={service.id}>
                        <div className="images">
                            <img src={service.image} alt="image" />
                        </div>
                        <div className="description_container">

                            <p className="card_item_title">{service.title}</p>
                            <p className="card_item_description">{service.description}</p>
                        </div>
                    </div>))
                }
            </div>

        </div>
    );
};

// Render it
ReactDOM.createRoot(
    document.getElementById("root")
).render(
    <Example />
);
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
.container {
  height: 753px;
  max-width: 82rem;
  background-color: #000;
  padding: 30px 0;
  margin-right: auto;
  margin-left: auto;
  display: flex;
  background-image: url('/images/spin_background.png');
  background-size: cover;
}

.services {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.card_item {
  max-width: 439px;
  height: max-content;
  background-color: #fff;
  border-radius: 16px;
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 23px;
}

.card_item:nth-child(2) {
  margin-top: 70px;
}

.card_item:nth-child(3) {
  margin-left: 140px;
}

.card_item:nth-child(4) {
  margin-top: 150px;
  margin-right: -40px;
}

.services .card_item .images {
  width: 77px;
  height: 77px;
  border-radius: 50%;
  background-color: #000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.card_item_title {
  font-size: 16px;
  font-weight: 500;
  margin: 0;
  margin-bottom: 5px;
  color: #000 !important;
}

.card_item_description {
  max-width: 307px;
  font-size: 16px;
  color: #000 !important;
  margin: 0;
}

@media only screen and (max-width: 992px) {
  /* Responsive adjustments if needed */
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>