firestore not returning any indication that a new document add was succesful or not

I think this is not right, or i am the one not doing it well, so when i add a new document to the firestore collection, i can use the ref to get the id, but when i pass a wrong collection name, I still get the same response, why isn’t firestore throwing an error.

async function addDoc(collection, data) {
    try {
        const db = admin.firestore();
        const ref = await db.collection(collection).doc() //add(data);
        ref.set(data);
        console.log("Document successfully added!", ref);
    }
    catch (err) {
        console.log("Error adding document: ", err);
    }
}

i want to know why this is behaving like this, and how to detect if the new document was created. Thanks

How to setup Firebase Cloud Messaging v9 in React?

I’m having trouble setting up my firebase environment in React.
I’m going through the firebase documentation, but I can’t seem to get the first step of getting permission correct.

I tried looking everywhere to fix these errors, but all attempts failed. Please help!

Errors:

Service worker registration failed, error: TypeError: Failed to register a ServiceWorker for scope ('http://localhost:8080/') with script ('http://localhost:8080/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script.
An error occurred while retrieving token.  FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:8080/firebase-cloud-messaging-push-scope') with script ('http://localhost:8080/firebase-messaging-sw.js'): A bad HTTP response code (404) was received when fetching the script. (messaging/failed-service-worker-registration).

Code:

src/index.js

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('../firebase-messaging-sw.js')
  .then(function(registration) {
    console.log('Registration successful, scope is:', registration.scope);
  }).catch(function(err) {
    console.log('Service worker registration failed, error:', err);
  });
}
src/firebase.js

import { initializeApp } from "firebase/app";
import { getMessaging, getToken } from "firebase/messaging";

const firebaseApp = initializeApp({
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: ""
});

const messaging = getMessaging(firebaseApp);
    
export const fetchToken = async (setToken) => {
  await getToken(messaging, { vapidKey: KEY_PAIR }).then((currentToken) => {
    if (currentToken) {
      setToken(currentToken)
    } else {
      console.log('No registration token available. Request permission to generate one.');
    }
  }).catch((err) => {
    console.log('An error occurred while retrieving token. ', err);
  });
}
public/firebase-messaging-sw.js

import { initializeApp } from "firebase/app";
import { getMessaging, onBackgroundMessage } from "firebase/messaging/sw";

const firebaseApp = initializeApp({
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: ""
});

const messaging = getMessaging(firebaseApp);

onBackgroundMessage(messaging, (payload) => {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: ''
  };

  self.registration.showNotification(notificationTitle, notificationOptions);
});

I am attempting to get my react application deployed via github pages

It works perfectly fine when I boot it up on LOCALHOST(npm start) but when it’s deployed, it doesn’t display my pages and components calls inside my App.js I am using react-router-dom (version 6.0.2).

APP.JS:

import React from "react";
import Navbar from "./components/Navbar/Navbar";
import Footer from "./components/Footer/Footer";
import {
  BrowserRouter,
  Routes,
  Route
} from "react-router-dom";
import Home from "./pages/Home";
import Search from "./pages/Search";
import Compare from "./pages/Compare";

function App() {
  return (
  <>
    <BrowserRouter>
      <Navbar />
      <Routes>
        <Route path="/" exact element={<Home />} />
        <Route path="/search" element={<Search />} />
        <Route path="/compare" element={<Compare />} />
      </Routes>
      <Footer/>
    </BrowserRouter>
  </>
  );
}

export default App;


Link to repo: https://github.com/ntommy06/CS410P-FinalProject

Looping through Buttons to get their Src attribute if selected

I’m using vanilla javascript and currently trying to loop through each button. If the button if clicked, change some .style attributes and push the image.src into an array. I’m having trouble creating code that can selected multiple .src’s but not ALL of the srcs. Even if they aren’t clicked all the .src’s still show up on my console. I just am at a total blank.

for (let i = 0; i < favoriteBtn.length; i++) {
  let btn = favoriteBtn[i];
  let favoriteTheme = false;
  let imgCard = document.getElementsByClassName("card");

  btn.addEventListener("click", () => {
    for (let i = 0; i < Array.from(imgCard).length; i++) {
      let card = imgCard[i].src;

      if (favoriteTheme == false) {
        btn.style.backgroundColor = "red";
        btn.style.color = "white";
        favoriteTheme = true;
        // images.push(`'${card}'`);
      } else {
        btn.style.backgroundColor = "";
        btn.style.color = "";
        favoriteTheme = false;
      }
    }
  });
}

