Is it possible to use math.random to only choose array values that haven’t already come up? (Infinite while loop)

appreciate any answers on this as I have been really struggling to make it work in different ways.

So, I have an array. When I click a button, I want a random value from that array to appear. When I click it again, I want only values that have not already appeared to be displayed. I’m not sure if this is possible with math.random as I’ve tried multiple different ways of doing this, and now currently have an infinite while loop going (I had a for loop before).

Basically, no matter what methods I have tried, I keep getting the same values pop up again. I’ve also tried .pop(), but then the indexes for the values change and I don’t know how to keep track of that.

This is what I have right now:

HTML:

<h1 id="myValue"></h1>
<button onclick="showValue()">Click here!</button>

JavaScript:

myArray = [1, 2, 3];

function showValue() {
  while (myArray.length > 0) {
    let valueChoice = myArray[Math.floor(Math.random() * myArray.length)];
    const isValue1 = myArray.indexOf(1);
    const isValue2 = myArray.indexOf(2);
    const isValue3 = myArray.indexOf(3);
    if (valueChoice === isValue1) {
      myArray.splice(isValue1, 1);
      document.getElementById("myValue").innerHTML = "Value 1";
    } else if (valueChoice === isValue2) {
      myArray.splice(isValue2, 1);
      document.getElementById("myValue").innerHTML = "Value 2";
    } else if (valueChoice === isValue3) {
      myArray.splice(isValue3, 1);
      document.getElementById("myValue").innerHTML = "Value 3";
    }
    else {
      document.getElementById("myValue").innerHTML = "Error";
    }
  }
}

Regex replace with a small text change?

I need to convert some HTML content to UBB code, for instance replacing the < > signs by square brackets [ ].
There also may be an ordered list <ol> tag with a start= attribute specifying the kind of marker.

const str = '<b>Something</b> is going on.<br><i>But what?</i><br><br><ol start="3"><li>First</li><li>Second</li><li>Third</li></ol>';
const regex = /<(/?([bisu]|li|ul|ol|ol start="d+"))>/gi;
let result = str.replace(regex, "[$1]");
console.log(result);

This works as expected, but I’d like to remove the quotation marks, so the <ol start="3"> will become [ol start=3]. I wonder if this is possible in the same regex.

Collision of to balls are getting stuck sometimes instead of bouncing off each other in html5 canvas

Balls do bounce, but sometimes they get stuck to each other.

Do tell if you need the rest of the code to solve this query.

This function is used to measure the distance between two balls.

    const measureDistance = (x1, y1, x2, y2) => {
        let result
        result = Math.pow(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2), 0.5)
        return result
    }
    function rotate(velocity, angle) {
        const rotatedVelocities = {
            x: velocity.dx * Math.cos(angle) - velocity.dy * Math.sin(angle),
            y: velocity.dx * Math.sin(angle) + velocity.dy * Math.cos(angle)
        };

        return rotatedVelocities;
    }
    const manageCollition = (tempArr, i, j) => {
        const angle = Math.tan(tempArr[j].dy - tempArr[i].dy / tempArr[j].dx - tempArr[i].dx)
        console.log(tempArr[j].dy - tempArr[i].dy / tempArr[j].dx - tempArr[i].dx)
        const u1 = rotate(tempArr[i], angle)
        const u2 = rotate(tempArr[j], angle)
        return { u1, u2 }

    }
    const checkCollisions = (ball, tempArr, i) => {
        let returnArr = tempArr;
        for (let j = 0; j < tempArr.length; j++) {
            if (j === i) continue
            const distance = measureDistance(ball.x, ball.y, tempArr[j].x, tempArr[j].y) - 2 * radius
            if (distance <= 0) {
                    const { u1, u2 } = manageCollition(tempArr, i, j)
                    returnArr = tempArr.map((element, index) => {
                        let newBall = element
                        if (index === i) {
                            newBall.dx = u1.x
                            newBall.dy = u1.y
                        }
                        if (index === j) {
                            newBall.dx = u2.x
                            newBall.dy = u2.y
                        }
                        return newBall
                    })
                }

            }
        return returnArr
    }

