I’m having trouble sending Notifications with the FCM Cloud Function

I’m sharing my code, I’ve uploaded 10,000 ads, but I still don’t know. I’ve been getting this error for a while, but all my tracks are ok.

text Payload : I will report ERROR: Firebase Messaging Error: An error occurred while trying to authenticate to the FCM servers. Make sure that the credentials used to authenticate this SDK have the appropriate permissions.

But;
await admin.messaging().send Multicast(message);
i receive the sent statement, but the notification does not arrive. I will also send you two different codes.

NOT WORKING

`exports.sendNotificationAdmin = functions.firestore.document(‘ilanlar/{ilanNumarasi}’).onCreate(async (snap, context) => {
const dataListing = snap.data();

const userTokens = [‘cYZPopVmaEF9mm0KCUZLcJ:APA91bEPOKDRs6xJLLiGcHDzascKL9LGSefAy7Hfa7vmVX-76bsH4uCrWTFmhvrMpYw-4unYzcictRd5hpzgttd_AKsPpxCKFCGljysUBHe4cBYsBRcL-g7AItsMVTs6wuuOov28mF9y’];

const isActive = dataListing.isActive;

if (isActive == 0){
    const message = {
        notification: {
          title: 'Yeni ilan eklendi!',
          body: 'Lütfen Onaylayın!',
        }
    };

    try {
        const response = await admin.messaging().sendToDevice(userTokens, message);
        console.log("Bildirim Gönderildi!");
    } catch (error) {
        console.error("Bildirim HATASI:", error);
    }

} else {
    console.log('isActive Değeri 0 değil.');
}

});`

working but not sending notifications :

I explained above that I tried two types of ways, but I couldn’t get on one way. sendToDevice gives a permission error, but sendMulticast does not, but does not send a notification.

customize bootstrap scrollspy to change color of active link

according to the official documentation from bootstrap , scrollspy Automatically update navigation components based on scroll position to indicate which link is currently active in the viewport. after diving into , i’ve come to realize that i need to customize it to change the color of active link when scrolled to its corresponding position, see the example below from official documentation , it changes background color of the active link to blue when scrolled , the purpose here is to customize it and make the active link color to red , and remove that that blue background color , i have gone through many solutions and examples but they didn’t solve my problem . any help will be appreciated

    <nav id="navbar-example2" class="navbar bg-body-tertiary px-3 mb-3">
  <a class="navbar-brand" href="#">Navbar</a>
  <ul class="nav nav-pills">
    <li class="nav-item">
      <a class="nav-link" href="#scrollspyHeading1">First</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#scrollspyHeading2">Second</a>
    </li>
    <li class="nav-item dropdown">
      <a class="nav-link dropdown-toggle" data-bs-toggle="dropdown" href="#" role="button" aria-expanded="false">Dropdown</a>
      <ul class="dropdown-menu">
        <li><a class="dropdown-item" href="#scrollspyHeading3">Third</a></li>
        <li><a class="dropdown-item" href="#scrollspyHeading4">Fourth</a></li>
        <li><hr class="dropdown-divider"></li>
        <li><a class="dropdown-item" href="#scrollspyHeading5">Fifth</a></li>
      </ul>
    </li>
  </ul>
</nav>
<div data-bs-spy="scroll" data-bs-target="#navbar-example2" data-bs-root-margin="0px 0px -40%" data-bs-smooth-scroll="true" class="scrollspy-example bg-body-tertiary p-3 rounded-2" tabindex="0">
  <h4 id="scrollspyHeading1">First heading</h4>
  <p>...</p>
  <h4 id="scrollspyHeading2">Second heading</h4>
  <p>...</p>
  <h4 id="scrollspyHeading3">Third heading</h4>
  <p>...</p>
  <h4 id="scrollspyHeading4">Fourth heading</h4>
  <p>...</p>
  <h4 id="scrollspyHeading5">Fifth heading</h4>
  <p>...</p>
</div>

Dynamically setting initial location on expo MapView