Getting Promise Pending in selenium for a web element used in an assertion

I am just trying to run a simple test using selenium with chai library for assertion. Webdriver executes a script to set a token for login. I can see on the UI that it login fine but the test fails on the assertion with web element status being promise pending. Any idea what am i missing here. thanks!

Here is the piece of code

const {Builder, By, Key, until} = require('selenium-webdriver');
let chai = require('chai');
let expect = chai.expect;
require('chromedriver');

(async function example() {
    let driver = await new Builder().forBrowser('chrome').build();
        await driver.get('http://localhost:4200/login');
        driver.executeScript('window.localStorage.setItem("token", "xyz");');
        driver.executeScript('window.localStorage.setItem("lastAction", "' + Date.now() + '");');
        await driver.wait(until.titleIs('XXXX'), 1000);
        expect(driver.findElement(By.id('welcome-header')).getText()).to.equal('ZZZZZ');

})();

And below is the error what i get

expect(driver.findElement(By.id('welcome-header')).getText()).to.equal('ZZZZZ');
                                                                         ^
AssertionError: expected {} to equal 'ZZZZZ'
    at example (******e2e-spike-copytestslogin_test_copy.js:13:74)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  showDiff: true,
  actual: Promise { <pending> },
  expected: 'ZZZZZ',
  operator: 'strictEqual'
}

Select Dropdown, make default Value not a selectable option

I have a form I want users to fill out. I have an array of options they can choose from but I don’t want any of them to be the default. I would like the drop down to say something like –Select– . Then when the users selects the dropdown, they can no longer select –Select–.

