sorting by date from firestore firebase

I am working with this
enter image description here

However, when I get the data, i have not been able to find a way to sort this. Ideally, Emma should be above Matt when I get the data.

I tried a simple JS .sort() where a.long - b.long, but no go there. Is there a good way to handle this? I am in charge of collection(s), I can edit the data accordingly to make it easier to get.

var birthdays = [];

db.collection("birthdays").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        // doc.data() is never undefined for query doc snapshots
        console.log(doc.id, " => ", doc.data());
        //birthdays.push(doc.data());
        //var birthdayDivString = '<div class="col-6">'+doc.data().name+'</div><div class="col-6">sort birthdays</div>';

        const sortedMessages = Object.values(snapshot.data()).sort((a, b) => a.long - b.long)

        birthdays = sortedMessages;

        //$("#birthdayDiv").append(birthdayDivString);

    });


});

How to remove hashchange event listener based on flag condition in JavaScript?

Am trying to remove the hashchange event listener based on the flag i have set as shown below;

window.addEventListener("hashchange", function(e) {
    if (isPopupOpen){
    
   popup.classList.remove('active');
      
       popup.style.transform = 'translateY(25%)';
       popup.style.height = '75%';
        
       //popup.style.display = "none";
       isPopupOpen = false;
        
      document.head.appendChild(con);
      popcontainer.style.display = "none";
    } 

   // This did not remove the hashchange event listener;
    if (!isPopupOpen){  window.removeEventListener("hashchange", this)
    }
  });

I have tried to remove the event listener when isPopupOpen flag is false but that did not work.

Kindly help.

Why is my discord.js bot not reacting to images/media?

This discord bot is made to react to images/media in any #meme channels however, it doesn’t react to any media. But there are no errors in the code and it boots up just fine and logs everything fine. what could be the issue?

const { GatewayIntentBits } = require('discord.js');
const { Client } = require('discord.js');
const TOKEN = ""


const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
    GatewayIntentBits.GuildMessageReactions
  ],
});

client.on("ready", () => {
  console.log(`${client.user.tag} is online`);
});

client.on('messageCreate', (message) => {
  console.log(`message sent in ${message.channel.name}`);
  if (
    message.channel.name === 'memes' &&
    message.attachments.size > 0 &&
    message.attachments.some((attachment) => {
      const validExtensions = ['.mp4', '.gif', '.jpg', '.png', '.webm'];
      return validExtensions.some((ext) => attachment.url.endsWith(ext));
    })
  ) {
    message.react('⭐');
  }
});

client.login(TOKEN);

Request failed with status code 405 Nextjs 14

Im using NextJs 14 and I get this error 405:

GET http://localhost:3000/api/products 405 (Method Not Allowed)
Uncaught (in promise) AxiosError

products.js

"use client"
import { useState } from 'react';
import Layout from '../../../components/Layout'
import axios from 'axios'

import { useRouter } from 'next/navigation'