I am trying to set the initial location of an expo MapView for a project of mine and am having trouble sending the longitude and latitude variables from the getlocation() call. I have tried sending the coordinates as variables, as they are and the best I get is a crashed app. Is there any way to make the initial region dynamically change based on the user’s location whenever they open the screen?

import React, { useState, useEffect } from 'react';
import { Platform, Text, View, StyleSheet , SafeAreaView} from 'react-native';
import MapView from 'react-native-maps';
import {FAB, Title} from 'react-native-paper';
import * as Location from 'expo-location';
import { homeStyle } from './Home.Style';

export const HomeScreen = () => {
    const [location, setLocation] = useState(null);
    const [latitude, setLatitude] = useState(null);
    const [longitude, setLongitude] = useState(null);
    useEffect(() => {
        (async () => {
          let location = await Location.getCurrentPositionAsync({});
          setLatitude(location.coords.latitude)
          setLongitude(location.coords.longitude);
          setLocation(location.coords);
        })();
      }, []);

      console.warn("latitude: ", latitude);
      console.warn("longitude: ", longitude);
return(
    <View style = {homeStyle.flex}>
        <MapView
            style = {homeStyle.flex}
            initialRegion={{
                latitude: 0,
                longitude: 0,
                longitudeDelta: 0,
                latitudeDelta: 0
            }}/>
        <FAB 
        icon="plus"
        style = {homeStyle.fab}
        />
    </View>
)
}

This screen is accessed through a button press on another screen. I currently have the initial region latitude and longitude set to dummy data for initial testing.

I have tried sending variables with the latitude/longitude coordinates which led to a crash, I have tried sending the location.coords.latitude and location.coords.longitude directly to the same result.

Mongoose – Check if a value of an array in an object of a document matches a given value

I’m making a mock webshop, and I would like to know how to check if there already exists a category in my webshop that has the same name as the one I am using to create a new one with.

  console.log(
    await webshopCollection.find({
      categories: {
        $elemMatch: {
          name: req.body.data.name,
        },
      },
    })
  );

Right now this block of code returns the whole document (that contains the given array value of name), but that’s not what I’m after. I’m only looking to check if the array in the products object contains the name that I’m using to create a new category with, that way I can avoid making a category with the same name.

I have tried a few different things, but to no avail.

Does anyone know how to solve this problem I have?

Invoke AWS Lambda into React page

I have this simple form executed into React page:

import React from 'react';
import axios from 'axios';

const FooterOne = ({ footerLight, style, footerGradient }) => {

  handleChange(event) {
    const inputValue = event.target.value;
    const stateField = event.target.name;
    this.setState({
      [stateField]: inputValue,
    });
    console.log(this.state);
  }
  async handleSubmit(event) {
    event.preventDefault();
    const { name, message } = this.state;
    await axios.post(
        'https://i1xsjzkri4.execute-api.us-east-1.amazonaws.com/default/serverlessAppFunction',
        { key1: `${name}, ${message}` }
    );
  }

  return (
    <>

      <form className='newsletter-form position-relative d-block d-lg-flex d-md-flex'>
        <input
            type='text'
            className='input-newsletter form-control me-2'
            placeholder='Enter your email'
            name='email'
            required=''
            autoComplete='off'
        />
        <input
            type='submit'
            value='Subscribe'
            data-wait='Please wait...'
        />
      </form>
    </>
  );
};

export default FooterOne;

Lambda code into AWS Lambda:

export const handler = async (event) => {
  // TODO implement
  const response = {
    statusCode: 200,
    body: JSON.stringify('Hello from Lambda!'),
  };
  return response;
};

Do you know how I can call the AWS Lambda code when I submit this simple form?

style.display=”block” no longer working once moving my code to neocities.org off of VScode

So, I coded in a section of my project in which one image/link is hidden until the user goes to multiple other links and then back. When I open in live server from my computer, the javascript does exactly as it needs to do. Keeps the object hidden until these three links have been visited. I recently transferred over my code to neocities as I am hosting my project there, and I cannot figure out what the problem is. The system records a list of the links you visit, and I checked and it does output a list, but it will not perform the actions needed when this list is created.

I tried to switch between calling it hidden or block or none and removing the style display, yet nothing seems to work.

