does the react library: react-idle-timer work on mobile browser?

i implemented react-idle-timer as given below in my code

App.js

        const onIdle = () => {
        props.logOut();
    };
    return (
        <div className={styles.app}>
            <Suspense fallback={null}>
                <div className={styles.homeContainer}>
                    <div className={['col-md-12 col-sm-12', styles.dashboardContainer].join(' ')}>
                        <IdleTimer timeout={60 * 1000 * 15} onIdle={onIdle} />
                        <ErrorBoundary>{routes}</ErrorBoundary>
                        <ToastContainer />
                    </div>
                </div>
            </Suspense>
        </div>
    );
}

logOut function:

export const logOut = () => {
    localStorage.clear();
    return {
        type: actionTypes.AUTH_LOGOUT
    };
};

it works just fine on desktop browser but it fails to do so in mobile browser. can anyone suggest the fix for that?

Javascript/jQuery beforeunload and unload not firing

I have a page where I want my script to let the server know that the user went offline when the browser/tab/page is closed.

$(document).ready(function() {
    // Inform the server that the user went online
    setStatus('online');

    // Inform the server that the user went offline
    $(window).on('beforeunload', function() {
        setStatus('offline');
    });

    // Inform the server that the user went offline
    $(window).on('unload', function() {
        setStatus('offline');
    });
});

async function setStatus(status) {
    let { data } = await axios.post('/status', { status: status });
}

The part where I have setStatus('online'); works but I can never seem to set the status to offline when I close the page/tab/browser.

jQuery credit card input format

I want to use jQuery validation for credit card input fields. When I seach for it I saw most people made this happen with additional validation methods.

I tried adding this to my code :

<script src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/additional-methods.js"></script>

or this code :

jQuery.validator.addMethod("lettersonly", function(value, element) {
  return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please"); 

But I’m getting this error

enter image description here

Is this about a version problem, I use the jQuery 3.6 version and tried 1.7 and 1.9 versions for validation plugin.

Note: I’m sure that I use validation plugin after adding jQuery cdn. I can reach jQuery but not to jQuery.validator method.

Addition: I’m tring to format name-surname input field with only letters and spaces. If you can help me with that too, I would be glad.(Or is there a plugin prepared for every input field for credit card inputs.)

How to properly display data in chartjs from SQL?

I got started with chartJS, so I really need guidance of where to look and learn. I’m trying to display duplicated data from my SQL to chartJS.

Example:
Table name: Traffic Violations
Data I want to display: Violation types (Speeding, drifting, seatbelt, etc).
How it should be displayed: Y-axis as numbers, X-axis as violation names.

I read this: SQL count how many duplicated values of a derived table
Watched this: 1.3: Graphing with Chart.js – Working With Data & APIs in JavaScript
also watched this: How to Switch Chart to Daily, Weekly and Monthly Data in Chart js
And this: Count Total number of rows in database in php -Analytics in php

I learned few things from each, but still didn’t satisfy my knowledge needs to achieve the goal I want.

I want to display the data in “Daily”, “Monthly”, “Yearly” format.

Sounds like that’s a totally different topic, because I want the “daily” chart to reset every 24 hours, and monthly every month without deleting the data from DB. None of these videos above shows me that, nor I couldn’t find what I’m looking for..

So, how to prepare my DB for chartJS?
best practice to fetch data and show it in the chart?

Here is what I have so far:

<?php
header('Content-Type: application/json');

require_once('./backend/config/connection.php');

$sqlQuery = "SELECT violationType, count(*) AS duplicates FROM traffic_violations GROUP BY violationType ORDER BY duplicates DESC";

$statement = $connection->prepare($sqlQuery);
$statement->execute();

$result = $statement->fetchAll();

$data = array();
foreach ($result as $row) {
    $data[] = $row;
}

if ($row->num_rows > 0) 
{
  // output data of each row
  while($row = $row->fetch_assoc()) 
  {
    echo $row["duplicates"]. "<br>";
  }
} 
else 
{
}

echo json_encode($data);
?>

Chart:

const ctx = document.getElementById('chart-test').getContext('2d');
    const myChart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: ['Speeding', 'Drifting', 'Sealtbelt', 'Wrong Parking', 'Wrong Lane Drive', 'No License'],
        datasets: [{
          label: 'Traffic Violations',
          data: [12, 19, 3, 5, 2, 3],
          backgroundColor: ['rgba(255, 99, 132)'],
          borderColor: ['rgba(255, 99, 132)'],
          borderWidth: 1
        }]
      },
      options: {
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    });

