Check how Mandy mongoose models exist

I’m trying to code a guess the emoji system and for this I need to check how many Models exists.

This is what I’m trying to do:

const data = model.findOne();

model.create({ ID: data.length + 1})

I try to search for the models and then create a new model with an ID which includes the number of the existing models + 1.

If I run the command with this code, it returns NaN in my database at ID. So it’s “NotANumber”.

Does someone know how to fix?

drizzle-orm with multiple many-to-one relations – Please specify relation name at normalizeRelation

I have two tables and two relations that I have defined as follows:

export const games = pgTable('games', {
    id: serial('id').primaryKey(),
    player1Id: integer('player1_id'),
    player1Scores: json('player1_scores'),

    player2Id: integer('player2_id'),
    player2Scores: json('player2_scores'),

    winnerId: integer('winner_id'),
});

export const players = pgTable('players', {
    id: serial('id').primaryKey(),
    email: varchar('email'),
    name: varchar('name', { length: 256 }),
});

export const playersRelations = relations(players, ({ many }) => ({
    games: many(games),
}));

export const gamesRelations = relations(games, ({ one }) => ({
    player1: one(players, { fields: [games.player1Id], references: [players.id] }),
    player2: one(players, { fields: [games.player2Id], references: [players.id] }),
    winner: one(players, { fields: [games.winnerId], references: [players.id] }),
}));

However, I get the error message with the gamesRelations that there are “multiple relations between ‘games’ and ‘players’). If I remove the entry with ‘player2’ and ‘winner’ from the gamesRelation, it works. But then the information is missing.

Probably the error is relatively simple, but I have no more ideas and am grateful for any help.

Error message:

There are multiple relations between “games” and “players”. Please specify relation name at normalizeRelation

In Javascript how could I loop over a table and its nested rows and generate a CSV?

The problem

I’m trying to loop over a table which has nested row and export all of the data to a CSV. This is the data structure:

  • Profile
  • Profile > Linked users

The data is coming from an API as an array with nested objects that I then loop over and output to the view.

My attempt

My current logic is partially working but interprets any table rows with nested rows as one combined row.

I can loop over the table rows but can’t exclude the combined rows so I get the following output:

  • Tom
  • Tom Jack Sam Alex (combined)
  • Jack
  • Sam
  • Alex
  • Josh

Codepen example

Here’s a basic example that logs the output: https://codepen.io/joshuarobertson/pen/xxQjmgV

Table data structure

This is a basic example of the table structure:

<table border="1" cellspacing="0" cellpadding="10">
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Town</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Tom</td>
            <td>20</td>
            <td>London</td>
        </tr>
        <tr>
            <td colspan="3">
                <table>
                    <tbody>
                        <tr>
                            <td>Jack</td>
                            <td>30</td>
                            <td>Glasgow</td>
                        </tr>
                    </tbody>
                    <tbody>
                        <tr>
                            <td>Sam</td>
                            <td>40</td>
                            <td>Belfast</td>
                        </tr>
                        <tr>
                            <td>Alex</td>
                            <td>50</td>
                            <td>Hull</td>
                        </tr>
                    </tbody>
                </table>
            </td>
        </tr>
        <tr>
            <td>Josh</td>
            <td>20</td>
            <td>Cardiff</td>
        </tr>
    </tbody>
</table>

Javascript

How I’m trying to loop over the table rows:

/*
** Export table data to CSV
*/
function exportToCsv () {
    // Get the table element
    var table = document.querySelector('table')

    // Create an empty array to store the cell values
    var cellValues = []

    // Get the table headers from the thead section
    var headerValues = []

    table.querySelectorAll('thead th').forEach(function(header) {
        headerValues.push(header.textContent.trim())
    })

    // Add the header values to the main cell values array
    cellValues.push(headerValues.join(','));

    // Function to process the rows recursively
    function processRows(rows) {
        rows.forEach(function(row) {
            var rowValues = []

            // Check if the row has nested tables
            var nestedTables = row.querySelectorAll('table');

            if (nestedTables.length > 0) {
                // Process nested tables recursively
                nestedTables.forEach(function(nestedTable) {
                    var nestedRows = nestedTable.querySelectorAll('tr')
                    console.log(nestedRows[0].innerText)
                    console.log(nestedRows[1].innerText)
                    console.log(nestedRows[2].innerText)
                    processRows(nestedRows)
                });
            } 
            else {
                // Loop over each cell of the row
                row.querySelectorAll('td').forEach(function(cell) {
                    rowValues.push(cell.textContent.trim())
                });

                // Add the row values to the main cell values array
                cellValues.push(rowValues.join(','))
            }
        })
    }

    // Process the top-level table rows
    var topRows = table.querySelectorAll('tbody tr')
    processRows(topRows)

    // Log the comma-separated list to the console
    console.log(cellValues.join('n'))


    // Combine each row data with new line character
    csv_data = csv_data.join('n')

    // Call this function to download csv file
    downloadCsv(csv_data)
}