I think I made a mistake in physics or math somewhere.

MongoDB date query

I have a collection named practices that stores documents of practices done by the users. I have 4 keys in each document.

  • startTime (date timestamp)
  • endTime (date timestamp)
  • user (objectID of user)
  • duration (length of practice in secs)

Now here is the confusion. As my timezone is (+5:00 from UTC), suppose I submit a practice with startTime=2024-10-10T01:00:00+05:00 which will be stored in MongoDB as startTime=2024-10-09T20:00:00Z as MongoDB stores date-time in UTC which will move back submitted timestamp to -5 hours, eventually moving to previous date from 10 to 09. Different users will have different timezones.

Now, I want to query a user’s whole practices for the day. I use dayjs for date manipulation.

I generate query like this:

const queryDay = '2024-10-10'

query = {
  startTime: {
  $gte: dayjs.utc(queryDay).startOf('day).toDate()
 },
  endTime: {
  $lte: dayjs.utc(queryDay).endOf('day).toDate()
 }
}

which results startTime=2024-10-10T00:00:00Z and endTime=2024-10-10T23:59:59Z.

Now, when the query runs it will miss the above submitted practice as it was saved with date-time that does not fall in the query but technically it should be included as it was happened on 10 but according to (+5:00).

According to my thinking start day and end day will different according to timezone. When my day starts which is at 2024-10-10T00:00:00+05:00, this time when converted to UTC equals to 2024-10-09T19:00:00Z and same for the end of day, day ends at 2024-10-10T23:59:59+05:00 which in UTC equals to 2024-10-10T18:59:59Z. if we use these startTime and endTime then it will accurately fetches all practices of the day.

These are my main questions:

  1. So how should I do it? Meaning how I build a query respecting user
    timezone who is fetching it.
  2. I have a doubt in toDate() method of dayjs. It behaves differently in node and browser environment. In browser it gives me a date object which is parsed in local timezone. In my case (+5:00) and when in node, it simply first converts the date in UTC then in date object (does not parses in server timezone or any). What would happen if in node it converts the date object into local timezone where the server is running because it will mess up the query?
  3. Is there a way that we can use a ISO string to use it in query. As I heard that it only uses date object to query date fields and does not accept string (ISO date string)? I don’t want to use toDate() as it’s behavior is not consistent.

How to intercept Ctrl-d?

I have to following Greasemonkey script:

(function() {
    'use strict';

    document.addEventListener('keyup', (ev) => {
        if (ev.ctrlKey && (ev.key == 'e' || ev.key == 'd')) {
            GM_log(ev);
            ev.preventDefault();
        }
    }, false);
})();

I tried it in Tampermonkey in Firefox. It works for Ctrl-e but does not work for Ctrl-d. How to make it working for Ctrl-d?

About styling a table dynamically and adding or removing columns

The columns wraps weirdly and I can’t figure out why it is happening.

const [isHidden, setIsHidden] = useState([]);
const { data: leadsData, isPending } = useLeads();
  
let columns = tableHead.length - isHidden.length
const handleVisiblity = (id) => {
  setIsHidden((prevHidden) => {
    if (prevHidden.includes(id)) {
      return prevHidden.filter((hiddenId) => hiddenId !== id);
    } else {
      return [...prevHidden, id];
    }
  });
};

if (isPending) return <Spinner />;

<div className="grid gap-2 w-full">
  <div className="flex items-center gap-6">
    <Popover>
      <PopoverTrigger>
        <NotButton size="icon">
          <ListTree />
        </NotButton>
      </PopoverTrigger>
      <PopoverContent align="start">
        <ul>
          {tableHead.map((table) => (
            <PopoverList
              key={table.id}
              id={table.id}
              title={table.title}
              isHidden={isHidden}
              handleVisiblity={handleVisiblity}
            />
          ))}
        </ul>
      </PopoverContent>
    </Popover>
  </div>
  <Separator className="mb-4" />
  <div>
    <Table className="w-full">
      <Table.Header>
        <Table.Row columns={columns}>
          {tableHead.map((table) => (
            <Table.Head key={table.id}>
              {!isHidden.includes(table.id) && table.title}
            </Table.Head>
          ))}
        </Table.Row>
      </Table.Header>
      <Table.Body>
        {leadsData.map((leads) => (
          <LeadsTable
            key={leads.id}
            leads={leads}
            isHidden={isHidden}
            id={tableHead.id}
            columns={columns}
          />
        ))}
      </Table.Body>
    </Table>
  </div>
</div>

ROW element

const Row = forwardRef(({ children, className, columns, ...props }, ref) => {
  console.log(columns) //output 7,6,5
  return (
    <tr
      ref={ref}
      style={{
        display: 'grid',
        gridTemplateColumns: `repeat(${columns}, minmax(200px, 1fr))` 
      }}
      className={cn(
        "border-b duration-300 ease-in-out hover:bg-muted/50 data-[state=selected]:bg-muted",
        className
      )}
      {...props}
    >
      {children}
    </tr>
  );
});

Head element

const Header = forwardRef(({ children, className, ...props }, ref) => (
  <thead ref={ref} className={cn("[&_tr]:border-b w-full", className)} {...props}>
    {children}
  </thead>
));

const Head = forwardRef(({ children, className, ...props }, ref) => (
  <th
    ref={ref}
    className={cn(
      "h-12 px-4 text-center font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 last:flex last:justify-center  ",
      className
    )}
    {...props}
  >
    {children}
  </th>
));

I am getting the correct number of columns in console.log(), it just wraps into 2 rows instead of a single row.

Before hiding columns

After hiding columns

The content part works just fine it’s just the <thead> part is acting weird.

Why the following simple function does not work in HTML? [closed]

I have two files, first file is a JavaScript file and in this file I have a function that is expected to print “Hello World”, and the second file is a php file and in this file I tried to call the function that exists in JavaScript file but that does not work.

Here is in the following the code that exists in the JavaScript file:

var para_1 = "Hello World";
function para1() {document.write(para_1);}

Here is the image of JavaScript file

Here is in the following the code that exists in php file:

<html>
<script src="JavaScript2/Variables2.js"></script>

<head>
    <title>ABC</title>
</head>

<body>

<script>
 para1();
</script>

</body>

</html>

Here is the image of php file

but after I run the php file, I didn’t get “Hello World” in the output. See this image: (Image)

I know it’s simple to type “Hello World” in the php file, but I want to know how to use a function from JavaScript file, so what is the problem of the code?

SupabaseJS join without including join table as a property in the response

const { data, error } = await this.client
      .from('tableA')
      .select('*, tableB!inner(tableC!inner())')
      .eq('tableAPK', pk)
      .eq('tableB.tableC.id', tableCPK)
      .returns<TableAObject[]>();

This code returns TableAObject array with tableB: {} property within each object. As in,

{ …tableAProperties, tableB: {} }. However, I would like for it to not be there. I joined purely for filtering reasons. Any help is appreciated.

Request for Support in Extracting and Mirroring Data Between Sites

I’m developing an internal monitoring site for gateways (GW), but I’m facing some challenges. Some GWs display call data using the following HTML structure:

<th class="route">Totais</th>

<th class="calling"></th>

<th class="conn"></th>

<th class="talking">20</th>

<th class="tot">20</th>

In my system, I extract data from the <th class="tot"> field.

However, other GWs load data dynamically through a variable in JavaScript, making direct access difficult. Here’s the code snippet from these GWs:

<script language="javascript">
  var dados = 'dados.html';
  $(tabela).load(dados);
  setInterval(function() {
    $(tabela).load(dados);
  }, 2000);
</script>

Is there any way to access the data or query it directly from the source?

I appreciate your help and look forward to any solutions or recommendations you may have.

I integrated AJAX to fetch total calls from each gateway’s HTML and store them in a global variable. I expected the data to load dynamically every 5 seconds and display the correct call totals in the corresponding boxes on the webpage.

show pictures in html tabs (overwritten)

<html><head><title>Report</title>
<style> .tab {cursor: pointer; padding: 10px; display: inline-block;} </style>
</head><body>
<h1>Report</h1>
<div class="tabs">
<span class="tab" onclick="showPlot('functionPlot')">Function Plot</span>
<span class="tab" onclick="showPlot('secondDerivPlot')">Second Derivative Plot</span>
</div>
<div id="plotContainer">
<img id="functionPlot" src="val_0.png" style="display:block;">
<img id="secondDerivPlot" src="deriv_0.png" style="display:block;">
</div>
<script>
function showPlot(plotID) {
document.getElementById("functionPlot").style.display = "none";
document.getElementById("secondDerivPlot").style.display = "none";
document.getElementById(plotID).style.display = "block";
}
</script>
</body></html>
<div class="iteration-summary">
<h2>Iteration 1</h2>
<div id="plotContainer">
<img id="functionPlot" src="val_1.png" style="display:block;">
<img id="secondDerivPlot" src="deriv_1.png" style="display:none;">
</div>
</div>

In this example, I create a html page with two tabs. When I click on Function Plot, I want to see the pictures val_0.png and val_1.png. Similarly, Second Derivative Plot should depict deriv_0.png and deriv_1.png.

Function Plot shows indeed the correct pics, but Second Derivative Plot shows deriv_0.png and val_1.png. What am I doing wrong?

React why state is updated through children but not updated through render props

I’m facing an issue with updating the value of a textarea in React when passing it through props. I have a modal component where I pass a textarea via a text prop. However, when the parent component’s state changes, the textarea content doesn’t update as expected.

Here’s an example of my code:

<ModalWithButton
  buttonText="Show"
  text={() => (
    <textarea
      value={description ?? ''}
      onChange={(e) => handleDescriptionChange(e.target.value)}
    />
  )}
/>

When I update the description state, the textarea does not re-render with the new value. I solved the problem by passing the textarea through children instead of using the text prop, and it worked:

<ModalWithButton
  buttonText="Show"
  buttonClassName="px-2"
  actionText="Close"
>
  <textarea
    value={description ?? ''}
    onChange={(e) => handleDescriptionChange(e.target.value)}
  />
</ModalWithButton>

Question: Why does the textarea not update when passed via the text prop, and why does passing it through children solve the issue?

Remark:

  • I change state through react context
  • For modal I use headlessUI Transition and Dialog components

Making div the same width as grandparent

I am working on a school project in react where the goal is to build a website which will display movies collected from a database. When a movie is clicked a small description box is opened underneath. The problem I’m having is that the box that appears is the same width as the movie box, whereas I want it to take up the full space of the row. See image for illustration.Ilustration of problem
here is the part of my code that has the problem. It is consisting of two react components and a css file

type here
import { useState } from 'react';
import FilmBild from './assets/filmBild.jpg';
import SingleMovieGridElement from "./SingleMovieGridElement.jsx";

function MovieGrid() {

    const [selectedMovieId, setSelectedMovieId] = useState(null);

    const handleMovieClick = (movieId) => {
        if (selectedMovieId === movieId) {
            setSelectedMovieId(null); // Om samma film klickas igen, stäng av beskrivningen
        } else {
            setSelectedMovieId(movieId);
        }
    };

    return (
        <div className="container">
            <div className="row gx-4 gy-4"> {/* gx-4 ger horisontell space, gy-4 ger vertikal space */}

                <SingleMovieGridElement handleMovieClick={handleMovieClick} selectedMovieId={selectedMovieId} />
                <div className="card mt-2 movie-description">

                </div>

            </div>
        </div>
    );
}



{/*

*/}
export default MovieGrid;

import { useOutletContext } from 'react-router-dom';
import { useLoaderData } from 'react-router-dom';
//import {useState} from "react";


function SingleMovieGridElement({handleMovieClick, selectedMovieId}) {

    //const [handleMovieClick, selectedMovieId] = useOutletContext()

    const movies = useLoaderData();
    console.log("filmer")
    console.log(movies)

    return(

        <>

        {movies.map((movie) => (
                <div key={movie.details.id} className="col-lg-4 col-md-6 col-sm-12">
                    <div className="card">
                        <img
                            src={`https://image.tmdb.org/t/p/original/${movie.details["poster_path"]}`}
                            className="card-img-top img-fluid"
                            alt={movie.details["original_title"]}
                            onClick={() => handleMovieClick(movie.details.id)} // Klicka för att visa beskrivningen
                        />
                        <div className="card-body">
                            <h5 className="card-title"
                                style={{ fontSize:'1rem' }}>
                                {movie.details["original_title"]}</h5>
                        </div>
                    </div>

                    {/* Shows description for the selcted movie */}
                    {selectedMovieId === movie.details.id && (
                        <div className="card mt-2 movie-description">
                            <div className="card-body">
                                <p>{movie.details["overview"]}</p>
                            </div>
                        </div>
                    )}
                </div>
            ))}
    </>)
}

export default SingleMovieGridElement;
#root {
  max-width: 1280px;
  margin: 0 auto;
  padding: 2rem;
  text-align: center;
}

.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}
.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
  filter: drop-shadow(0 0 2em #61dafbaa);
}