I am using Redux forms and React-Bootstrap for the presentation. I seen some answers on Stack Overflow, they say set the option to disable or add it as an option group. This resolve how it behaves when the dropdown opens but removes that option as a default option.

  let selectOptions = options.map((option, index) => {
    return (
      <option key={index} value={option}>
        {option}
      </option>
    );
  })
  const {value, ...inputs} = input
  
    return (
    <Aux>
      <Form.Label className="mb-1">{label}</Form.Label>
      {explanation && !readonly ? (
        <OverlayTrigger
          trigger="click"
          key={"right"}
          placement={"right"}
          overlay={
            <Popover id="popover-basic">
              <Popover.Header as="h3">{label}</Popover.Header>
              <Popover.Body>{explanation}</Popover.Body>
            </Popover>
          }
        >
          <i className="material-icons text-info align-top ml-2 cursor">help</i>
        </OverlayTrigger>
      ) : null}
      <Form.Control
        className={`${formStyle} ${validationStyle} ${noValidationStyle}`}
        disabled={readonly}
        as="select"
        placeholder="select"
        {...input}
        isInvalid={(touched || attempt) && !!error}
        isValid={!error}
      >
        {selectOptions}
      </Form.Control>

      {(touched || attempt) && !!error && !readonly ? (
        <Form.Control.Feedback type="invalid" className="animated fadeIn">
          {error}
        </Form.Control.Feedback>
      ) : (
        <span>{"u00A0"}</span>
      )}
    </Aux>

How to load ajax to the table (authorization is success now in console log on html)

after a few error and trials i have managed to authorize my data and load into the html but however now how can i call the api from database and load into my table

here the code for my file

<table id="infoTable" class="table" style="width: 920px; margin: 0; padding: 0; border: 0;">
                                <thead>
                                  <tr>
                                    <th scope="col" style="text-align: justify;"> </th>
                                    <th scope="col" style="text-align: center; padding-right: 2px;"></th>
                                    <th scope="col" style="text-align: center;"></th>
                                  </tr>
                                </thead>
                                <tbody>
                                  <tr>
                                    <td scope="row" style="padding-left: 45px;"></td>
                                    <td style="text-align: center;"></td>
                                    <td style="text-align: center;"></td>
                                  </tr>
                                
                                </tbody>
                                
                              </table>  

here the ajax file

$.ajax({
                                // The url that you're going to post
                                /*

                                This is the url that you're going to put to call the
                                backend api,
                                in this case, it's
                                https://ecoexchange.dscloud.me:8080/api/get (production env)

                                */
                                url:"https://ecoexchange.dscloud.me:8080/api/get",
                                // The HTTP method that you're planning to use
                                // i.e. GET, POST, PUT, DELETE
                                // In this case it's a get method, so we'll use GET
                                method:"GET",
                                // In this case, we are going to use headers as
                                headers:{
                                    // The query you're planning to call
                                    // i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
                                    query:"RecyclableGet(0)",
                                    
                                    // Gets the apikey from the sessionStorage
                                    apikey:sessionStorage.getItem("apikey")
                                },
                    
                                success:function(data,textStatus,xhr) {
                                    

                                        console.log(data);
                                },
                                error:function(xhr,textStatus,err) {
                                    console.log(err);
                                }
                            });

So this is all i have currently i trying to load my database into the table but so far i am receiving is a blank empty table, needed some help and advise here
Thanks

how to use chrome.history.addUrl with custom time

How can I use chrome.history.addUrl with custom time?
So right now chrome.history.addUrl adds a URL with current time, so how can I change it so it can add URL to a different time?

Can I maybe change chrome’s time?
or change the time when chrome is saving into database?

Basically I am trying to genereate a custom chrome browser history.

Why does my api ajax request pull undefined?

I am trying to call my API with a search term from a submit form but I can get an error stating cannot read properties of undefined, I am not sure why there is no data when I send the ajax request, below is my code.

$(function (){
   let searchform = $('#searchForm')
     searchform.on("submit",function(event){

        event.preventDefault();
        newNameInput = $('#search_term')
        let searchterm = newNameInput.val();
        console.log(searchterm)
        $('#showList').empty();
        $.ajax({
            method: 'GET',
            url: 'http://api.tvmaze.com/search/shows?q='+searchterm,
            success: function(movies){
                $.each(movies, function(i,movie){
                    $('#showList').append('<li class="list"><a href="'+ movie._links.self.href+'">'+ movie.show.name +'</a></li>')
                    $('#showList').show();
                })
            }
        })
    
    }) 
})

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">
    <title>TV Shows</title>
</head>
<body>
    <h1>TV Shows</h1>
    <div id="show" hidden></div>
    <ul id="showList" hidden></ul>
    <form id="searchForm">
        <input type="text" id="search_term">
        <label for="text">Search</label>
        <button>Submit</button>
    
    </form>
    <a id="homelink" href="/" hidden>Back to All Shows</a>
    
    <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
        crossorigin="anonymous"></script>
    <script src="/public/js/index.js"></script>
</body>
</html>

When I check the URL it returns data correctly but does not from Ajax.

http://api.tvmaze.com/search/shows?q='+searchterm

Masonry and JQuery

I am trying to reload my masonry each time I add item to my with an ajax query. However, it seems the recalculation of the masonry (I mean the display of each bloc) is never finished.

Each video bloc is hovering each other after load once I reexecute manually

$grid = $('#masonry').masonry({
        itemSelector: ".video-box",
        percentPosition: true,
      });

Does anyone see the reason why in my code ?

Ajax function called (load() is called each time the bottom of the page is crossed and at the first page load)

    function load(recherche, start=0, limit=20, handlerEndPage) {
  console.log(start)
  console.log(limit)
  //$(document).bind("scroll", handlerEndPage);

  $("#loader_active").show()
  let form_data = new FormData();
  form_data.append('recherche', recherche);
  form_data.append('start', start);
  form_data.append('limit', limit);


  $.ajax({

    url: "http://siteurl.com/ajax/videos.php",
    contentType: false,
    dataType: "json",
    processData: false,
    cache: false,
    data: form_data,
    type: 'POST',

    success: function (data) {
      if (data.length != 0){

        $grid = $('#masonry').masonry({
          itemSelector: ".video-box",
          percentPosition: true,
        });

        $(data).each(function(index, value) {
          if (value.id_video != null){
            $item = $(showVideo(value, false));
            $grid.append($item).masonry('appended', $item);
          }
        })


        console.log("bind")
        setTimeout(function(){
          $(document).unbind("scroll", handlerEndPage);
          $(document).bind("scroll", handlerEndPage);
        }, 300);

        // Scroll top items
        const scrollButtons = document.querySelectorAll(".scroll-btn"),
            searchesWrapper = document.querySelector(".searches-wrapper");

        var amount = 0;
        scrollButtons.forEach((btn, i) => btn.addEventListener("click", () => {
          let direction = i > 0 ? "-" : "+";

          amount = eval(`${amount} ${direction} ${searchesWrapper.offsetWidth}`);
          searchesWrapper.style.setProperty("--scroll", amount + "px");

          if (amount >= 0) {
            scrollButtons[0].disabled = true;
          } else {
            scrollButtons[0].disabled = false;
          }

          if (Math.abs(amount - searchesWrapper.offsetWidth) >= searchesWrapper.scrollWidth) {
            scrollButtons[1].disabled = true;
          } else {
            scrollButtons[1].disabled = false;
          }
        }));

        // Videos


        // Masonry Layout
        //$('#masonry').masonry('reloadItems')

        //$('#masonry').masonry({
        //  itemSelector: ".video-box",
        //  percentPosition: true,
        //});

      }
      else {
        console.log("Aucune video restante.")
        console.log("unbind")
        $(document).unbind("scroll", handlerEndPage);
      }

      $("#loader_active").hide()

      // Evénement : Aucune vidéo retournée

      if ($(".bgVideo").length == 0){
        console.log("Aucun resultat trouvé")
        $("#aucun_resultat").show()
      }
      else {
        console.log("Des résultats ont été trouvés")
        $("#aucun_resultat").hide()
      }

      $grid = $('#masonry').masonry({
        itemSelector: ".video-box",
        percentPosition: true,
      });

    }
  })
}

Page before ajax call

<!DOCTYPE html>
<html lang="fr" xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://ogp.me/ns/fb#">
    <head>
        <title>Tok Tok</title>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=0" />

        <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous" />
        <link href="http://siteurl.com/css/style.css" rel="stylesheet" />

        <link href="http://siteurl.com/css/style-toktok.css" rel="stylesheet" />
        <link rel="preconnect" href="https://fonts.gstatic.com" />
        <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500;600;700&display=swap" rel="stylesheet" />
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />

        <link rel="shortcut icon" href="http://siteurl.com/favicon.ico" type="image/x-icon" />
        <link rel="apple-touch-icon" href="http://siteurl.com/image/grey_grenouille.png" />
        <link rel="icon" href="http://siteurl.com/favicon.ico" type="image/x-icon" />
        <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
        <script src="https://kit.fontawesome.com/566683bca0.js" crossorigin="anonymous"></script>
        <script src="https://unpkg.com/masonry-layout@4/dist/masonry.pkgd.min.js"></script>
    </head>

    <script src="http://siteurl.com/js/showVideo.js"></script>
    <script src="http://siteurl.com/js/load.js"></script>

    <body>
        <header>
            <div class="wrapper">
                <form class="search-box">
                    <input type="search" name="search" id="search" placeholder="Rechercher ..." />
                    <button id="search-btn">
                        <span id="clear" onclick='$("#search").val("");' class="material-icons">search</span>
                    </button>
                </form>
                <button type="button" id="upload-btn">
                    <span class="material-icons">video_call</span>
                    <span>Upload</span>
                </button>
                <button type="button" id="sign-in-btn">
                    <span class="material-icons">account_circle</span>
                    <span>Sign in</span>
                </button>
                <nav id="menu" aria-hidden="true">
                    <div class="list">
                        <p class="list-title">List 1</p>
                        <ul>
                            <li><a href="#">Item 1</a></li>
                            <li><a href="#">Item 2</a></li>
                            <li><a href="#">Item 3</a></li>
                            <li><a href="#">Item 4</a></li>
                        </ul>
                    </div>
                    <div class="list">
                        <p class="list-title">List 2</p>
                        <ul>
                            <li><a href="#">Item 1</a></li>
                            <li><a href="#">Item 2</a></li>
                            <li><a href="#">Item 3</a></li>
                            <li><a href="#">Item 4</a></li>
                        </ul>
                    </div>
                    <div class="list">
                        <p class="list-title">List 3</p>
                        <ul>
                            <li><a href="#">Item 1</a></li>
                            <li><a href="#">Item 2</a></li>
                            <li><a href="#">Item 3</a></li>
                            <li><a href="#">Item 4</a></li>
                        </ul>
                    </div>
                    <div class="list">
                        <p class="list-title">List 4</p>
                        <ul>
                            <li><a href="#">Item 1</a></li>
                            <li><a href="#">Item 2</a></li>
                            <li><a href="#">Item 3</a></li>
                            <li><a href="#">Item 4</a></li>
                        </ul>
                    </div>
                </nav>
                <button type="button" id="menu-btn">
                    <span class="material-icons">menu</span>
                    <span class="material-icons">close</span>
                </button>
            </div>
        </header>

        <section id="searches">
            <div class="wrapper">
                <div class="searches-top">
                    <h1 class="section-title">Trending Searches</h1>
                    <div class="scroll-buttons">
                        <button type="button" class="scroll-btn" disabled>
                            <span class="material-icons">chevron_left</span>
                        </button>
                        <button type="button" class="scroll-btn">
                            <span class="material-icons">chevron_right</span>
                        </button>
                    </div>
                </div>
                <div class="searches-container">
                    <div class="searches-wrapper">
                        <a href="#" class="search-box">
                            <video src="http://siteurl.com/videos/511.mp4" preload="metadata"></video>
                            <p class="search-title">Search tag</p>
                        </a>
                        <a href="#" class="search-box">
                            <video src="http://siteurl.com/videos/510.mp4" preload="metadata"></video>
                            <p class="search-title">Search tag</p>
                        </a>
                        <a href="#" class="search-box">
                            <video src="http://siteurl.com/videos/505.mp4" preload="metadata"></video>
                            <p class="search-title">Search tag</p>
                        </a>
                        <a href="#" class="search-box">
                            <video src="http://siteurl.com/videos/506.mp4" preload="metadata"></video>
                            <p class="search-title">Search tag</p>
                        </a>
                        <a href="#" class="search-box">
                            <video src="http://siteurl.com/videos/507.mp4" preload="metadata"></video>
                            <p class="search-title">Search tag</p>
                        </a>
                        <a href="#" class="search-box">
                            <video src="http://siteurl.com/videos/508.mp4" preload="metadata"></video>
                            <p class="search-title">Search tag</p>
                        </a>
                        <a href="#" class="search-box">
                            <video src="http://siteurl.com/videos/492.mp4" preload="metadata"></video>
                            <p class="search-title">Search tag</p>
                        </a>
                        <a href="#" class="search-box">
                            <video src="http://siteurl.com/videos/493.mp4" preload="metadata"></video>
                            <p class="search-title">Search tag</p>
                        </a>
                        <a href="#" class="search-box">
                            <video src="http://siteurl.com/videos/494.mp4" preload="metadata"></video>
                            <p class="search-title">Search tag</p>
                        </a>
                        <a href="#" class="search-box">
                            <video src="http://siteurl.com/videos/495.mp4" preload="metadata"></video>
                            <p class="search-title">Search tag</p>
                        </a>
                        <a href="#" class="search-box">
                            <video src="http://siteurl.com/videos/496.mp4" preload="metadata"></video>
                            <p class="search-title">Search tag</p>
                        </a>
                        <a href="#" class="search-box">
                            <video src="http://siteurl.com/videos/497.mp4" preload="metadata"></video>
                            <p class="search-title">Search tag</p>
                        </a>
                        <a href="#" class="search-box">
                            <video src="http://siteurl.com/videos/498.mp4" preload="metadata"></video>
                            <p class="search-title">Search tag</p>
                        </a>
                        <a href="#" class="search-box">
                            <video src="http://siteurl.com/videos/499.mp4" preload="metadata"></video>
                            <p class="search-title">Search tag</p>
                        </a>
                    </div>
                </div>
            </div>
        </section>
        <section id="trending">
            <div class="wrapper">
                <h1 class="section-title">Dernières vidéos</h1>
                <div id="masonry" class="trending-container"></div>
            </div>
        </section>
    </body>

    <script src="http://siteurl.com/js/script.js"></script>
    <script>
        let start = 0;
        let limit = 30;

        // Gestion infinite scroll
        var handlerEndPage = function () {
            var deviceAgent = navigator.userAgent.toLowerCase();
            var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);

            if ($(window).scrollTop() + $(window).height() > $(document).height() - 100 || (agentID && $(window).scrollTop() + $(window).height() + 200 > $(document).height())) {
                load($("#search").val(), start, limit, handlerEndPage);
                start += limit;
                console.log("Fin de page détectée -> Chargement enclenché");
            }
        };

        $(document).bind("scroll", handlerEndPage);

        load("", start, limit, handlerEndPage);
        start += limit;

        // Gestion de la barre de recherche
        let old_search = "";
        let search = "";

        $("#clear").on("click", function () {
            setTimeout(function () {
                $("#videos").empty();
                $("#loader_active").show();
                search = $("#search").val();

                console.log("rechargement");
                start = 0;
                limit = 30;
                load(search, start, limit, handlerEndPage);
                start += limit;
            }, 100);
        });

        $("#search").on("keyup paste", function () {
            setTimeout(function () {
                $("#videos").empty();
                $("#loader_active").show();
                search = $("#search").val();

                console.log("rechargement");
                start = 0;
                limit = 30;
                load(search, start, limit, handlerEndPage);
                start += limit;
            }, 100);
        });

        // Gestion des Play/Pause de chaque vidéo
        $(document).on("click", ".video-box", function () {
            console.log("ok detected");
            if (this.children[0].paused) {
                console.log(this.children[0]);
                $(this).children("#video_tag").removeClass("pause");
                $(this).children("#video_tag").addClass("play");

                let playPromise = this.children[0].play();
                if (playPromise !== undefined) {
                    playPromise
                        .then((_) => {
                            // Automatic playback started!
                            // Show playing UI.
                        })
                        .catch((error) => {
                            // Auto-play was prevented
                            // Show paused UI.
                        });
                }
            } else {
                this.children[0].pause();
                $(this).children("#video_tag").removeClass("play");
                $(this).children("#video_tag").addClass("pause");
            }
        });
    </script>