places.js

document.addEventListener("DOMContentLoaded", () => {
    let page = String(window.location.pathname);
    //collects path in current window
    let list = JSON.parse(window.localStorage.getItem("list") || "[]");
    //list for every page visited in local storage

    if (!list.includes(page)) { 
        list.push(page)
        window.localStorage.setItem("list", JSON.stringify(list))
        //if page is not in list, it is now added to list.
    }

    if (list.includes("/clocktower/clocktower") && list.includes("/stables/stables") && list.includes("/bank/bank")) {
        //checks list if three locations are there, if they are....reveals cemetery
        document.getElementById("hiddenlink").style.display="block";
        window.alert("Odd. Had I noticed that before?");
    }

    if (list.includes("/cemetery/cemetery")) {
        /* this will reset the list once cemetery is visited*/
        window.localStorage.setItem("list", "[]");
        document.getElementById("hiddenlink").style.display="none";
        
    }

})

Using window.alert(list); will produce something such as: /opening/places,/bank/bank,/clocktower/clocktower,/stables/stables

places.html (section is div class="cemetery" which is what I want to be hidden until the sections:clocktower, bank, and stables have all been visited. It works fine through my own live server, but after I uploaded it to an actual site, it cannot execute it. I think the problem is that is not looking through the list to see what it includes

<!DOCTYPE html>
<html lang="en-US">
  <head> 
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>San Roque, California</title>
    <link rel="icon" type="image/x-icon" href="/misc/favicon.PNG">
    <link href="/style.css" rel="stylesheet" type="text/css" media="all">
  </head>


    <body>
      <div class="background">
        <div class ="inside">
          <div class="places">
            <div class="stables">
                  <a href="/stables/stables.html"><img src="stable.png" height="180"></a>
            </div>
            <div class="cemetery">
                  <a href="/cemetery/cemetery.html" id="hiddenlink" style="display: none;"><img src="graveyard.png" height="220"></a>
            </div>
            <div class="clocktower">
                  <a href="/clocktower/clocktower.html"><img src="clocktower.png" height="350"></a>
            </div>
            <div class="bankstore">
              <img src="bankstore.png" usemap="#image-map" height = 200>
                  <map name="image-map">
                  <area target="" alt="bank" title="bank" href="/bank/bank.html" coords="0,0,165,200" shape="rect">
                  <area target="" alt="store" title="store" href="/store/store.html" coords="165,200,337s,0" shape="rect">
                   </map>
            </div>
            <div class="saloon">
                <a href="/saloon/saloon.html"><img src="saloon.png" height="200"></a>
            </div>
            <div class="office">
                <a href="/office/office.html"><img src="sheriff.png" height="200"></a>
            </div>
          </div>
        </div>
  </div>
  <script src="places.js"> 
 </script>
    </body>

</html>

additional image for reference of the list output being made
enter image description here

How to conditionally render image in case one doesnt load, using the image component provided by nextjs

Im fetching data for an image. The image’s src is saved in the variable “movie.primaryImage.url”, but there are cases when the image doesnt load, ive tried to implement conditional rendering so when the image doesnt load a fallback one is set. Here is my attempt but it doesnt work. How do i set a fallback image in case the one im fetching doesnt work in nextjs?

 {
           movie.primaryImage.url 
           ?
         
         <Image 
          src={movie.primaryImage.url}
          alt={movie.titleText.text}
          height={300}
          width={200}
          />
          :
          <Image 
          src={'https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.vecteezy.com%2Fvector-art%2F5337799-icon-image-not-found-vector&psig=AOvVaw3KsJjOSvwjWH-OLH8cJPIT&ust=1702332423213000&source=images&cd=vfe&opi=89978449&ved=0CBEQjRxqFwoTCJDFlNHwhYMDFQAAAAAdAAAAABAD'}
          alt={movie.titleText.text}
          height={300}
          width={200}
          />
          
          }
          <h2>{movie.titleText.text}</h2>
          <p>Release Year: {movie.releaseYear.year}</p>
          {/* Add more details as needed */}
        </div>
      ))}

