Firestore: Using Logical OR and modular syntax in Firebase Functions

I’m building a web app with a React front end hosted on Firebase Hosting that uses scheduled Pub/Sub Firebase Functions to scrape data and store it in a Firestore database (which is also access in the front end). This is my first time using Firebase.

tl;dr, can I do this in a Firebase Function?

const q = query(citiesRef,  
  or(where('capital', '==', true),
     where('population', '>=', 1000000)
  )
);

I’ve been trying to use the new “Logical OR” query feature for a Firestore query from within a Firebase Function. The docs show code samples implying that this feature can be used via the “Web modular API” (which seems to only be accessible via the “Web SDK”…which would mean my React front end in my case?), but also implies, for some unclear reason, that it is not usable via the “Web namespaced API” or Node.js—both of which seem to be preferred flavors within Firebase Functions, which I believe use a toolset called the “Firebase Admin SDK” to access Firestore functionality.

Basically, I’d like to use this feature within a Firebase Function. Is this just not (yet?) possible?

Other Firebase documentation led me to believe it might be possible, but I think I may have been confusing similarly named syntaxes/functionalities/services… I’m not sure. Some docs refer to it being possible to “upgrade” to a “modular SDK” version of the “Admin SDK”…and that now there’s a “2nd generation” mentioned in yet another doc which is more “modular”… but is maybe actually unrelated to the “Web modular API,” which allows the functionality I was looking to use in a Firebase Function?

Any help untangling this would be greatly appreciated!

List database record in full calendar

I’m trying to list the database data in fullcalendar via Javascript, but it’s not listing even the data is in json.

class list data

<?php 
include '../banco.php';

$query_events = "SELECT     
                 id,
                 title,
                 data,  
                 hora_inicio,   
                 cor,   
                 profissional,  
                 paciente,  
                 convenio,  
                 carteirinha_paciente,  
                 recorrencia_consulta,  
                 situacao_consulta, 
                 duracao    
                FROM consultas";
$resultado_events = $pdo->prepare($query_events);
$resultado_events->execute();

$events = [];

while ($row_events = $resultado_events->fetch(PDO::FETCH_ASSOC)) {
    $id = $row_events['id'];
    $data = $row_events['data'];
    $hora_inicio = $row_events['hora_inicio'];
    $cor = $row_events['cor'];
    $profissional = $row_events['profissional'];
    $cliente = $row_events['cliente'];
    $convenio = $row_events['convenio'];
    
    $events[] = [
        'id' => $id,
        'title' => $title,
        'data' => $data." ".$hora_inicio,
        'cor' => $cor,
        'profissional' => $profissional,
        'cliente' => $cliente,
        'convenio' => $convenio,
        'recorrencia_consulta' => $recorrencia_consulta,
    ];
    
}

echo json_encode($events);

File render calendar and list records via url

document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
        var calendar = new FullCalendar.Calendar(calendarEl, {
              
            locale: 'pt-br',
            
            initialView: 'dayGridMonth',
            
            headerToolbar: {
                  left: 'prev,next',
                  center: 'title',
                  right: 'dayGridMonth,dayGridWeek,dayGridDay'
            },
            
            editable: true,
            
            events: {
            url: '../server/consulta/list_consultas.php',
            method: 'GET',
            }
            
            
        });
    
        calendar.render();
});

Can you help me?

A listing of the database data was performed and decoded in JSON, expecting to receive this data in the javascript class and list it in the calendar, but the calendar just renders empty.

How to update a merged Matrix?

Tried coding Tetris using Canvas. Now i got stuck at the collision detection part.

Got 2 different matrices: one for the specific piece, one for my map.
To detect collision later on, i wanted to merge the piece matrix into the map and update it.

Merging worked well like that:

(https://i.stack.imgur.com/gyP1s.png)

Updating that Matrix in my animation loop makes it update too fast and it throws errors.

How can i update my merged matrix properly with the constantly updating movements of my pieces?
Can provide more pics of my code if needed ofc.

From 2 icons to animated hamburger menu toggle THANK YOU

Hey guys can someone help me with the following task. I don’t really have any coding background so I don’t really understand anything. Basically the code bellow is my JavaScript for my WordPress website. The thing I need you guys for is to code the highlighted part so the open and close button is the same (animated hamburger) because in this case they are 2 different icons. I already have my animated hamburger html widget I just need to connect it properly with this code so it works fine. Can you please help me with that It would be highly appreciated.


$('.f-open').on('click', function(){
    $('.f-menu-section').addClass('active')
})
$('.f-close').on('click', function(){
    $('.f-menu-section').removeClass('active')
})

Liquid Image Transition Effect Multiple Images

I’m trying to achieve a liquid transition effect when my images change as I hover over different list items. I’m using GSAP, three.js and Robin Dela’s hover-effect. I’m not sure where I am going wrong.Here is my Javascript code. Can some one point out where I may be going wrong?

document.addEventListener("DOMContentLoaded", function() {
    var menuLinks = document.querySelectorAll(".main-menu a");
    var subMenuImages = document.querySelector(".sub-menu-images");
    var defaultList = document.getElementById("women-list"); 

    // Initialize the hover effect
    var hoverEffect = new hoverEffect({
        parent: subMenuImages,
        intensity: 0.2,
        image1: "/assets/images/braids.jpg", // Default image
        image2: "", 
        displacementImage: "/assets/images/distort.png"
    });

    menuLinks.forEach(function(link) {
        link.addEventListener("click", function(event) {
            event.preventDefault();

            var target = this.getAttribute("href");
            var targetList = document.querySelector(target);

            var lists = document.querySelectorAll(".sub-menu-links");
            lists.forEach(function(list) {
                list.style.display = "none";
            });

            var defaultLink = document.querySelector(".main-menu .active-link");
            if (defaultLink) {
                defaultLink.classList.remove("active-link");
            }

            this.classList.add("active-link");

            targetList.style.display = "block";

            var listItems = targetList.querySelectorAll("li");
            listItems.forEach(function(item, index) {
                item.style.animationDelay = (index * 0.3) + "s";
            });

            // Update the hover effect image on menu item click
            var firstItem = targetList.querySelector("li:first-child");
            var imageURL = firstItem.getAttribute("data-image");
            hoverEffect.next(imageURL);
        });
    });

    var subMenuLinks = document.querySelectorAll(".sub-menu-links li");

    subMenuLinks.forEach(function(link) {
        link.addEventListener("mouseover", function() {
            var imageURL = this.getAttribute("data-image");
            hoverEffect.next(imageURL);
        });
    });

    // Set default image on page load
    var defaultImageURL = defaultList.querySelector("li:first-child").getAttribute("data-image");
    hoverEffect.next(defaultImageURL);
});

Error: Request Failed with status code 429?

İ’m new with coding. I tried to make a discord bot integrated with OpenAIAPI but i guess i made somethings wrong can you help me?

client.on('messageCreate', async function(message){
    try {
        // Don't respond to yourself or other bots
        if(message.author.bot) return;

        const gptResponse = await openai.createCompletion({
            model: "davinci",
            prompt: 'ChatGPT is a friendly chatbot.',
            temperature: 0.9,
            max_tokens: 100,
            stop: ["ChatGPT:", "Tunee:"],

        })
        message.reply($(gptResponse.data.choices[0].text))

    } catch(err){
        console.log(err)
    }

});

I think there is the mistake but i couldn’t figure it

Here is the error message

Error: Request failed with status code 429
    at createError (C:UsersUSERDesktopKod Projelerim ve ÇalışmalarımCHATGPT-DISCORD-CHATBOTnode_modulesaxioslibcorecreateError.js:16:15)
    at settle (C:UsersUSERDesktopKod Projelerim ve ÇalışmalarımCHATGPT-DISCORD-CHATBOTnode_modulesaxioslibcoresettle.js:17:12)
    at IncomingMessage.handleStreamEnd (C:UsersUSERDesktopKod Projelerim ve ÇalışmalarımCHATGPT-DISCORD-CHATBOTnode_modulesaxioslibadaptershttp.js:322:11)
    at IncomingMessage.emit (node:events:525:35)
    at endReadableNT (node:internal/streams/readable:1359:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

Mocking useFormikContext() Hook in TypeScript using React-Testing-Library

I’m having a tough time trying to get the react-hooks library to work with Formik – specifically useFormikContext<FormTypeFields>() – in TypeScript in my project. I have fields where I want to test the ability to automatically type into them inside of react-testing-library. Right now I think I’m getting somewhere, but the result.current inside of the act function is undefined. I’ve attached sample code that I hope will help.

TestForm.tsx

import React from "react";
import { Grid, GridItem } from "@chakra-ui/react";
import { FormTypeFields } from "./form-type-fields.model";

const TestForm = () => {
  const { values } = useFormikContext<FormTypeFields>();
  const { testField } = values;

  return (
    <Grid
      templateColumns="repeat(12, minmax(0, 1fr))"
      gap={{ base: 6, md: 8, lg: 8 }}
    >
      <GridItem colSpan={12}>
        <label for="testField">Test Field</label>
        <input type="text" id="testField" name="testField" />
      </GridItem>
    </Grid>
  );
}

export default TestForm;

form-type-fields.model

export class FormTypeFields {
  testField: string = "";

  constructor(entity: any) {
    if (!entity) return;
    this.testField = entity.testField;
  }
}

Here’s the test I’m trying to write:
TestForm.test.tsx

import React from "react";
import { render } from "@testing-library/react";
import TestForm from "./TestForm";
import * as Formik from "formik";
import userEvent from "@testing-library/user-event";
import { renderHook, act } from "@testing-library/react-hooks";
import { FormTypeFields } from "./test-form-fields.model";

describe("typing should work", async () => {
  const { result } = renderHook<
    Formik.FormikContextType<FormTypeFields>,
    Formik.FormikContextType<FormTypeFields>
  >(() => Formik.useFormikContext<FormTypeFields>());

  act(() => {
    result.current.values = { testField: "" };
  });

  render(<TestForm />);

  expect(screen).toMatchSnapshot();
  await userEvent.keyboard("ABC");
  expect(screen.getByLabelText("Test Field").innerHTML).toContain("ABC");
});

I can’t figure out how to wire this up so I can test the keyboard("ABC") function in the react-testing-library functionality on the input form.

The error message is this:

    TypeError: Cannot set properties of undefined (setting 'values')

      15 |
      16 |   act(() => {
    > 17 |     result.current.values = { testField: "" };
         |     ^
      18 |   });
      19 |
      20 |   render(<TestForm />);

And I’m getting this warning:

console.warn
    Warning: Formik context is undefined, please verify you are calling useFormikContext() as child of 
a <Formik> component.

      11 |     Formik.FormikContextType<FormTypeFields>,
      12 |     Formik.FormikContextType<FormTypeFields>
    > 13 |   >(() => Formik.useFormikContext<FormTypeFields>());
         |                  ^
      14 |
      15 |   act(() => {
      16 |     result.current.values = { testField: "" };

Looking for suggestions, thanks.

How to fix Chart js Bar

i make a bar with chart js in a project with next but the bar is stick on left panelenter image description here

import React, { useState, useEffect } from 'react';
import BarChart from './Graphics/BarChart';
import { Container } from '@mui/material';
import styles from '@styles/pages/statistics/Statistics.module.css';
import PieChart from './Graphics/PieChart';
import BarKPIChart from './Graphics/BarKPIChart';
import BarChartByTags from './Graphics/BarChartByTags';
import { useAnswersStatistic } from '@hooks/Answers/useAnswersStatistics';

export default function ChartToShow(props) {
  const [componentToRender, setComponentToRender] = useState(null);
  const { stateAnswer } = useAnswersStatistic();
  const { questionsAnswers } = stateAnswer;
  useEffect(() => {
    let component;
    switch (props.componentType) {
      case 'Pie':
        component = <PieChart questionsAnswers={questionsAnswers} idQuestion={props.idQuestion} />;
        break;
      case 'Bar':
        component = <BarChart questionsAnswers={questionsAnswers} idQuestion={props.idQuestion} />;
        break;
      case 'BarKPI':
        component = <BarKPIChart questionsAnswers={questionsAnswers} idQuestion={props.idQuestion} />;
        break;
      case 'BarTag':
        component = <BarChartByTags questionsAnswers={questionsAnswers} idQuestion={props.idQuestion} />;
        break;
    }
    setComponentToRender(component);
  }, [props.componentType, questionsAnswers, props.idQuestion]);

  return <Container className={styles.chart_wrapper}>{componentToRender}</Container>;
}

the graph mush be like this enter image description here
but this hapens when i change some in code and the chart re-renderize

Is there a software design pattern for a “utility” class with only static methods?

In OOP, consider the example case of a global class like Math with methods like Math.abs(), Math.sin(), Math.floor(), or in general any kind of class that cannot be instantiated but provides a group of “utility” functions.

Such a class is often implemented as a “static” class with “static” methods that can be invoked directly from the class itself (this depending on the programming language).

In software design, is there a specific design pattern for this?

How can I retrieve data from Telegram.WebApp.sendData() using telegraf.js?

I use telegraf.js
can’t get data from Telegram.WebApp.sendData()

bot.start(async(ctx)=>{

        ctx.reply('Hello', {
            reply_markup:{
                inline_keyboard: [
                    [{text: 'Auth', web_app:{url:FRONT_URL}}]
                ]
            }
        })
}

my front-end app

window.Telegram.WebApp.sendData(JSON.stringify({data:'test'}))

I try methods like this,

bot.on('message', (ctx)=>{})
bot.on('web_app_data', (ctx)=>{})

events are not processed
I read the telegraf documentation and did not find examples of working with webApp

Does anyone know if there is a possibility to implement this on telegraf at all?

Updating PeerJS Data Handler Callback Function at Runtime

I am using PeerJS in my project.

I have successfully implemented and documented a data handler for the peer connection, as described in the PeerJS documentation: (docs)

connection.on('data', data => peerOnDataHandler(data, connection));

However, I now need to update the callback function at runtime. The reason for this is that there is a state within my function peerOnDataHandler() that requires updating.

I attempted to update the callback function using the following code, but it doesn’t seem to work as expected, or perhaps I am not using it correctly:

connection.off('data', data => peerOnDataHandler(data, connection));
connection.on('data', data => peerOnDataHandler(data, connection));

Change element when hover on different element

<section id="section_line">
  <div id="line_div1">
    <article class="line_clanek" id="line_clanek1">
      <h3>Season 1</h3>
      <p>Release date:<br> 2.Prosince 2013 - 14.Dubna 2014</p>
    </article>
    <article class="line_clanek" id="line_clanek2">
      <h3>Season 3</h3>
      <p>Release date:<br> 1.Dubna 2017 - 1.Října 2017</p>
    </article>
    <article class="line_clanek" id="line_clanek3">
      <h3>Season 5</h3>
      <p>Release date:<br> 20.Června 2021 - 5.Září 2021</p>
    </article>
  </div>
  <div id="line">
    <div class="line_dot" id="line_dot1"></div>
    <div class="line_dot" id="line_dot2"></div>
    <div class="line_dot" id="line_dot3"></div>
    <div class="line_dot" id="line_dot4"></div>
    <div class="line_dot" id="line_dot5"></div>
    <div class="line_dot" id="line_dot6"></div>
  </div>
  <div id="line_div2">
    <article class="line_clanek" id="line_clanek4">
      <h3>Season 2</h3>
      <p>Release date:<br> 26. července 2015 - 4. října 2015</p>
    </article>
    <article class="line_clanek" id="line_clanek5">
      <h3>Season 4</h3>
      <p>Release date:<br> 10. listopadu 2019 - 31. května 2020</p>
    </article>
    <article class="line_clanek" id="line_clanek6">
      <h3>Season 6</h3>
      <p>Release date:<br> 4. září 2022 - 11. prosince 2022</p>
    </article>
  </div>
</section>

I want to, when I hover on article #line_clanek1, to change the background-color of #line_dot1 to red. I tried lot of things but nothing worked.

I tried using +, ~ and > but nothing worked. I tried ChatGPT but no help for me from GPT. Can I do this just by using CSS or I need to use JavaScript?

next.js 13.2.4 Props not linking


// VSC errors
// page.tsx Cannot find name 'SearchResult' [Ln 11, Col 29]
// page.tsx Cannot find name 'SearchResult' [Ln 28, Col 29]
// page.tsx Cannot find name "Result" [Ln 30, Col 20] 
// Item.tsx Cannot find name "Result" [Ln 5, Col 13] 

#page.tsx

import getWikiResults from "@/pages/lib/getWikiResults"
import Item from "@/pages/[searchTerm]/components/Item"

type Props = {
    params: {
        searchTerm: string
    }
}

export async function generateMetadata({ params: { searchTerm } }: Props) {
    const wikiData: Promise<SearchResult> = getWikiResults(searchTerm)
    const data = await wikiData
    const displayTerm = searchTerm.replaceAll('%20', ' ')

    if (!data?.query?.pages) {
        return {
            title: `${displayTerm} Not Found`
        }
    }

    return {
        title: displayTerm,
        description: `Search results for ${displayTerm}`
    }
}

export default async function SearchResults({ params: { searchTerm } }: Props) {
    const wikiData: Promise<SearchResult> = getWikiResults(searchTerm)
    const data = await wikiData
    const results: Result[] | undefined = data?.query?.pages

    const content = (
        <main className="bg-slate-200 mx-auto max-w-lg py-1 min-h-screen">
            {results
                ? Object.values(results).map(result => {
                    return <Item key={result.pageid} result={result} />
                })
                : <h2 className="p-2 text-xl">{`${searchTerm} Not Found`}</h2>
            }
        </main>
    )

    return content
}

#Item.tsx

import Link from 'next/link'
import Image from 'next/image'

type Props = {
    result: Result
}

export default function Item({ result }: Props) {
    const itemTextCol = (
        <div className="flex flex-col justify-center">
            <h2>
                <Link href={`https://en.wikipedia.org/?curid=${result.pageid}`} target="_blank"
                    className="text-xl font-bold underline">
                    {result.title}
                </Link>
            </h2>
            <p>{result.extract}</p>
        </div>
    )

    const content = result?.thumbnail?.source
        ? (
            <article className="m-4 max-w-lg">
                <div className="flex flex-row gap-4">
                    <div className="flex flex-col justify-center">
                        <Image src={''} alt={''}>
                            src={result.thumbnail.source}
                            alt={result.title}
                            width={result.thumbnail.width}
                            height={result.thumbnail.height}
                        </Image>
                    </div>
                    {itemTextCol}
                </div>
            </article>

        )
        : (
            <article className="m-4 max-w-lg">
                {itemTextCol}
            </article>
        )

    return content
}

I have no clue why I’m not able to get the Result linked to the pages.tsx file. Is there something I’m missing?

I’m trying to query the results from the Item.tsx file without success. I should be able to link the Item component to the pages.tsx file but it keeps on stating there is no ‘Result’ name in both files.

TypeError: Value is not an object: undefined

Here is my data.json file

"base_url": "https://gorest.co.in/public/v2/users"

Here is my k6 Sample.js

import http from 'k6/http';
import { check } from 'k6';
import { sleep } from 'k6';
import {open} from 'k6';

const jsonData = JSON.parse(open(__ENV.resourseURL));
const baseURL = jsonData.base_url;

export let options = {
vus: 10, // Number of virtual users to simulate
duration: '1m', // Duration of the test in minutes
};

export default function () {
// Send an HTTP GET request
let response = http.get(baseURL);

// Assert the response code is 200
check(response, { 'Status is 200': (r) => r.status === 200 });

// Add additional assertions using check()

// Sleep for 1 second before executing the next iteration
sleep(1);
}

and when I am running it via command

k6 run –env resourseURL=data.json Sample.js

it is giving me an TypeError: Value is not an object: undefined