React ApexCharts Heatmap Can’t display months on x-axis

I am trying to replicate this post using the linked code in the first answer. But I cannot display months in my chart. My goal is to create a a heatmap very similar to Github’s contributions chart. This is the result result Here is my code:

import { useParams } from "react-router-dom/cjs/react-router-dom.min";
import React, { useState, useEffect, useRef } from "react";
import ReactApexChart from "react-apexcharts";

export default function TeamMember() {
  const { TeamId, UserId } = useParams();

  const chartOptions = {
    chart: {
      height: 350,
      type: "heatmap",
    },
    
    colors: ["#008FFB"],
    title: {
      text: "User Contributions",
    },

    xaxis: {
      type: "datetime",
      labels: {
        format: "MMM",
        showDuplicates: false,
      },
    },
  };

  const chartSeries = [
    {
      name: "Sun",
      data: [
        { x: "04-26-2020", y: 0 },
        { x: "05-03-2020", y: 40 },
        { x: "05-10-2020", y: 40 },
        { x: "05-17-2020", y: 40 },
        { x: "05-24-2020", y: 40 },
      ],
    },
    {
      name: "Mon",
      data: [
        { x: "04-27-2020", y: 10 },
        { x: "05-04-2020", y: 40 },
        { x: "05-11-2020", y: 40 },
        { x: "05-18-2020", y: 40 },
        { x: "05-25-2020", y: 40 },
      ],
    },
    {
      name: "Tue",
      data: [
        { x: "04-28-2020", y: 20 },
        { x: "05-05-2020", y: 40 },
        { x: "05-12-2020", y: 40 },
        { x: "05-19-2020", y: 40 },
        { x: "05-26-2020", y: 40 },
      ],
    },
    {
      name: "Wed",
      data: [
        { x: "04-29-2020", y: 40 },
        { x: "05-06-2020", y: 40 },
        { x: "05-13-2020", y: 40 },
        { x: "05-20-2020", y: 40 },
        { x: "05-27-2020", y: 40 },
      ],
    },
    {
      name: "Thu",
      data: [
        { x: "04-30-2020", y: 50 },
        { x: "05-07-2020", y: 40 },
        { x: "05-14-2020", y: 40 },
        { x: "05-21-2020", y: 40 },
        { x: "05-28-2020", y: 40 },
      ],
    },
    {
      name: "Fri",
      data: [
        { x: "05-01-2020", y: 60 },
        { x: "05-08-2020", y: 40 },
        { x: "05-15-2020", y: 40 },
        { x: "05-22-2020", y: 40 },
        { x: "05-29-2020", y: 40 },
      ],
    },
    {
      name: "Sat",
      data: [
        { x: "05-02-2020", y: 70 },
        { x: "05-09-2020", y: 40 },
        { x: "05-16-2020", y: 40 },
        { x: "05-23-2020", y: 40 },
        { x: "05-30-2020", y: 40 },
      ],
    },
  ];

  return (
    <div>
      <div id="chart">
        <ReactApexChart
          options={chartOptions}
          series={chartSeries}
          type="heatmap"
          height={350}
        />
      </div>
      <div id="html-dist"></div>
    </div>
  );
}

Any help on this issue or anything else related to creating this chart would be really helpful.

Google Analytics JavaScript not executed by CefSharp of PupeeterSharp

1.Background

The code snippets in sections 2.1 and 2.2 below aim at executing Google Analytics JavaScript from a C# console application that uses a headless web browser to load the following HTML page hosted on a web server (let’s say https://my.server.com/index.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Title Placeholder</title>
    <!-- Google tag (gtag.js) -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-**********"></script>
    <script>
        window.dataLayer = window.dataLayer || [];

        function gtag()
        {
            dataLayer.push(arguments);
        }

        gtag('js', new Date());
        gtag('config', 'G-**********');
    </script>
</head>
<body>Body Placeholder
</body>
</html>

When the above mentioned HTML page is loaded from a web browser such as Google Chrome, its Google Analytics JavaScript gets executed as expected (Google Analytics server reports that this web page was loaded).

2. C# Code snippets

2.1. Using Puppeteer Sharp