How to store REST api payload for user from frontend?

I would like to store the payload of REST API calls made by a user in frontend and be able to make the calls to recreate what the user did (like a replay button)

I have the following scenario:

User opens website.

User picks a product and configures it.

How can I store the REST API calls payload from frontend: Is there a framework that does that? Which database should I use?

How to return value from executed script with chrome.devtools.inspectedWindow.eval

I’m trying to execute some script inside webpage from devtool panel using chrome.devtools.inspectedWindow.eval, the code is working fine but can’t figure out how to return response to callback. I am grateful for your support.

Executed script

const someScript = function () {
    alert("from panel")
    return 123
    // i can't return
}

Devtool

//this regex convert function body to string
someScript.toString().replace(/^functions*S+s*([^)]*)s*{|}$/g, ""),
   function (result, isException) {
       if (isException) {
           //exception always fire
           console.log("Result not received");
       } else {
           console.log("Selected element: " + result);
       }
});

Error: Module Not Found on Discord Bot’s Command Handler

first and foremost, I’m very new to this. I’ve been following the tutorials at the Discord.js Site, with the goal being to make a discord bot for the Play by Post DnD server I’m in where everyone wants to gain experience via word count.

I mention I’m new to this because this is my first hands-on experience with Javascript, a lot of the terminology goes over my head.

So, the problem seems to be where I’ve broken away from the tutorial. It goes over command handlers, which I want to stick with because it seems to be good practice and easier to work with down the line when something most breaks (And I know it will). But the tutorial for Databases (Currency/Sequelizer) doesn’t really touch on command handlers beyond “Maintain references”.

But that’s enough foreword, the problem is in trying to get a command that checks the database for a player’s current experience points and level.

I have the relevant (seemingly) files organized with the index.js and dbObjects.js together, a models folder for the Users, and LevelUp(CurrencyShop in the tutorial) and a separate folder for the Commands like the problematic one, xpcheck.js

I can get the command to function without breaking, using the following,

const { Client, Collection, Formatters, Intents } = require('discord.js');
const { SlashCommandBuilder } = require('@discordjs/builders');
const experience = new  Collection();
const level = new Collection();

Reflect.defineProperty(experience, 'getBalance', {
    /* eslint-disable-next-line func-name-matching */
    value: function getBalance(id) {
        const user = experience.get(id);
        return user ? user.balance : 0;
    },
});

Reflect.defineProperty(level, 'getBalance', {
    /* eslint-disable-next-line func-name-matching */
    value: function getBalance(id) {
        const user = level.get(id);
        return user ? user.balance : 1;
    },
});

module.exports = {
    data: new SlashCommandBuilder()
        .setName('xpcheck')
        .setDescription('Your current Experience and Level'),
    async execute(interaction) {
        const target = interaction.options.getUser('user') ?? interaction.user;

        return interaction.reply(`${target.tag} is level ${level.getBalance(target.id)} and has ${experience.getBalance(target.id)} experience.`);;
    },
};

The problem is that the command doesn’t reference the database. It returns default values (1st level, 0 exp) every time.

I tried getting the command to reference the database, one of many attempts being this one;

const { Client, Collection, Formatters, Intents } = require('discord.js');
const { SlashCommandBuilder } = require('@discordjs/builders');
const Sequelize = require('sequelize');
const { Users, LevelUp } = require('./DiscordBot/dbObjects.js');


module.exports = {
    data: new SlashCommandBuilder()
        .setName('xpcheck')
        .setDescription('Your current Experience and Level'),
    async execute(interaction) {
        const experience = new  Collection();
        const level = new Collection();
        const target = interaction.options.getUser('user') ?? interaction.user;

        return interaction.reply(`${target.tag} is level ${level.getBalance(target.id)} and has ${experience.getBalance(target.id)} experience.`);;
    },
};