/*
** Download CSV
*/
function downloadCsv (csv_data) {

    // Create CSV file object and feed
    // our csv_data into it
    csv_data = new Blob([csv_data], {
        type: "text/csv"
    })

    // Create to temporary link to initiate
    // download process
    const temp_link = document.createElement('a')

    // Download csv file
    temp_link.download = "GfG.csv"
    const url = window.URL.createObjectURL(csv_data)
    temp_link.href = url

    // This link should not be displayed
    temp_link.style.display = "none"
    document.body.appendChild(temp_link)

    // Automatically click the link to
    // trigger download
    temp_link.click()
    document.body.removeChild(temp_link)
}

Any help is much appreciated.

Sending event to GA4 occasionally fails with TypeError: Failed to fetch

Currently, I am sending custom GA events on any push notification action from the service worker. To send the events I used the endpoint and parameters from official GA4 documentation.

Since I cannot see the browser terminal to see the error, in the code for GA endpoint failures I log an error to my database. I receive a majority of the GA events (95%), but some of them fail and I get either TypeError: Load failed or TypeError: Failed to fetch logged to my database.

I personally cannot replicate the issue myself. All events triggered by me are sent successfully, but for some website users it fails. I tried checking if I could find a common theme based on their devices or browsers, but it seems to be random since it happens on Samsung Internet, Mobile Safari, Chrome Mobile and other browsers.

My service worker:

// ...

// Triggered when push notification is closed
self.addEventListener('notificationclose', event => {
  event.waitUntil(trackEvent('webpush_action', { action: 'Closed' }));
});

async function trackEvent(name, params) {
  // ...

  const subscription = await self.registration.pushManager.getSubscription();

  if (!subscription) {
    throw new Error('No subscription currently available.');
  }

  try {
    const response = await fetch(`https://www.google-analytics.com/mp/collect?measurement_id=${measurementId}&api_secret=${apiSecret}`, {
      method: 'POST',
      body: JSON.stringify({
        client_id: subscription.endpoint,
        events: [{ name, params }]
      })
    });

    if (!response.ok) {
      throw new Error(await response.text());
    }

    console.info('[Service Worker] Analytics event sent:', name);
  } catch (error) {
    const message = `[Service Worker] Unable to send the analytics event: ${error}`;
    console.warn(message);
    await logAnError(message); // just to log an error to my database for debugging purposes
  }
}

I tried manually replicating the issue by executing fetch to send the events from the browser console with either incorrect api_secret, client_id or events data values, but I could not get the error. The call always returns 204.

Vue access data from parent if using runtime compiler

Im working on a project with vuejs and the goal is to render html received from a server which can include custom vue components. These components need access to a shared context object to fetch data of their own. Im rendering this html using vues compile function. To get the data into the child components im aware of two ways of doing it…

  • 1: replacing part of the html (which does not include any binding like <component :props="var" /> just the <component />)
  • 2: accessing it from the child component using this.$parent.context

I am quite sure that the second way is not the “vue way of doing things”. Im interested in any ideas how to solve the problem in a more elegant way.

TypeError: Cannot read property ‘addEventListener’ of null. Whats going on guys? [duplicate]

Hey guys there is something that requires the upmost assistance. I have a checkbox in a div.

Here is the code:

const flareup = document.getElementById("incorrect")
const checker = document.getElementById("clicker")
const maincheck = document.getElementById("maincheck")  
checker.addEventListener("mousedown", function(){
    if(event.button == 0){
        console.log("Ok")
        if(checker.checked == true){
            console.log("I am here")
            flareup.style.display = "block"
        }
    if(event.button == 1){
       maincheck.className = "animationclass"
    }
  }
})

As can be seen in the code, I want it to show something if it is left clicked and i want it to add an animation class if it is right clicked. My problem is, before I even so much as click it, I get an Uncaught Error, stating that it:

TypeError: Cannot read property 'addEventListener' of null

I am not sure whats wrong. I have made sure my script tag for the javascript file is on top and that i havent misspelled anything or given it a class instead of an ID. For more context, here is my HTML:

<!DOCTYPE html>
<html>
<head>
<title>The Verification Game</title>
<link rel="stylesheet" href="./starting.css"></link>
</head>
<script src="https://kit.fontawesome.com/1f2023aaf1.js" crossorigin="anonymous"></script>
<script src="verification.js"></script>
<body>
<div id="underneath">
<h2>Are you a human?</h2>
<input type="checkbox" id="realclicker"></input>
</div>
<div id="maincheck">
<h2>Are you a robot?</h2>
<input type="checkbox" id="clicker"></input>
</div>
<div id="incorrect">
<div id="inner">
<h1 class="fancytext">So you are a robot? You can't come here.</h1>
</div>
</div>

Please help!

black and white video stream using html5 video and javascript

Is there a solution to stream a video ( live webcam ) in black and white continuously using javascript,

I want to test every single pixel if the average of rgb [(red + green + blue)/3] is higher than x turn it to white ( 255 ) else turn it to black ( 0 )

I’ve found this code but it crashes, it can not stream with no stop,

const videoElement = document.getElementById('videoElement');

const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');

// Function to process each frame
function processFrame() {
  // Set canvas dimensions to match the video element

  canvas.width = videoElement.videoWidth;
  canvas.height = videoElement.videoHeight;

  // Draw the current frame of the video onto the canvas
  ctx.drawImage(videoElement, 0, 0);

  // Get the image data of the current frame
  const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  const data = imageData.data;

  // Iterate over each pixel in the image data
  for (let i = 0; i < data.length; i += 4) {
    // Extract RGB values of the pixel

    const red = data[i];
    const green = data[i + 1];
    const blue = data[i + 2];

    // Calculate the average brightness of the pixel

    const brightness = (red + green + blue) / 3;

    // Define the threshold value
    const threshold = 120; // Adjust this value as needed

    // Compare the brightness with the threshold
    if (brightness > threshold) {

      // Turn the pixel to white
      data[i] = 255; // Red
      data[i + 1] = 255; // Green
      data[i + 2] = 255; // Blue
    } else {
      data[i] = 0; // Red
      data[i + 1] = 0; // Green
      data[i + 2] = 0; // Blue   
    }
  }

  // Put the modified image data back onto the canvas

  ctx.putImageData(imageData, 0, 0);

  // Draw the modified canvas onto the video element

  videoElement.srcObject = canvas.captureStream();

  // Call the processFrame function recursively to continuously process frames

  requestAnimationFrame(processFrame);
}


videoElement.addEventListener('play', processFrame);

net::ERR_QUIC_PROTOCOL_ERROR 200

Access the index.html homepage and pull JS files to report an error,messages:net::ERR_QUIC_PROTOCOL_ERROR 200
The console reports an error, the far right prompts login: 37, click and locate such a piece of code:

const changeFavicon = link => {
        let $favicon = document.head.querySelector('link[rel="icon"]');
        if ($favicon !== null) {
          $favicon.href = link;
        } else {
          $favicon = document.createElement("link");
          $favicon.rel = "icon";
          $favicon.href = link;
          document.head.appendChild($favicon);
        }
      };
      let iconUrl = localStorage.getItem('company.icon') || '/favicon.ico';
      changeFavicon(iconUrl);
      window.document.title = localStorage.getItem('company.name') || 'test';

There is no idea, this is in the browser refresh button, right-click to clear cache hard loading will report this problem, how to troubleshoot this problem?

Bootstrap elements bleeding on smaller device sizes

Something is weird with the margin/padding of the carousel. The container for the lorem text when resized automatically sizes into the navbar when on less than ~990px breakpoint.

This is not what I want intended for mobile devices. I’m unsure how to fix it either. I have a unique situation where I have a video playing in the background of essentially the carousel.

I tried adding padding to the body, that didn’t fix it either.

<nav class="navbarWidth navbar navbar-expand-lg navbar-dark bg-dark fixed-top position-fixed " aria-label="Eighth navbar example">
    <div class="container-fluid">
        <a class="navbar-brand" href="/">Website name</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarsExample07"
            aria-controls="navbarsExample07" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse " id="navbarsExample07">
            <ul class="navbar-nav navbar-collapse justify-content-end px-4">
                <li class="nav-item">
                    <a class="nav-link" aria-current="page" href="/">lorem</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/">lorem</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/">lorem</a>
                </li>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown" aria-expanded="false">
                        <Dropdown>Other Resources
                    </a>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="/"></a></li>
                        <li><a class="dropdown-item" href="/">lorem</a></li>
                        <li><a class="dropdown-item" href="/">lorem</a></li>
                        <li><a class="dropdown-item" href="/">lorem</a></li>
                        <li><a class="dropdown-item" href="/">lorem</a></li>
                    </ul>
                </li>
            </ul>

        </div>
    </div>