@keyframes logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@media (prefers-reduced-motion: no-preference) {
  a:nth-of-type(2) .logo {
    animation: logo-spin infinite 20s linear;
  }
}

.card {
  padding: 2em;
}

.read-the-docs {
  color: #888;
}


.card {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 350px; 
}

.card-img-top {
  max-height: 200px;
  object-fit: cover; 
}

.card-body {
  flex: 1; 
  padding: 15px;
  display: flex;
  flex-direction: column;
  justify-content: space-between; 
}

.card-title {
  font-size: 1rem;
  font-weight: bold;
  line-height: 1.4; 
  overflow: hidden; 
  text-overflow: ellipsis; 
  white-space: normal; 
  height: 50px;  
  display: -webkit-box;
  -webkit-line-clamp: 2; 
  -webkit-box-orient: vertical;
}

.card-body p {
  flex: 1;
  font-size: 0.875rem;
  color: #666;
  overflow: hidden; 
  text-overflow: ellipsis; 
  white-space: normal; 
  height: 70px; 
}



.movie-description {
  width: 100%; 
  height: 300px; 
  overflow-y: auto; 
}

.row {
  position: relative;
}



I have tried playing with setting the position of movie-description to absolute and left:0; and setting the position of .row to relative so that it fills the space. This kind of fixes the width part, it’s a little off but not terrible. the problem however is that the rest of the movie boxes ends up on top of the description box. I believe that a large part of the problem is that the description box is contained by the size of the movie box in some sense and therefore it’s so problematic. This is my first course in web programming som I’m very new to this. Any help is very much appreciated.

whats the best way to do front end scripting in asp.net mvc? [closed]

What i want to do is have a list of ingredients with abutton next to each one which will add them to a meal. after i add them to a meal i then want to submit a form which will add the meal to the database

But that requires passing a list to JavaScript then passing it back to csharp to add this to the database server side.

is there an easier way?

i’ve looked at blazor but can i do MVC using Blazor?

Here’s what i want to do any way any help would be appreciated

Thank you enter image description here