However, when I run node deploy-commands.js, it produces

Error: Cannot find module ‘./DiscordBot/dbObjects.js’

It does the same thing even if I remove the /DiscordBot, or any other way I’ve attempted to make a constant for it. I’m really uncertain what I should do to alleviate this issue, and I already know I have a lot of other hurdles to get through (like making the bot count words and award experience for word count). In my attempts to maintain motivation for learning something complicated like this- I thank you for any help, guidance, constructive criticism or advice on good practices you can provide. Thank you.

How to handle input from a textbox to not print a NaN

I am trying to get user input from the textbox and then click the button beside in order to calculate the area of a circle. Problem is alert always prints NaN.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>HTML 5 Boilerplate</title>
    <link rel="stylesheet" href="./css/style.css">
    <script>
        const PI = 3.14159;

        function getAreaOfCircle(rad) {
            let area = PI * Math.pow(rad, 2);
            alert(area);
        }
    </script>
</head>
<body>
    <input type="text" placeholder="Type something..." id="myInput">
    <input type="button" onclick="getAreaOfCircle();" value="Calculate Area of a Circle">
</body>
</html>

Perform different actions in top 3 values in Dictionary?

I have a sorted dictionary with certain number of entries:

dict = {B:3, A:2, C:2, D:1, E:0, F:0...}

After filtering the dictionary to get only the entries with top 3 largest values:

result = Object.fromEntries(Object
    .entries(dict)
    .sort(([, a], [, b]) => b - a)                         
    .filter((s => ([, v]) => s.add(v).size <= 3)(new Set))
);

The current dictionary is

{"B": 3, "A": 2, "C": 2, "D": 1}

So I am trying to add 4 to the largest values,2 to the second largest values and 1 to the third largest values, what are the ways to do this?

One of the ways I can think of is:

for (const key of Object.keys(result)) {
     // if result[key] largest
            //plus 4
     // if result[key] second largest
            //plus 2
     // else
            //plus 1 
}

Thanks for reading..

Why do Tooltips disappear when creating/destroy/creating a graph in Antv/G6

I am working with Vue 3 and antv/G6, and have an issue with tooltips disappearing when I draw a graph (with tooltips), destroy the graph, and redraw it. Here is a minimal working example. I only show the Vue code. I can provide the javascript code to manipulate the graph as well if needed. Any insights are appreciated.

<template>
  <div>
    <h2>Hello World</h2>
    <div id="mountGraph"></div>
  </div>
</template>

<script>
import * as dp from "../Composition/delayPropagationGraphImpl.js";
import G6 from "@antv/g6";
import { onMounted } from "vue";

export default {
  setup() {
    let graphCreated = false;
    let graph = false;

    const graphConfiguration = dp.setupConfiguration({
      container: "mountGraph",
      width: "800",
      height: "600",
      defaultNodeSize: 40,
    });

    function drawGraph() {
      const gNodes = [{ id: "1" }, { id: "2" }, { id: "3" }];
      const gEdges = [
        { source: "1", target: "2" },
        { source: "1", target: "3" },
      ];

      if (graphCreated) {
        graph.destroy();
      }
      graph = new G6.Graph(graphConfiguration); // ERROR
      graphCreated = true;

      const data = { nodes: gNodes, edges: gEdges };
      graph.data(data); // combines data and render
      graph.render();    
      return;
    }

    onMounted(() => {
      drawGraph();
      drawGraph();  // <<< Tooltiops disappear
    });
  },
};
</script>

replace the form with a message -not with PHP

I have this code

<!DOCTYPE html>
<html>
<body>

<p>This example demonstrates how to assign an "onsubmit" event to a form element.</p>

<p>When you submit the form, a function is triggered which alerts some text.</p>

<form action="/action_page.php" onsubmit="myFunction()">
  Enter name: <input type="text" name="fname">
  <input type="submit" value="Submit">
</form>

<script>
function myFunction() {
  alert("the message has been send");
}
</script>

</body>
</html>

I want not to do this alert message.I want to replace the form giving it this message the message has been send