Need to understand how [0] of $deleted[0]} is working here in (else if delete) part

I am not getting any error just getting the two different outputs when I want to delete a todo that is not in the array list with two options, console. log(todo ${ deleted ) it prints " todo is deleted "....... and when i put [0] console.log(todo ${ deleted[0] ) it prints ” todo undefined is deleted”
explain [0] part in {deleted[0]} of template literal section

let input = prompt("what would you like to do ");

let todos=["pay rent","car wash","buy chicken"];

while(input!=="quit" && input!=="q") {
    if (input==="list"){
        console.log("***********");
       
        for (let i = 0; i < todos.length; i++) { 
            console.log(`${i}: ${todos[i]}`);
        }
            console.log("***********");
    }
    else if (input === "new") {
        const newTodo= prompt("ok! what is the new todo ?");
        todos.push(newTodo);
        console.log(`added ${newTodo}`);
        
    }
    else if (input === "delete") {
         const index = prompt("enter index to delte todo");
         const deleted = todos.splice(index, 1);
         console.log(`todo  ${deleted[0]}  is deleted`);

    }
    

    input = prompt("what would you like to do ")

}

console.log("you quit the app");

these are the two different output i am getting when i delete todos which are are not in the array list

todo   is deleted  
todo undefined is deleted

Compute arithmetic-geometric mean of arbitrary array length in JS

The arithmetic-geometric mean of two numbers is defined as the limit of a sequence of arithmetic and geometric means.

Here is what I have for one iteration with two numbers:

function agm2(n)
{
    /**
     * @param {Float64Array(2)} n
     */
    var x0 = n[0], x1 = n[1];

    var a0 = (x0 + x1) / 2;
    var a1 = Math.sqrt(x0 * x1);

    return new Float64Array([a0, a1]);
}

Per this thread on MathOverflowDotNet, we can generalise this function to get the iteration-by-iteration function for an arbitrary number using elementary symmetic polynomials and binomial coefficients.

For three variables:

function agm3(n)
{
    /**
     * @param {Float64Array(3)} n
     */
    var x0 = n[0], x1 = n[1], x2 = n[2];

    var a0 = (x0 + x1 + x2) / 3;
    var a1 = Math.sqrt((x0 * x1 + x1 * x2 + x0 * x2) / 3);
    var a2 = Math.pow(x0 * x1 * x2, 1 / 3);

    return new Float64Array([a0, a1, a2]);
}

Four variables:

function agm4(n)
{
    /**
     * @param {Float64Array(4)} n
     */
    var x0 = n[0], x1 = n[1], x2 = n[2], x3 = n[3];

    var a0 = (x0 + x1 + x2 + x3) / 4;
    var a1 = Math.sqrt((x0 * x1 + x0 * x2 + x0 * x3 + x1 * x2 + x1 * x3 + x2 * x3) / 6);
    var a2 = Math.pow((x0 * x1 * x2 + x0 * x1 * x3 + x0 * x2 * x3 + x1 * x2 * x3) / 4, 1 / 3);
    var a3 = Math.pow(x0 * x1 * x2 * x3, 1 / 4);

    return new Float64Array([a0, a1, a2, a3]);
}

And five variables:

function agm5(n)
{
    /**
     * @param {Float64Array(5)} n
     */
    var x0 = n[0], x1 = n[1], x2 = n[2], x3 = n[3], x4 = n[4];

    var a0 = (x0 + x1 + x2 + x3 + x4) / 5;
    var a1 = Math.sqrt((x0 * x1 + x0 * x2 + x0 * x3 + x0 * x4 + x1 * x2 + x1 * x3 + x1 * x4 + x2 * x3 + x2 * x4 + x3 * x4) / 10);
    var a2 = Math.pow((x0 * x1 * x2 + x0 * x1 * x3 + x0 * x1 * x4 + x0 * x2 * x3 + x0 * x2 * x4 + x0 * x3 * x4 + x1 * x2 * x3 + x1 * x2 * x4 + x1 * x3 * x4 + x2 * x3 * x4) / 10, 1 / 3);
    var a3 = Math.pow((x0 * x1 * x2 * x3 + x0 * x1 * x2 * x4 + x0 * x1 * x3 * x4 + x0 * x2 * x3 * x4 + x1 * x2 * x3 * x4) / 5, 1 / 4);
    var a4 = Math.pow(x0 * x1 * x2 * x3 * x4, 1 / 5);

    return new Float64Array([a0, a1, a2, a3, a4]);
}

My question is, how can I generalise this so that I don’t have to define separate functions for each length? The agm function should take any Float64Array, iterate over it enough times, and then output the result.

Implementing binomial coefficients is no problem since I know how to write the factorial function for non-negative whole numbers, but how do I properly implement the elementary symmetric polynomials for an arbitrary array length beyond the first and last terms?

Combining NestJs In Memory Cache And Redis Cache At The Same TIme

I have read the NestJs docs and a lot of online tutorials about using in memory cache and Redis cache. What i am looking for is the ability to use both at the same time.

For instance when a request is made i will check if the data is in in-memory cache and if so i will return it to the user. If not i will fetch it from Redis and then store it in in-memory cache and afterwards return it to the user.

I have googled a lot but could not find any tutorials or answer pertaining to using in-memory cache and Redis at the same time in NestJs. I am not sure if the two can be combined in NestJs.

Any pointer to tutorial or suggestion will be appreciated.

Pre-session CSRF tokens with React & Express

I am using React for my frontend and Express for middleware, e.g my frontend can call /profile to get the profile for a signed in user. It is also worth noting that the UI is not rendered from Express, so I can’t include a pre-session CSRF token inside the HTML.

My question is: how do I get a pre-session CSRF token to the frontend before the user is authenticated to prevent a login CSRF attack?

I am planning to use the double submit cookie pattern to send/authenticate CSRF tokens but am open to other suggestions if it works better.

My initial thought was to have an endpoint that generates a CSRF token in Express e.g GET/csrf but am not entirely sure if that is safe/best practice.

javascript: window.location.hash returns empty string

I’m working on a vanilla js recipe project that is part of a course.i used the model controller view code pattern and for some reason when i try to get the hash of my current page it returns <empty string>.the hash should be a ‘#’symbol followed by an id of numbers for each recipe.

the code:
controller module:
this async function is where i get the page id

import * as model from './model';

const controlRecipe = async function () {
  try {
    const id = window.location.hash.slice(1);
    console.log(id);//logs <empty string>
    
    if (!id) return;

    //loading recipe
    await model.loadRecipe(id);//passing the id here

    //rendering recipe
    recipeView.render(model.state.recipe);
  } catch (err) {
    console.log(err)
  }
}

model module:
the id is passed to this loadRecipe function from the controller to load the recipe
the API_URL is just the API link without the id
the getJSON function gets the json() format of the fetch and then the recipe data is manipulated

import { API_URL} from "./config";
import { getJSON } from "./helpers";

export const loadRecipe = async function(id){
    try {
        const data = await getJSON(`${API_URL}${id}`);

        const {recipe} = data.data;

        state.recipe = {
        id: recipe.id,
        title: recipe.title,
        publisher: recipe.publisher,
        sourceUrl: recipe.source_url,
        image: recipe.image_url,
        servings: recipe.servings,
        cookingTime: recipe.cooking_time,
        ingredients: recipe.ingredients,
        };
    }
    catch (err) {
        console.log(err);
    }
};

example:
the id appears at the url but is logged to the console. when i manually add the ‘#’ it works fine and the id is logged

i tried searching for a solution but couldn’t find anything. can u please help thanks.

Error when making a request from another app

I have the following middleware protecting my routes:

import { authMiddleware } from "@clerk/nextjs";
import { importSPKI, jwtVerify } from "jose";
import { NextResponse } from "next/server";

const publicRoutes = [
    "/",
    "/contact",
    "/pricing",
    "/api/webhooks/user",
    "/sign-in",
    "/sign-up",
];

export default authMiddleware({
    publicRoutes,
    afterAuth: async (auth, req, evt) => {
        if (publicRoutes.some((route) => req.nextUrl.pathname === route)) {
            return NextResponse.next();
        }
        const publicKey = await importSPKI(
            `-----BEGIN PUBLIC KEY-----
        MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsn6Pl9xht3Jp/BlHE2ZV
        NYXkNcfpiD6+sNbEIrf64e53mwMx2Ot2mu1D6VIS/yeVduF/j4eEqm2m7z9Uh+kR
        KYjtVWawUeuW5egLda8FxdKJRkrf0Ll9HC0XPCC4zanlpYcM3JIgLrOmCUmayD0j
        hUmt6u5b4ri5jW0fAawL3q8meVBVdE2dJHPrhyK9fAegmm2ATXDDU4NUTDLcta/O
        fgK+Ro67NKvv3Ng4Abey7wkcrvFVUCV3M+msc1RvclCNhZlgcPXRVi93F3KkDfEi
        3lT5UXWpUeDTcOeZPyP/1xCmWNtrgk4LzrvnryVD5oKpsYRJocWUebSHC4TIeSXz
        NwIDAQAB
        -----END PUBLIC KEY-----`,
            "RS256"
        );

        const session = req.cookies.get("__session");
        const token = req.headers.get("Authorization");

    if (!token && !session && req.nextUrl.pathname.startsWith("/app")) {
      const url = req.nextUrl.clone();
            url.pathname = "/sign-in";
            return NextResponse.redirect(url);
    }

        if (!token && !session) {
            return NextResponse.json(
                { error: "No token or signed in user." },
                { status: 401 }
            );
        }

        if (token) {
            try {
                const decoded = await jwtVerify(token, publicKey);
                console.log(decoded);
            } catch (error) {
                return NextResponse.json({ error: error }, { status: 400 });
            }
        }
    },
});

export const config = {
    matcher: ["/((?!.*\..*|_next).*)", "/", "/(api|trpc)(.*)", "/api"],
};

It has public routes which can be accessed by anyone. The rest requires a signed in user const session = req.cookies.get("__session"); or a valid Authorization header const token = req.headers.get("Authorization");.

When sending with postman to for example localhost:3000/api/user with the correct Authorization header everything works as expected.

However, when accessing the same endpoint with same headers from a different app in the browser I get a Next.js server error:

uncaughtException: Error: aborted
    at abortIncoming (node:_http_server:793:17)
    at socketOnClose (node:_http_server:787:3)
    at Socket.emit (node:events:531:35)
    at TCP.<anonymous> (node:net:337:12)
    at TCP.callbackTrampoline (node:internal/async_hooks:130:17) {
  code: 'ECONNRESET'
}

However, when I make the endpoint public and try to access it again I get no errors. I also get some errors in the browsers console:

Access to fetch at 'http://localhost:3000/api/reviews/add' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
script.js:23 
        
        
       GET http://localhost:3000/api/user net::ERR_FAILED

script.js:23 
        
        
       
        
       Uncaught (in promise) TypeError: Failed to fetch
    at get (script.js:23:29)
    at injectUser (script.js:68:22)
    at HTMLDocument.<anonymous> (script.js:136:3)```

What's wrong here?

How to show a child element on top of it’s parents and siblings by using CSS only

I am trying to add some options on top of Twitter UI for text editing, but when I do that, I get an issue, and I cannot show the element on top of other elements. It’s always being shown behind the siblings.

Here is the code I am trying and running it on https://twitter.com/home

let tweetArea = document.querySelector(".public-DraftStyleDefault-block");

const unlistedItems = document.createElement('ul');
unlistedItems.innerHTML += `
  <li> Option 0</li>
  <li> Option 1</li>
  <li> Option 2</li>
  <li> Option 3</li>`;
unlistedItems.style.position = 'absolute';
unlistedItems.style.top = '0';
unlistedItems.style.backgroundColor = "red";
unlistedItems.style.zIndex = '100';

tweetArea.parentNode.insertBefore(unlistedItems, tweetArea);

I am getting this result which adds the element but it does not show it on top of the siblings and parents. I want my element to be visible and shown even on top of the Gif icon and toolbar. How can I achieve that?

enter image description here