</nav>


<body class="d-flex flex-column vh-100 min-vh-100 ">
    <!-- <div id=""></div> -->
    <div id="myCarousel" class="carousel w-100 mb-6 " data-bs-ride="carousel" data-bs-theme="light">
        <div class="carousel-inner">
            <div class="carousel-item active  ">
                <div id="video-container"></div>
                
                <script>var video = document.createElement("video");
                    video.src = "url.mp4 video";
                    video.preload = "auto";
                    video.muted = true;
                    video.autoplay = true;
                    video.loop = true;
                    video.addEventListener("loadeddata", function () {
                        videoContainer = document.getElementById("video-container");
                        videoContainer.appendChild(video);
                        video.play();
                    });
                </script>

                <div class="carousel-caption text-start p-xxl-auto col-sm-6 col-lg mx-auto ">
                    <div class="row">
                        <div class="col-12 col-lg-6">
                            <h1 class="display-3 fw-normal text-white pt-5">NAME</h1> // Text that bleeds into the navbar
                            <h2 class="display-5 fw-normal lh-1 text-white">lorem</h2>
                            <h2 class="display-5 fw-normal lh-1 text-white">lorem</h2>
                            <br>
                            <p class="fs-3 text-white position-relative ">lorem
                            </p>
                            <p class="lead text-white"> lorem </p>
                        </div>
                        <div class="col-6 col-sm-4">
                            <img src="../images/1.jpg" alt=""
                                class="featurette-image img-fluid mx-auto rounded-circle img-thumbnail " xmlns=""
                                role="img" aria-label="Placeholder: 500x500" preserveAspectRatio="xMidYMid slice"
                                focusable="false">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

I adjusted the body padding, the container padding/margins with different breakpoints.

What would be the best way to handle this problem?

useState does not set

First of all, yes, I talked with ChatGPT, it does not give a working answer.
The main is that I want an image to be rendered.
Why in my case the setter does not work?

Probably the error lies on the surface, I am a newbie so please do not be strict.

I am trying to set setMeme in two places, but it does not work.
What’s horroring for me is that I do not receive any error.

I screened a few sites, but solutions mostly rely on “useEffect”, and did not help

this did not help:

The useState set method is not reflecting a change immediately

import React from "react"; import memesData from "../memesData.js"; import { useState, useEffect } from "react"; import front_img from "../../public/images/front_meme.png";

function importAll(r) {
    return r.keys().map(r);   }
     const images = importAll(require.context('./', false, /.(png|jpe?g|svg)$/)); //alert(images); // Create a require.context for the images folder //const imagesContext = require.context("../images", true);

export default function Meme() {
    const [memeImg, setMeme] = useState("");
    const [word , setWord] = useState("");
    //setWord("dfb")
    //alert(word);

    const getMemeImage = async () => {
      const memesArray = memesData.data.memes;
      const randomNumber = Math.floor(Math.random() * memesArray.length);
      const selectedMeme = memesArray[randomNumber];
    
      setMeme("svsdsd");
      // No console.log here
      if (selectedMeme && selectedMeme.url) {
        setMeme(selectedMeme.url);
      }
      useEffect(() => {
        console.log("Meme Image:", memeImg);
      }, [memeImg]);
    };
    
     // Add memeImg as a dependency for useEffect

     return (
    <div>
      <form className="form">
        <input type="text" className="form--input" />
        <input type="text" className="form--input" />
        <button onClick={getMemeImage} className="form-button">
          Get a new meme image
        </button>
      </form>
      <img className="meme--image" src={front_img} alt="" />
      
        <img
          className="meme--image"
          src={memeImg}
          // imagesContext(`./${memeImage}`).default 
          alt=""
        />
      
    </div>   ); }

Node.js, Express.js and @mysql/xdevapi based Boilerplate code?

I am using @mysql/xdevapi in my Express.js application for creating REST web APIs.

My current way of using @mysql/xdevapi is

const mysqlx = require('@mysql/xdevapi')

const options = {
    host: 'mysql',
    port: 33060,
    password: 'password',
    user: 'root',
    schema: 'DB_name'
}

const session = await mysqlx.getSession(options)

var getData = async function (req, res) {
    try {
        let { id } = req.body
        var data = (await session.sql(`SELECT * FROM data_table WHERE id = ${id}`).execute()).fetchAll()
        res.json({ success: true, data: data })
    } catch (error) {
        res.json({ success: false, message: "Error in getData" })
    }
}