</html>

ShowVideo function:

function showVideo(videoData, autoplay=false) {

    // VIDEO BOX

    let videoBox = $("<div/>", {
        class: "video-box",
        id: "append"
    });

    let video = $('<video />', {
        src: "http://siteurl.com/videos/" + videoData.lien,
        preload: "none",
        controls: false,
        autoplay: false,
        poster: "http://siteurl.com/thumbnails/"+videoData.id_video+".jpg",
        id : "video_tag"
    });

    let vidElements = $("<div/>", {
        class: "vid-elements"
    });

    // ICONS

    let stateIcon = $("<div/>", {
        class: "state-icon"
    });

    let playArrow = $("<span/>", {
        class: "material-icons"
    });
    playArrow = playArrow.html('play_arrow');

    let pause = $("<span/>", {
        class: "material-icons"
    });
    pause = pause.html('pause');

    stateIcon = stateIcon.append(playArrow)
    stateIcon = stateIcon.append(pause)

    vidElements = vidElements.append(stateIcon)


        //<div className="bottom-elements">
        //    <p className="vid-title">Meme title</p>
         //   <button type="button" className="favorite">
         //       <span className="material-icons">favorite</span>
        //    </button>
       // </div>


    let bottomElements = $("<div/>", {
        class: "bottom-elements"
    });

    let buttonFavorite = $("<button/>", {
        class: "favorite",
        type: "button"
    });


    let memeTitle = $("<p/>", {
        class: "vid-title"
    });
    memeTitle = memeTitle.html(videoData.titre)

    let favorite = $("<span/>", {
        class: "material-icons"
    });
    favorite = favorite.html("favorite")

    buttonFavorite = buttonFavorite.append(favorite)
    bottomElements = bottomElements.append(memeTitle)
    bottomElements = bottomElements.append(buttonFavorite)

    vidElements = vidElements.append(bottomElements)

    videoBox = videoBox.append(video)
    videoBox = videoBox.append(vidElements)

    return videoBox


}