using System.Threading.Tasks;
using PuppeteerSharp;

class Program {
    static async Task Main(string[] args) {        
        await new BrowserFetcher().DownloadAsync();
        var browser = await Puppeteer.LaunchAsync(new LaunchOptions {Headless = true});
        var page = await browser.NewPageAsync();
        page.DefaultNavigationTimeout = 0;
        page.DefaultTimeout = 0;
        var navigation = new NavigationOptions {
            Timeout = 0,
            WaitUntil = new[] {
                WaitUntilNavigation.DOMContentLoaded,
                WaitUntilNavigation.Networkidle0
            }
        };
        await page.GoToAsync("https://my.server.com/", navigation);
        await browser.CloseAsync();
    }
}

2.2 Using CefSharp

using CefSharp;
using CefSharp.WinForms;

class Program {
    static void Main(string[] args) {
        var settings = new CefSettings();
        Cef.Initialize(settings);
        var browser = new ChromiumWebBrowser("https://my.server.com/");
        Cef.Shutdown();
    }
}

3. Question

Why is the Google Analytics JavaScript of the https://my.server.com/index.html page not executed (i.e. Google Analytics server does not report that this web page was loaded) when running the Main methods in sections 2.1 or 2.2
?

Programmatically add label with URL

I am currently adding a label with URL called UAT Template based on the dropdown item select. The label should not be created if already exist.

  • the link is not open in the new tab

  • The label for some reason not created

      function AddURL(){
    
      let lblTemplate = document.getElementsByClassName("ard-FormField-description")[8];
      //Check if the lblTemplate contain word 'UAT Template location'
      if(lblTemplate.innerHTML !== '' && lblTemplate.innerHTML.toLowerCase().indexOf('UAT Template Location') > -1){
          if (lblTemplate.indexOf(lblTemplate) == -1) {
              // create anchor link element
              let link = document.createElement("a")
    
              // Create txt
              let txt = document.createTextNode("UAT Template Location")
    
              //append txt to anchor element
              link.appendChild(txt)
    
              // set the title
              link.title =" Click to UAT Template Location";
    
              // set the href property
              link.href = "https://gampoendev.com/:w:/r/teams/teamcollab/Shared%20Documents/Templates/";
              link.setAttribute('target','_blank');
    
              // get text to add link to
    
              lblTemplate.appendChild(link)
          }
          else {
              return;
          }
      }
    

    }

why setTimeout executed first then the setImmediate in nodeJS-v20.11.0 [duplicate]

console.log("---------Event Order---------");

const fs = require('fs');
const path = require('path');

const currentDir=__dirname
const fileName='example.txt'
const filePath=path.join(currentDir,fileName)

console.log('Start--------');
setTimeout(()=>{
    console.log('setTimeout 1');
},0)
setImmediate(()=>console.log('setImmediate 2'))

setImmediate(()=>console.log('setImmediate 3'))
setTimeout(()=>{
    console.log('setTimeout 4');
},0)

fs.readFile(filePath,(err,data)=>{
    if (err) {
        console.log('Error while reading file',err);
    }else{
        console.log(data.toString());
    }
})
console.log('end--------');

this is the code spinet and the order of log get differ from the official doc
statement:“However, if you move the two calls within an I/O cycle, the immediate callback is always executed first:”
my log as below
Start——–
end——–
setTimeout 1
setTimeout 4
setImmediate 2
setImmediate 3
Hello, this is some content!

Slack Markdown: Most text is only partial hyperlinked instead of full

I have this Cloud Function that posts to Slack, some text is fully hyperlinked but the majority is only partial and I don’t know why. The full bug title should be hyperlinked. Can anyone help me debug it? For example, these are fully hyperlinked:

Fix portfolio Dockerfile path

Profiler for A: The user can still change chains

Yet many aren’t like this:

Overview > Historical Token Portfolio [and other widgets]: Changing
time period filters completely resets the token selection>

Code:

async function generateSummary(groupedBugs) {
    try {
        const openai = new OpenAI({
            apiKey: OPENAI_API_KEY
        });

        const currentDate = new Date();
        const oneWeekAgo = new Date(currentDate.getTime() - 7 * 24 * 60 * 60 * 1000);
        
        let formattedBugs = `*Weekly Bug Recap: ${oneWeekAgo.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })} - ${currentDate.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}*n_______________________________nn`;
        
       // Separate known features and unknown features
       const knownFeatures = {};
       let unknownFeatures = [];

       for (const [feature, bugs] of Object.entries(groupedBugs)) {
           if (feature === 'Unknown Feature') {
               unknownFeatures = bugs;
           } else {
               const mainFeature = feature.split(':')[0].trim();
               if (!knownFeatures[mainFeature]) {
                   knownFeatures[mainFeature] = [];
               }
               knownFeatures[mainFeature].push(...bugs);
           }
       }

       // Format known features
       for (const [feature, bugs] of Object.entries(knownFeatures)) {
           formattedBugs += `*${feature}*n`;
           bugs.forEach((bug, index) => {
               const fullTitle = bug.title.replace(/^BUGs*::s*/i, '').trim();
               formattedBugs += `${index + 1}. <${bug.url}|${fullTitle}>n`;
           });
           formattedBugs += 'n';
       }

       // Format unknown features at the bottom
       if (unknownFeatures.length > 0) {
           formattedBugs += `*Unknown Feature*n`;
           unknownFeatures.forEach((bug, index) => {
               const title = bug.title.replace(/^BUGs*::s*/i, '').trim();
               formattedBugs += `${index + 1}. <${bug.url}|${title}>n`;
           });
       }


        const prompt = `Format the following bugs by feature using Slack's markdown syntax:
        - Preserve the existing bold text, underlines, and hyperlinks
        - Do not use code blocks, quote blocks, or any other additional formatting
        - Do not add any additional information
        - Ensure the output matches the input format exactly but make sure hyperlink covers full text, not partial!
        - The output should be plain text with Slack markdown, not wrapped in any blocks

        Here's the bug summary to format:

        ${formattedBugs}`;

        const response = await openai.chat.completions.create({
            model: "gpt-4o-mini",
            messages: [{ "role": "user", "content": prompt }],
        });

Rxjs observer un-subscription in angular [duplicate]

I am creating a rxjs Subject inside a angular component and creating a subscription to that Subject in that component itself.
In that case, is the following statement correct

You do not need to unsubscribe the autosearch subscription. That's because the observer that is being subscribed to will be out of scope when that component gets destroyed, so all its subscriptions will be garbage collected automatically

Angular Data table is working fine with static data but not with api data

I am implementing Angular data table in my project but problem
is that when implementing with static data its working fine but
when working with api data or dynamic data its not working
fine.
Its loading data in datatable but search and pagination is not
showing. I have tried a lot of online solutions but search and
pagination is not showing.

Can any body tell me the exact cause and its solutions. I am
using bootstraps and angular 17 and i have implemented all
necessary steps and its also working fine with static data.
Thanks.

Floting-UI: “Uncaught TypeError: e is undefined”

Here is my reprex:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Floating-UI Example</title>
    <style>
        .tooltip {
            position: relative;
            cursor: pointer;
            display: inline-block;
            margin-top: 100px;
        }
        .tooltip-content {
            display: none;
            position: absolute;
            background: #333;
            color: #fff;
            padding: 5px;
            border-radius: 5px;
            white-space: pre-wrap;
            z-index: 1000;
        }
    </style>
    <script src="https://unpkg.com/@floating-ui/[email protected]/dist/floating-ui.dom.umd.js"></script>
</head>
<body>
    <div class="tooltip" id="tooltip">
        Hover over me
        <div class="tooltip-content" id="tooltip-content">
            Tooltip content
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const { computePosition, offset, flip, shift } = window.FloatingUIDOM;
            const tooltip = document.getElementById('tooltip');
            const tooltipContent = document.getElementById('tooltip-content');

            tooltip.addEventListener('mouseenter', () => {
                tooltipContent.style.display = 'block';
                computePosition(tooltip, tooltipContent, {
                    placement: 'top',
                    middleware: [
                        offset({ mainAxis: 10 }),  // Correct usage of offset
                        flip(),
                        shift({ padding: 5 })
                    ],
                }).then(({ x, y }) => {
                    Object.assign(tooltipContent.style, {
                        left: `${x}px`,
                        top: `${y}px`
                    });
                }).catch(error => {
                    console.error("Error computing position:", error);
                });
            });

            tooltip.addEventListener('mouseleave', () => {
                tooltipContent.style.display = 'none';
            });
        });
    </script>