var app = express()
app.post('/getData', getData)

var server = app.listen(config.express.bindPort, config.express.bindIp, function () {
    console.log(`Express listening on port ${config.express.bindIp}:${config.express.bindPort}`)
})

This setup give me error after few hours

Error: This session was closed because the connection has been idle too long. Use "mysqlx.getSession()" or "mysqlx.getClient()" to create a new one.

What should be right way to use @mysql/xdevapi with Express.js? Any good Boilerplate code?

Getting “Uncaught TypeError: Cannot read properties of undefined (reading ‘push’)” when attempting to run this simple JavaScript code

I am trying to make a simple karaoke queue app to help learn the basics of JavaScript and I’m not exactly sure where I am going wrong. Here is the code I have so far:

var queueCounter = 0;
var singerQueue = [];

function rotateQueue(inputArray) {
    let queue = inputArray;
    let currentSinger = queue.shift();
    queue. Push(currentSinger);
    return queue;
}

function addNewSinger(inputArray, newSinger) {
    let queue = inputArray;
    if (singerQueue == undefined || singerQueue.length == 0) {
        queueCounter++;
        queue.push([queueCounter, newSinger]); // Here is TypeError
    } else {
        let lastSinger;
        queue.forEach(value => {
            if (value[0] == queueCounter) {
                lastSinger = value;
            }
        });
        if (lastSinger == undefined) {
            return 'ERROR';
        } else {
            let index = queue.indexOf(lastSinger);
            queueCounter++;
            queue.splice(index, 0, [queueCounter, newSinger]);
            return queue;
        }
    }
}

singerQueue = addNewSinger(singerQueue, 'Some Name');
singerQueue = addNewSinger(singerQueue, 'Another Name');
singerQueue = rotateQueue(singerQueue);
console.log(singerQueue);

// assuming this output should be:
// [[2, 'Another Name'], [1, 'Some Name']]

I have been tweaking it to try and get around this type error (for instance the whole let queue = inputArray bits I know it’s redundant), but the main goal is to have a queue that you can rotate and add new people while adding them after the last person to sign up, not necessarily the actual end of the qeueue. (I know I haven’t added a way to catch if someone is already in the queue yet) I am hoping someone has some insight as to where the type error is coming from… Thank you in advance!

How to convert Array of javascript objects to form-encoded for POST?

For an Angular(v14) application, I have a requirement to “POST the following form-encoded parameters to a given URL for a list of items where n is the zero based index of the lines”

Format:

 ItemNo[n]=<Item Identifier>
 Description[n]=<Item Identifier>

So, for example, 3 items would be like so:

 ItemNo[0]=1001
 Description[0]=a wonderful item
 ItemNo[1]=1002a
 Description[1]=something
 ItemNo[2]=1002c
 Description[2]=another thing

On my end, the items I need to POST in the form-encoded format are in an array like so:

 [
     { ItemNo: '1001', Description: 'a wonderful item' },
     { ItemNo: '1002a', Description: 'something' },
     { ItemNo: '1002c', Description: 'another thing' },
 ]

So I’ve been trying to figure out how to get the array of items into the correct format: Form-encoded, without much luck. Hoping someone can help!

I’ve found quite a few similar questions, (though I’m unsure if I am using the most appropriate search terms) but Angular evolves so quickly that each time I try to implement a suggestion, I find the suggested solution uses one or more depreciated methods, so I’ve ended up with quite a mess of failed attempts!

I’ve written a function which will rewrite my array to add the indexing to the keys, so now I’ve got:

 [
    { ItemNo[0]: '1001', Description[0]: 'a wonderful item' }
    { ItemNo[1]: '1002a', Description[1]: 'something' }
    { ItemNo[2]: '1002c', Description[2]: 'another thing' }
 ]

But how can I get this into a form-encoded type?
Everything I have tried that seemed promising (most recently DefaultUrlSerializer()) seems to give me results like

 "/?0=%5Bobject%20Object%5D&1=%5Bobject%20Object%5D"

(not keyname=value)

Also, on my http.post() method, what should the incoming type be, to be posting “form-encoded”? I’m guessing string?

React form validation using html input properties

There are many fancy ways to validate form inputs in React
but is there a way to get a simple boolean which when a form is submitted tells me if all inputs in the form were valid according to html

html offers simple form validation techniques on input tags like required, min, max and even complex ones like pattern and I’d like to very much use these.

Is there any way I can simply check if a bunch of inputs are valid according to html and get a boolean output according to that?