Example of result after ajax call (videos are crossing hover each other once I execute:

example of result

Inconsistent results when sending a large volume of webhook messages

I’m new to node.js and discord.js, the previous version of this bot was written in discord.py (now deprecated).

This function iterates through all the webhooks (id and token) in my SQL database and sends a message to each of them. There are about 1500 of them (one for each server). I have to send a message roughly every 5 seconds. This worked perfectly in the python version, but that only had to run on about 300 guilds. I don’t have the code for it anymore, but it worked the same way (all the requests were sent at once, probably about 300 requests in 500ms and this worked fine), so I don’t think this is a rate limit issue.

    client.on('messageCreate', (message) => {
        if (message.channelId === '906659272744665139') {
            console.log('found message');
    
                const url = message.content;
                var webhooklist = [];
                
                //get all the webhooks from the database
                db.prepare('SELECT * FROM webhooks').all().forEach(webhook => {
                    const webhookclient = new WebhookClient({id: webhook.webhookID, token: webhook.webhookToken});
                    webhooklist.push(webhookclient);
                })
    
                console.time('sent');
                
                var failed = 0;
                webhooklist.forEach(webhook => {
    
                    var row = new MessageActionRow()
                        .addComponents(
                            savebutton,
                            reportbutton
                        )
                    
                    webhook.send({content: url, components: [row]})
                        .catch(err => {
                            if (err instanceof DiscordAPIError) {
                                if (err.code === 10015) {
                                    //remove the webhook from the database
                                    db.prepare('DELETE FROM webhooks WHERE webhookID = ?').run(webhook.id);
                                    console.log(`Removed webhook ${webhook.id}`);
                            } else {
                                failed += 1;
                                console.log(err);
                            }
                        } else {
                            failed += 1;
                        }
                    });
                });
    
                console.timeEnd('sent');
                console.log(failed);
              
            });
        }
    });