</body>
</html>

Getting error “entries is not a function” when trying .entries() on an Object [closed]

I’m attempting to iterate through all the entries in an Object.

All the how-to guides seem to suggest using Object.entries() but I’m getting an error that no such function exists.

I’m initially forming the object as a PHP array from an SQL DB, then dumping the PHP array into Javascript Object using:

<script type="javascript">var libr = <?php echo json_encode($library); ?>;</script>

I’ve added a screenshot showing the object’s structure in a console window, and the specific error when I attempt to call .entries() on it:

screenshot

What am I missing?

glsl code gets broken by for loop (Julia Sets) p5.js [duplicate]

#ifdef GL_ES
precision mediump float;
#endif

varying vec2 pos;

const float MAX_ITERATIONS = 2000.0;
uniform vec2 u_resolution;
uniform float u_time;
uniform float ca;
uniform float cb;
uniform vec2 u_bounds;
uniform vec2 u_aspectRatio;
uniform sampler2D colorMap;
uniform int power;
uniform float zoom;

struct Complex {
    float real;
    float imag;
};

// Function to perform complex multiplication
Complex complexMultiply(Complex a, Complex b) {
    Complex result;
    result.real = a.real * b.real - a.imag * b.imag;
    result.imag = a.real * b.imag + a.imag * b.real;
    return result;
}

// Complex complexPower(Complex a, int n) {
//     Complex result;
//     result.real = 1.0;
//     result.imag = 0.0;

//     Complex base = a;

//     for (int i = 0; i < n; i++) {
//         result = complexMultiply(result, base);
//     }

//     return result;
// }


// Function to perform complex addition
Complex complexAdd(Complex a, Complex b) {
    Complex result;
    result.real = a.real + b.real;
    result.imag = a.imag + b.imag;
    return result;
}

// Function to calculate the magnitude of a complex number
float complexMagnitude(Complex a) {
    return sqrt(a.real * a.real + a.imag * a.imag);
}

float iterations = 0.0;

float iterateSet(Complex z0, Complex c, int n) {

    Complex oldZ = z0;

  // iterate for max iterations
  for(float i = 0.0; i < MAX_ITERATIONS; i++) {
    // exit condition
    // if the magnitude of the complex number is greater than 2, return the number of iterations
    if (complexMagnitude(oldZ) > 4.0) {
      break;
    }

    // calculate the real and imaginary parts of the complex number
    Complex newZ = complexAdd(complexMultiply(oldZ, oldZ), c);
    oldZ = newZ;
    iterations++;
  }
// color binding
  if(iterations == MAX_ITERATIONS) {
    return 0.0;
    } else {
        float abs_z = complexMagnitude(oldZ);
        return iterations + 1.0 - log(log(abs_z))/log(float(n));
    }
    
}

void main(){

    vec2 z = pos * 2.0 - 1.0; // Convert from [0,1] to [-1,1]
    z.x *= u_aspectRatio.x;
    z.y *= u_aspectRatio.y;

    // add zoom
    z.x *= zoom;
    z.y *= zoom;


    // Apply bounds
    z = z * (u_bounds.y - u_bounds.x) / 2.0 + (u_bounds.x + u_bounds.y) / 2.0;

    Complex c = Complex(ca, cb);
    int power = power;                // Degree of the function z^n + c

    Complex z0 = Complex(z.x,z.y);

    float i = iterateSet(z0, c, power);

  // Modify the hue to be more interesting with time-based effects
    float hue = mod(sqrt(i) + u_time * 0.1, 1.0); // Adjust hue with time
    float sat = 0.5 + 0.5 * sin(u_time * 0.5); // Vary saturation over time
    float bright = 1.0 - min(i / MAX_ITERATIONS, 1.0); // Brightness based on iteration

       // Refined color effect
    // float normalizedI = i / MAX_ITERATIONS; // Normalize iterations
    // float hue = mod(sqrt(normalizedI) * 2.0 + u_time * 0.1, 1.0); // Enhanced hue with time
    // float sat = 0.7 + 0.3 * sin(u_time * 0.7); // More pronounced saturation variation
    // float bright = 0.8 - 0.6 * normalizedI; // Improved brightness based on iteration

    // Create a more dynamic color effect
    gl_FragColor = vec4(hue, sat, bright, 1.0);

}