export default function NewProduct() {
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [price, setPrice] = useState("");
  const [goToProducts, setGoToProducts] = useState(false);
  const router = useRouter();

  async function createProduct(e) {
    e.preventDefault();
    const data = { title, description, price };

    await axios.post("/api/products", data)
    setGoToProducts(true);
    router.push("/products");
  }

app/api/products/route.js


import { Product } from '../../../models/Product'
import { mongooseConnect } from '../../lib/mongoose'

export default async function handle(req, res) {
    const {method} = req;
    await mongooseConnect()

    if(method === 'GET') {
        res.json(await Product.find())
    }

    if(method === 'POST') {
        const {title, description, price} = req.body;
       const productDoc = await Product.create({
            title, description, price,
        })
        res.json(productDoc)
    }
}

For Desktop and ios , is there any way to make video from image and text message

the script for ai based video from image and text

Image to Video Generation refers to the task of generating a sequence of video frames based on a single still image or a set of still images. The goal is to produce a video that is coherent and consistent in terms of appearance, motion, and style, while also being temporally consistent, meaning that the generated video should look like a coherent sequence of frames that are temporally ordered. This task is typically tackled using deep generative models, such as Generative Adversarial Networks (GANs) or Variational Autoencoders (VAEs), that are trained on large datasets of videos. The models learn to generate plausible video frames that are conditioned on the input image, as well as on any other auxiliary information, such as a sound or text track.

looking for guidelines

Retaining DDL Selected Value from Validation Errors on Submit (CSHTML, JS)

Trying to figure out if I have painted myself into a corner.

I have and ASP.NET MVC application form where I dynamically change a group of questions based upon a dropdown box selection. So the user will see a generic form, has the ability to refine the request and as they select different options, I use a change event on the dropdown to then show or hide divs for the section of questions.

My Javascript :

            <script type="text/javascript">
                $(function () {
                    $('div.login').hide();
                    $('div.normal').show();//by default, display the normal div
                    $('div.login.SignUp').show();//by default, display the normal div
                    $("#ddl_select").change(function () {
                        var currentdiv = $("div." + $(this).val());
                        currentdiv.show(); //based on the selected value to show the relevant div.

                        $('div.login').not(currentdiv).hide(); //hide other div
                    });
                });
            </script>

My Dropdown box :

    <select id="ddl_select" name="userSelection">
          <option value="SignUp">Sign Up</option>
          <option value="ReportABug">Report a Bug</option>
          <option value="Feature">Feature Request</option>
    </select>

and then in my .cshtml I will have my divs named as such:

<div class="login SignUp">
     <div class="form-row pt-2 px-3 pb-3">
        Form field details here 
    </div>
            </div>
            <div class="login ReportABug">
                    <div class="form-row pt-2 px-3 pb-3">
        Form field 1 details here   
    </div>
                    <div class="form-row pt-2 px-3 pb-3">
        Form field 2 details here   
    </div>
                    <div class="form-row pt-2 px-3 pb-3">
        Form field 3 details here   
    </div>
            </div>

etc…

All and all this works for changing the display of the form, but when I start adding in validation like required, string lengths, etc. The validations fire properly, but I lose the selection I was on. So if SignUp is my default section exposed, but the user selects ReportABug, fills out the form and submits, after the validation rules on the model are fired, if there are any failures, they are returned back and actually display properly, but the page returns back to its inital state (SignUp) being initial display. If the user selects ReportABug again from the dropdown, the previous data and error messages are there and properly displayed, I am just trying to figure in how from retain the selection and have so the user retains the selection.

Maybe I have to set a session varible anytime the validation is fired and then check where that exists etc.

‘accept’ attribute in the input file type doesn’t prevent the file to be stored in the ‘State’

I have react app and I want to take file from the user and send it to the backend. The problem is when I set the accept attribute to accept only audio files it allows other files when you choose to show all the file in the file explorer.
Here is the code snippet for better understanding.

const FormCom: React.FC = () => {
  const [File, setFile] = useState<File | undefined>(undefined);

  useEffect(() => {
    console.log(File?.name);
  }, [File]);

  return (
    <div>
      <Container className="d-flex align-items-center  justify-content-center">
        <Row>
          <Col>
            <Form>
              <Form.Label htmlFor="THE_FILE">
                {File?.name ? File?.name : "Click here and choose the file"}
              </Form.Label>
              <Form.Control # KEEP IN MIND <Form.Control> IS AN INPUT ELEMENT. IT'S FORM REACT-BOOTSTRAP
                onChange={(x: React.ChangeEvent<HTMLInputElement>) =>
                  setFile(x.target.files?.[0])
                }
                type="file"
                name="THE_FILE"
                id="THE_FILE"
                accept="audio/*" 
              />
            </Form>
          </Col>
        </Row>
      </Container>
    </div>
  );
};

export default FormCom;

if you try it yourself you will see in the console that it’s accept anything. Should I make a Checker function for that. Check if the file extension is correct then set it to the State or did I miss something in the input element.

removing event listeners for all elements inside html collection

I am working on this new project in which I need to add and remove event listeners to the HTML collection elements like so:

function Gameboard(){
    const board = [[Cell(),Cell(),Cell()],[Cell(), Cell(), Cell()],[Cell(), Cell(), Cell()]]
    const getBoard = () => board;
    const addToken = (row, column) => {
      board[row][column] = "token";
    } 
    // this is the board display container
    const container = document.querySelector(".container");
    const cells = container.children;

    return {getBoard, addToken, cells}
}

const board = Gameboard()

This is only a portion of the Gameboard function so if you need further clarification I can provide.

The final const board = Gameboard() variable declaration is the one that is used in the below code.

const playGame = () => {
        for (let i=0; i<board.cells.length; i++){
            const listener = (e) => {
                if(e.target.innerText===""){
                    const row = Math.floor(i/3);
                    const column = i%3;
                    board.addToken(row, column, activePlayer.token)
                    if(!checkGameOver()){
                        switchPlayerTurn()
                    }
                    else{
                        for(let j=0; j<board.cells.length; j++){
                            board.cells[j].removeEventListener("click", listener)
                        }
                    }
                }
            }
            board.cells[i].addEventListener("click", listener)
        }
    }

So here I want to remove event listeners for every cells[] element.

I tried to loop through the html collection inside the event listener and remove every event listener but it only removes the event listener of the element that caused the checkGameOver function to be true

Quicktime – The document “video.mov Could Not be Opened

I am working on a program that allows you to screen record a screen after clicking a button. Once the recording is finished, a user is able to download the video by clicking another button. When attempting to open the video with Quicktime Player, it appears that it is unable to be opened. Here is the main.js snippet that shows how the blob is created, as well as the blob console logged out.

function handleDataAvailable (e) {
    chunks.push(e.data);
}

function handleStop (e) {
const blob = new Blob(chunks, { 'type' : 'video/mp4' });
chunks = [];

downloadButton.href = URL.createObjectURL(blob);
downloadButton.download = 'video.mp4';
downloadButton.disabled = false;

recordedVideo.src = URL.createObjectURL(blob);
recordedVideo.load();
recordedVideo.onloadeddata = function() {
    const rc = document.querySelector(".recorded-video-wrap");
    rc.classList.remove("hidden");
    rc.scrollIntoView({ behavior: "smooth", block: "start" });

    recordedVideo.play();
}

stream.getTracks().forEach((track) => track.stop());
audio.getTracks().forEach((track) => track.stop());

console.log('Recording stopped');

}

Warning from Quicktime

Blob log

Do you need to sanitize an input element if it is not submitted?

As a super simple example, if you had something like this to just quickly give 50% of the current input:

<input type="number" class="number">
<br/>
50% of that is:<span class="result"></span>

<script>
  document.querySelector('.number').addEventListener("keyup", () => {
    const input = document.querySelector('input.number').value;
    const output = (50 / 100) * input;
    document.querySelector('.result').innerText = output;
  });
</script>

Is it necessary to do any sort of sanitization on the user input – or – is there no risk because it all happens on the frontend?

I know it’s good practice to always sanitize things, but is there any real risk in this use-case?

Snippet posted above shows a simple example.

Targeting Data in a .map with onClick

So I have the following code:

const test = (e) => {
  console.log('example:', e.target.item.attributes.dataIWant);
}

{records.map((item, index) => {

        return (
          <>
            <Accordion key={index}>
              <AccordionSummary  onClick={test(item)} expandIcon={<ExpandMoreIcon />} aria-controls="panel1a-content" id="panel1a-header">
                <Typography>{item.attributes.name} {item.attributes.date}</Typography>
              </AccordionSummary>
            </Accordion>
          </>
        )
      })}

This is using react material UI, I have a collection of data in records, that I am mapping through. This creates and accordion panel that you can click to see accordion details.

When i click one of those panels, i want to grab a specific piece of data from the data set. Lets call it item.attributes.id

Generally i would assume to grab it with the event, to target that specific panels click/data set. But it doesn’t seem to be working, just getting item is undefined.

So what am I missing here?

How to change the style of a geojson feature on a click event in react leaflet

I am working on a react app with react leaflet. When you click on a country on the leaflet map, the country is supposed to change style (turn a different colour). I can’t get this to work. In the current implementation the mouseover, and mouseout events work, but not click. At the moment, the click changes the style for a split second during the click event, then returns to the default style. I need the color change to be persist beyond the click event

If anyone has any idea how to fix this, I would be very grateful:

App.jsx

function App() {
  const {
    fetchCountryData,
    fetchPeopleIndicatorData,
    fetchEconomicIndicatorData,
    fetchEnvironmentIndicatorData,
  } = useCountryData();

  const [clickedCountry, setClickedCountry] = useState(null);
  const [countryData, setCountryData] = useState([]);
  const [peopleIndicatorData, setPeopleIndicatorData] = useState([]);
  const [environmentIndicatorData, setEnvironmentIndicatorData] = useState([]);
  const [economicIndicatorData, setEconomicIndicatorData] = useState([]);
  const [sidebarIsOpen, setSidebarIsOpen] = useState(false);

  const handleCountryClick = async (country) => {
    if (clickedCountry === country) {
      setClickedCountry(null);
      setSidebarIsOpen(false);
    } else {
      setClickedCountry(country);
      const countryData = await fetchCountryData(country.properties.ISO_A3);
      setCountryData(countryData);
      setPeopleIndicatorData(
        await fetchPeopleIndicatorData(country.properties.ISO_A3)
      );
      setEconomicIndicatorData(
        await fetchEconomicIndicatorData(country.properties.ISO_A3)
      );
      setEnvironmentIndicatorData(
        await fetchEnvironmentIndicatorData(country.properties.ISO_A3)
      );
      setSidebarIsOpen(true);
    }
  };

  const defaultStyle = {
    fillColor: "#000",
    fillOpacity: 0.7,
    weight: 3,
    opacity: 0.7,
    dashArray: 3,
    color: "black",
  };

  const highlightStyle = {
    fillOpacity: 0.7,
    weight: 5,
    dashArray: "",
    color: "#807c7c",
    fillColor: "#ffffff",
  };

  const clickStyle = {
    fillColor: "#fa0000",
    fillOpacity: 1,
    weight: 5,
    opacity: 1,
    dashArray: "",
    color: "#807c7c",
  };

  const onEachCountry = (country, layer) => {
    layer.on({
      click: (e) => {
        e.target.setStyle(clickStyle);
        handleCountryClick(country);
      },
      mouseover: (e) => {
        if (clickedCountry !== country) {
          e.target.setStyle(highlightStyle);
        }
      },
      mouseout: (e) => {
        if (clickedCountry !== country) {
          e.target.setStyle(defaultStyle);
        }
      },
    });
  };

  const handleSidebarClose = () => {
    setClickedCountry(null);
    setSidebarIsOpen(false);
  };

  return (
    <div className="App">
      <div className="map-container">
        <MapContainer>
          <TileLayer
            url="https://api.maptiler.com/maps/basic-v2/{z}/{x}/{y}.png?"
          />
          <GeoJSON
            data={countriesData.features}
            style={defaultStyle}
            onEachFeature={onEachCountry}
          />
        </MapContainer>
      </div>
    </div>
  );
}

export default App;

Prerendering with Angular 17 and viewing prerendered results?

I’m trying to get a better understanding of how prerendering with Angular 17 works under the hood. I just tried it out and wrote and article about how to get it to work.

https://fireflysemantics.medium.com/creating-an-angular-application-with-route-prerendering-39d6cd4df22a

And I see the routes being prerendered in dist/ssr/browser. However when looking inside any of the static index.html pages, there’s no visible data.

For example the page for the product/bronco looks like this:

<!DOCTYPE html><html lang="en" data-critters-container><head>
  <meta charset="utf-8">
  <title>Ssr</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="styles-5INURTSO.css"></head>
<body><!--nghm-->
  <app-root _nghost-ng-c3984273398 ng-version="17.0.6" ngh="0" ng-server-context="ssg"><router-outlet _ngcontent-ng-c3984273398></router-outlet><!----></app-root>
<script src="polyfills-LZBJRJJE.js" type="module"></script><script src="main-EEDU2CCN.js" type="module"></script>

<script id="ng-state" type="application/json">{"__nghData__":[{"c":{"0":[]}}]}</script></body></html>

So I’m guessing the data is loaded with the module script:

</script><script src="main-EEDU2CCN.js" type="module"></script>

And just wanted to confirm?