The problem:
A request is sent to each webhook, however, the messages don’t actually get sent half the time. For example, I’m looking at 3 different servers that this bot is in, and in one of them a message appeared and in the other two it didn’t (any other combination of these outcomes also occurs, its not a problem with how the servers are set up). There are also no errors, indicated by the failed variable. To clarify, about 50% of the messages get through, but the other 50% are supposedly sent by the bot but never appear in the channel.

Things that are (most likely) NOT the issue:

-Discord Rate limits
Why: Sending messages through webhooks does not count against the bot’s sent messages, and therefore will not cause rate limits (the global 50 messages per second). The only way this would cause me to be rate limited is if I was exceeding the 5/5 rate limit for each webhook individually (this is the same as what happens when you try to spam one channel).

-API rate limits
Why: API rate limits would only trip if I sent more than 10,000 invalid requests in 10 minutes. All of the requests go through, and there are no errors in the console. If I was being API rate limited, I would get completely blocked from using the discord API for up to an hour.

-I’m setting off some sort of spam protection
I’ve already considered this. Since most of the messages get through, I don’t think this is the problem. If I did set off any filters regarding volume of requests, the requests would probably either time out, or I would get blocked.

Other notes:

-A delay between requests is not a viable solution because pretty much any amount of delay multiplied by the 1500 times this has to run would result in this function taking multiple minutes to run.