As you can here I am visualizing a Julia set but while i am taking the power as input.
In the line here, Complex newZ = complexAdd(complexMultiply(oldZ, oldZ), c);

I got to call a square on the oldZ (Complex number).

I am using the function to get complex number of power n but that exact lines are making the difference in the shader it doesn’t work and produces the error. if for a power n i just multiply oldZ n times it works perfectly fine but can’t make a function to do it for me as the error comes up.

`

Uncaught TypeError: Failed to execute 'useProgram' on 'WebGL2RenderingContext': parameter 1 is not of type 'WebGLProgram'.
    at o.value (p5.min.js:2:998442)
    at o.value (p5.min.js:2:996492)
    at s.value (p5.min.js:2:983345)
    at a.default.RendererGL.drawBuffers (p5.min.js:2:898165)
    at S.default.RendererGL.rect (p5.min.js:2:755846)
    at l.default._renderRect (p5.min.js:2:525825)
    at l.default.rect (p5.min.js:2:525322)
    at draw (sketch.js:18:3)
    at e.default.redraw (p5.min.js:2:545491)
    at l.default.resizeCanvas (p5.min.js:2:518532)
This works ```                                                                                       if(n == 2) {
      oldZ = complexAdd(squaredZ, c);
    } else if (n == 3) {
      oldZ = complexAdd(cubedZ, c);
    }  else if (n == 4) {
      oldZ = complexAdd(complexMultiply(oldZ, cubedZ), c);
    } else {
      oldZ = complexAdd(complexMultiply(complexMultiply(oldZ, cubedZ), oldZ), c);
      }. ``` but this doesn't                                                                  Complex complexPower(Complex a, int n) {                                                            Complex result;
     result.real = 1.0;
     result.imag = 0.0;

     Complex base = a;

     for (int i = 0; i < n; i++) {
         result = complexMultiply(result, base);
     }

     return result;
 } ```

I tried making a recursive function to get the value when given an exponential power but that broke the code and after removing and re pasting each line of the code, it was the complexPower function which broke it.

So I changed it to for loop and it just keeps breaking the code, I comment the function and it’s works neatly and add it then get the error that my glsl can’t access useProgram.

I want to have a power function but don’t know why this keeps happening and how to make a function that works in this scenario.

My working laptop details are :
name : Apple Macbook Air
chip : Apple M1
memory : 8GB
macOS : 14.5 (23F79)

I am using p5.js with VScode and redering in the chrome browser by processing the script file in an html page.

Embedding a React app externally in another React app via CDN

enter image description here

I need to display a component from one React app within another React app using a CDN. However, I am encountering an error related to the useState hook. The component works fine in its original app, but when imported via CDN, it fails to function properly, and the error specifically points to an issue with useState. How can I resolve this issue and successfully integrate the component?

Error 404 Not Found. Connecting my Nest.js with React via Axios

I’m using Nest.js on my backend and React on my front end.

It seems that I’m having a problem doing a Post request via Axios. Hence, I keep getting this 404 (Not found error).

Why am I still getting this 404 error?

// FrontEnd

import React from "react";
import axios from "axios";

const AddSched: React.FC = () => {
    const handleClick = async () => {


        try{
            const createNapTimeDto = {
                userId: 5, 
                babyId: 5, 
                date: new Date().toISOString()
            }
        
            const response = await axios.post('http://localhost:3000/naptime/create', createNapTimeDto);
            console.log("Created object", response)
        }catch(error){
            console.error("There was an error", error)
        }
    };


    return (
        <div>
            <h2>Ready to log for Baby Axel</h2>
            <button onClick={handleClick}>Nap Time</button>
            <button onClick={handleClick}>Diaper Time</button>
            <button onClick={handleClick}>Tummy Time</button>
            <button onClick={handleClick}>Bath Time</button>
        </div>
    );
};

export default AddSched;


//backend

import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { NapTimeEntity } from '../naptime.entity';
import { Repository } from 'typeorm';
import { UserEntity } from 'src/user/user.entity';
import { CreateNapTimeDto } from '../dto/createNaptime.dto';
import { BabyEntity } from 'src/baby/baby.entity';
import { GetOneResponseDto } from '../dto/getOneResponse.dto';

@Injectable()
export class NapTimeService {


    constructor(
        @InjectRepository(NapTimeEntity)
        private readonly napTimeRepo: Repository<NapTimeEntity>,

        @InjectRepository(UserEntity)
        private readonly userRepo : Repository<UserEntity>,

        @InjectRepository(BabyEntity)
        private readonly babyRepo : Repository<BabyEntity>



    ){}


    async create(
        createNapTimeDto: CreateNapTimeDto
    ){

        //checks if user is existing
        const existingUser = await this.userRepo.findOneBy({id: createNapTimeDto.userId})
        if(!existingUser){
            throw new NotFoundException({
                status: "Error", 
                message: "UserID not found!"
            })
        }


        //checks if a babyId matches UserId
        const matchedBaby = await this.babyRepo.findOne({
            where: {
                id: createNapTimeDto.babyId,
                user: existingUser
            }
        })


        if(!matchedBaby){
            throw new NotFoundException({
                status: "error",
                message: "baby does not belong to the specified user"
            })
        }
        // Save to naptime entity
        const newNaptime = new NapTimeEntity;

        newNaptime.date = createNapTimeDto.date;
        newNaptime.babies = matchedBaby;
        newNaptime.user = existingUser; 
        await this.napTimeRepo.save(newNaptime)

        return{
            status: "OK",
            message: "New naptime created successfully", 
            data: {
                date: createNapTimeDto.date,
                babyId: createNapTimeDto.babyId,
                userId: createNapTimeDto.userId

            }
        }
    }

}


import { Controller, Logger, Body, Query} from '@nestjs/common';
import { NapTimeService } from '../service/naptime.service';
import { Post, Get, Patch } from '@nestjs/common';
import { CreateNapTimeDto } from '../dto/createNaptime.dto';
import { UpdateNapTimeResponse } from '../dto/updateNapTimeResponse.dto';

@Controller('naptime')
export class NapTimeController {

    private readonly logger = new Logger(NapTimeController.name);
    constructor(private readonly napTimeService: NapTimeService){}


    @Post('/create')
    async createNapTime(
    
        @Body() createNapTimeDto: CreateNapTimeDto
    ){

        try{

            return this.napTimeService.create(createNapTimeDto)

        }catch(error){
            this.logger.error(NapTimeController.name, error);
            throw error
        }
    }

}

Here are some of the things that I did:

  • Added CORS code on my backend.

  • Verified that the post request is working on the Postman.

  • Verified that my frontend runs at port 3001 and backend at 3000.

Is it possible to handle/read/interpret MediaRecorder video dataavailable event blobs (recorded chunks) in real-time without awaiting the final chunk?

A media element such as a HTML5 video tag can be recorded with the Media Stream Recording API. A straightforward example is provided here by the helpful people at Mozilla:

https://developer.mozilla.org/en-US/docs/Web/API/MediaStream_Recording_API/Recording_a_media_element

Passing a timeslice argument to MediaRecorder‘s start() method causes the callback function supplied to ondataavailable to be called during recording at (approximately) the requested interval.

You might think this should be perfect for doing something fun with the video stream in real time, right?
Stream those blobs to a server backend and let ffmpeg decode or transcode them in real-time, for example?

Apparently not. Fun, it seems, is not allowed. The only thing the “canonical” examples out there do, including the Mozilla one linked above, is to append the incoming blobs to an array of blobs, and then only do anything with that array after recording has finished. Neither real-time, nor fun at all:

let recordedChunks: blob[] = [];
recorder.ondataavailable = event => recordedChunks.push(event.data);