-This could be related to another issue I’m having, where buttons take a long time to respond to so the interactions will often time out before I can even run .deferReply(), however, none of the webhook requests time out (which suggests that this may not be the issue)

-my internet has seemed slow recently even though I have gigabit, but again, if internet was the issue there would be errors.

In conclusion, a large volume of webhook messages like this SHOULD work, so this issue is most likely client-side.

firebase’ is not defined no-undef firebase error

cant use firebase in react app, i installed firebase using npm install firebase and created firebase project. and i add that code that given from firebase and exported it like this

export const auth = firebase.auth();
export const googleAuthProvider = new firebase.auth.GoogleAuthProvider();

then i used it in react component like below

import {auth} from '../../firebase';

and it says cant compile like this
image

Logical OR operators throws a syntax error here in JS – where am I going wrong?

Logical OR operators throws a syntax error here in JS – where am I going wrong?

function playRound(playerSelection, computerSelection) {
  if (playerSelection == 'rock' && computerSelection == 'paper') ||
  (playerSelection == 'paper' && computerSelection == 'shotgun') ||
  (playerSelection == 'shotgun' && computerSelection == 'rock') {
  console.log(`Sorry! ${computerSelection} beats ${playerSelection}`);}
}

Remove a URL search parameter when there is duplicate names?

I am trying to manipulate my URL using URLSearchParams. However URLSearchParams.delete() expects the name of the param. If I have params with the same name, (from what I’ve tested) the function only removes the last matching param. Is there a way to delete by both name and value?

My query looks something like this:

?color[]=Black&color[]=Green&material[]=Steel

So when I call .delete("color[]") it will remove the color[]=Green param, but what if I want to remove color[]=Black?

The reason for the duplicate names is the backend (PHP) is leveraging this functionallity to auto parse the parameters into arrays…which requires the syntax above.

Big picture is- I’m trying to add/remove “filters” from this array-to-be. Also, some filter categories could have matching values so I don’t want remove by value either. I am open to considering an entirely new approach…just trying to do it in the least hacky way.