But I could be wrong of course…

  • Is there any way of making sense of the recorded chunk blobs in a standalone way?
  • And can it be done in a standard-compliant way without relying on the
    internal minutiae of how each browser out there has decided to
    implement this recording API?
  • Or is it maybe better to ignore the Media Stream Recording API
    altogether, and use a different method to upload video in a way that
    can be interpreted in real-time?

BTW, I know it’s possible to capture VideoFrames in real-time and upload those as individual images (WEBP or JPEG) via OffscreenCanvas’ convertToBlob() method, but this seems sub-optimal in terms of overall compression and processing efficiency to me.

(It’s summer 2024 and similar -albeit poorly phrased- questions seem to have been asked on SO for several years now, but none of them have ever seemed to received a real answer that wasn’t handwavey nonsense.)

Search Function in JavaScript to retain item and will not disappear upon erasure

I am creating a simple data table where it shows me the values of tracking from a firebase realtime database I am generating the table via JavaScript. Here is my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Build a table</title>
    <script src="https://www.gstatic.com/firebasejs/7.13.2/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.13.2/firebase-analytics.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.13.2/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.13.2/firebase-database.js"></script>    
</head>
<body>
    <div class="container">
        <input id="searchbar" 
               onkeyup="search_animal()" 
               type="text" name="search" 
               placeholder="Search item..">

    </div>


    <script>
            // JavaScript code

            function search_animal() {
            let input = document.getElementById('searchbar').value
            input = input.toLowerCase();
            let x = document.getElementsByClassName('pritem');

            for (i = 0; i < x.length; i++) {
                if (!x[i].innerHTML.toLowerCase().includes(input)) {
                x[i].style.display = "none";
                }
                else {
                x[i].style.display = "xx";
                }
            }
            }

    </script>




    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }


        .container {
            display: flex;
            flex-direction: column;
            align-items: center;
            margin: 20px;
        }

        #searchbar {
            margin: 10px;
            padding: 10px;
            border-radius: 5px;
            width: 50%;
            box-sizing: border-box;
        }

        #list {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .animals {
            font-size: 1.2em;
            padding: 10px;
            border-bottom: 1px solid #ccc;
            animation: fadeIn 0.5s ease-in-out;
        }

        .animals:last-child {
            border-bottom: none;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }        
    </style>

    <button onclick="addData()">CLICK ME</button>

    <style>
        table {
            text-align: center;
        }
    </style>

<table id = "list">

        <tbody id = 'xx'>
            <th width = 200 >Requesting Office</th>
            <th width = 200 >Mayor's Office</th>
            <th width = 200 >Treasury Office</th>
            <th width = 200 >Budget Office</th>
            <th width = 200 >Mayor's Office</th>
        </tbody>
</table>
</body>
<script src="build-table.js"></script>
</html>

For the generation of table here is my code:

  function generateTable(table, data) {
    for (let element of data) {
      let row = table.insertRow();
      
      for (key in element) {
        let cell = row.insertCell();
        row.setAttribute('class', "pritem")
        let text = document.createTextNode(element[key]);
        
        cell.appendChild(text);
      }
    }
  }

I am hauling the files from my realtime database values as follows:

firebase.initializeApp(firebaseConfig);  
  var ltbmofiles = firebase.database().ref("prLTBMO");
 
  
  ltbmofiles.on("value", function(snapshot) {
    var placementObjectrValuesSplit = Object.values(snapshot.val())
    valueMax = placementObjectrValuesSplit
    // will show undefined if not defined or not yet present
    for (var x = 0; x <= placementObjectrValuesSplit.length-1; x++) {
        mountains.push(placementObjectrValuesSplit[x]);
        console.log(placementObjectrValuesSplit[x])

    }
    let table = document.querySelector("table");
    // let data = Object.keys(mountains[0]);
    // generateTableHead(table, data);
    generateTable(table, mountains);

})  

My problem with my code is this:

  1. while it shows my search quite properly when I search “treasury” for example, it shows the treasury row searched. However, when you clear the search bar, it does not show the full table again and whenever you search a word it doesn’t show anything anything anymore. Any ideas why this happens and how can I fix it?

I tried putting the tag properly from the row, while it shows me the item properly, it disappears.