Catching as many errors and warnings from browser console via JS to send back to stat server

So I work with some devs that don’t track errors and I want to be able to make an easy to use way to log all the errors and issues on the client side to be sent back to the server for analysis.

So far I have over ridden console.log to look for key words like Error or Invalid and also logs the current URL and time the error was detected on but is there a better way to record problems to be sent back to me for analysis?

I was thinking of making a little lib that devs could import and has a few decorator functions and hooks to help track bugs.

Any libraries/toolkits or standard methods/practises I could use?

Thanks.

So I’m getting a syntax error. I followed the tutorial and I still dont see why im getting an error. btw im a begginer [closed]

I am trying to hack my crushes instagram and I get this thing off github….
Why is it not working? I made it myself btw. Please help me I don’t know what error I made.

# MADE BY HACKERSMAN - #

def HACKWOMAN(attack, attack):

  print("start hack)
def siper hack():
  import DDOS
  impport hack
  ddosplus hack === hack.hack(user("CharlieDefina_9"))
  DDOS.user(ddosplus hack)

HACKWOMAN(1,1)
siper hack()

Creating a loop using setTimeout up to the minute, then every five minutes

I would like to check the minute, until I get to :00, :05, :10, etc minutes, then set to 5 minutes (on the minute) and continue on during the application. Is there a better way to do this? Do I need a clearTimeout? Please help and thanks!

Goal: Check the minute, once on 00

// Set to 1 minute initially.
let interval = 60000;

function timeCheck() {
  const date = getNow();
  console.log("checking...", `${dayjs(date).hour()}:${dayjs(date).minute()}:${dayjs(date).second()}`);
  // Check browser time in minutes for 00, 05, 10, 15, 20, etc.
  if (dayjs(date).minute() % 5 === 0) {
    // Set to 5 minute.
    interval = 300000;
    ...
  }
  setTimeout(timeCheck, interval);
}

clearTimeout(timeCheck);
timeCheck();

node project bundled with webpack is not working correctly

I have to node project that can be compiled: client.js and server.js
I want to have to separate bundled file e.g. client.bundle.js and server.bundle.js
This is my webpack config:
const path = require(‘path’);

module.exports = {
    target: 'node',
    entry: {
        server:'./server.js',
        client:'./client.js'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].bundle.js'
    },
};

server.bundle.js is working fine but client.bundle.js is logging multiple chars and finally throws an error.
enter image description here

server.js has imported following module:

const FtpSrv = require('ftp-srv');

client.js has imported following module:

const ftp = require("basic-ftp")
const express = require("express");
const path = require('path')
const app = express();

const formidable = require('formidable');
const client = new ftp.Client()

What is the best way to realize high precision arithmetic calculations in JavaScript?

I’m doing an algorithm that checks if a number is prime for college, but I came across a connotation and calculation problem where I need to consider large numbers.

One of them was solved with the support of BigInt(), however in arithmetic calculations from a certain number of decimal places it ends up losing precision and consequently returning false true.

For example, multiplying 2 numbers ending in 1,3,7,9 always results in a number ending in 1,3,7,9, but from 3**34 onwards the calculations start to lose precision.

Is there any efficient way to solve this problem in JavaScript?

Having trouble trying to get my bot to schedule a message. There are no errors, I am just not getting the desired output

I am trying to create a discord bot where you can schedule a message to be sent at a certain time. I have got my bot to work all the way until the bot ask “Please send the message you would like to schedule”. Once the bot ask that and the user does not respond, the bot does not do anything after that. I suspect the code is not sending the information to the mongodb database or the collector is not actually collecting anything, however I do not know why. Can someone please tell me what could be going wrong, I appreciate the help

const momentTimezone = require('moment-timezone')
const { MessageCollector } = require('discord.js')
const scheduledSchema = require('../models/scheduled-schema')
module.exports = {
    requiredPermissions: ['ADMINISTRATOR'],
    expectedArgs: '<Channel tag> <YYYY/MM/DD> <HH:MM><"AM" or "PM"> <Timezone>',
    minArgs: 5,
    maxArgs: 5,
    init: () => {},
    callback: async({message, args}) => {
        const { mentions, guild, channel } = message
        
        const targetChannel = mentions.channels.first()
        if(!targetChannel){
            message.reply('Please tag a channel to send your message in.')
            return
        }
            args.shift()
            
            const[date, time, clockType, timeZone] = args
            
            if (clockType !== 'AM' && clockType !== 'PM'){
                message.reply(`You must provide either "AM" or "PM", you provided "${clockType}"`)
                return
            }
            const validTimeZones = momentTimezone.tz.names()
            if(!validTimeZones.includes(timeZone)){
                message.reply('Unknown timezone!')
                return
            }
            const targetDate = momentTimezone.tz(
                `${date} ${time} ${clockType}`,
                'YYYY-MM-DD HH:mm A',
                timeZone
            )
            message.reply('Please send the message you would like to schedule')
            const filter = (newMessage) => {
                return newMessage.author.id == message.author.id
            }
            const collector = new MessageCollector(channel, filter, {
                max: 1,
                time: 1000 * 60 // 60 seconds
            })
           
            collector.on('collect', async  (collected) => {
                const collectedMessage = collected.first()
                message.reply(collected.first())
                if(!collectedMessage){
                    message.reply('You did not reply in time.')
                    return
                }
                message.reply('Your message has been scheduled.')
                
                await new scheduledSchema({
                    
                    date: targetDate.valueOf(),
                    content: collectedMessage.content,
                    guildId: guild.id,
                    channelId: targetChannel.id,
                    
                }).save()
            
            
            })
            
            },
           
        }

Keep getter function in sync with an object’s current state in React/TypeScript

WHAT I HAVE

I have a Parent class and a Child class.

export class Parent {
    properties: { x: any };
    child: Child;
    constructor() {
        this.properties = {
            x: 1
        }
        this.child = new Child(this.getX);
    }
    getX = () => {
        return this.properties.x;
    }
}

class Child {
    parent_getX:()=>string
    constructor(parent_getX:()=>string){
        this.parent_getX = parent_getX;
    }
}

The Parent class has:

  • a field called properties which stores an int value called x.
  • a function called getX() which simply pulls the value of x from within the properties object.
  • a field called child which holds a reference to a Child object.

The Child class only receives a reference to the Parent‘s getX() function.

WHAT I WANT

My goal is to be able to update the value of x and that everytime I call child.parent_getX() or parent.getX() I get the latest value of x.

WHAT I’M SEEING

I have a React component called Example that takes a Parent object with a an x value of 1 as initial state.

Whenever I increment this value using setState(...) the value of x is incremented but for some reason, parent.getX() and parent.child.parent_getX() always keeps returning the initial value of x. What can I do to keep the function in sync with the parent object?

export const Example = () => {

    const [parent, setParent] = useState(new Parent());

    const incrementX = ()=>{
        let newParent = { ...parent, properties: { ...parent.properties, x: parent.properties.x + 1 } }
        setParent(newParent);
    }

    return (<>
        <p>
            Parent.getX() = {parent.getX()}
            <br/>
            Parent.child.parent_getX() = {parent.child.parent_getX()}
        </p>
        <button onClick={incrementX}>
            Increment
        </button>
    </>);
}

Why’s .closest() removing the entire table when I only want it to remove the specific row?

I’ve been stuck on this for hours and can’t figure out what’s wrong.

I’m trying to only remove the row (the entire <tr></tr>) that the user wants remove. The check the checkbox followed by clicking Delete.

My jquery code below removes the entire table rather than the row the user wants removed when clicking Delete.

How can I make it so that the user removes only the row they want to remove? Thanks in advance!

My jquery code is inside a giant $document.on('click')....

Here’s my table:

<tr>
    <td><input type="checkbox" class="question-manager-id" value="7052"></td>
    <td>7052</td>
    <td class="anchor-looking-no-bottom edit-question" data-url="http://localhost.test/games/7052">Some data</td>
    <td>Text</td>
    <td>Math</td>
    <td>20</td>
    <td>math vocab</td>

    <td>
       <label class="switch">
         <input type="checkbox" data-id="7052" class="question-manager-enabled-toggle" checked="">
         <span class="toggle-slider round"></span>
      </label>                        
    </td>

    <td>
      <button class="button small delete-question alert" data-id="7052">Delete</button>
    </td>
</tr>

Here’s my jquery (I’ve added questionId variable in case I could somehow use it to only remove the user’s chosen row):

let questionId = $('.question-manager-id:checked').val(); // returns 7052
$('button.delete-question').parents('tr').remove();

HTML/JS recursion issue [duplicate]

Attempting to make a countdown clock where the user puts in the name of the event and the date and the function writes to the document that clock with the name of the event. I can get it to run once with the information but not continually update. I’ve kept it in the same file as the GET method seemed to cause some problems. This was to essentialize this issue. I’ve tried both setInterval and setTimeout.


<!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>Event Countdown Form</title>
    <link rel="stylesheet" href="style.css">
  </head>
  
  <body>
    
    <form>
      <br>
      <label for="name"></label>
      <br>
      <input type="text" id="name" name="name">
      <br><br>
      <label for="date"></label>
      <br>
      <input type="date" id="date" name="date">
      <br><br>
      <button onClick="countdown()">Submit</button>
    </form>
    
    <script>
      function countdown () {
        const newName = document.getElementById("name").value;
        const newDate = document.getElementById("date").value;
        
        const birthday = new Date(newDate);

      //initializing the values of days, hours, minutes, seconds in milliseconds
      const second = 1000;
      const minute = second * 60;
      const hour = minute * 60;
      const day = hour * 24;
      
      //calculating time left to the event
      const today = new Date();
      const timespan = birthday - today;
      const days = Math.floor(timespan / day);
      const hours = Math.floor((timespan % day) / hour);
      const minutes = Math.floor((timespan % hour) / minute);
      const seconds = Math.floor((timespan % minute) / second);
      
      //if it is the day of the event
      if (timespan <= 0 && timespan > -day) {
        document.write(
          `
            <div>
                <h1>HAPPY ${newName.toUpperCase()}!!!</h1>
              </div>
          `
          );
        return;
      }
      
      //write to the document
      document.write(
          `
          <div>
            <ul>
              <li>There are</li>
              <li>${days} days</li>
              <li>${hours} hours</li>
              <li>${minutes} minutes</li>
              <li>${seconds} seconds</li>
              <li>until your ${newName}</li>
            </ul>
          </div>
          `
          );
          
        //run countdown function every second   
        setTimeout(countdown, 1000);
}
        
    </script>
    
  </body>
  
</html>

How to append a new item without re-rendering the items that were already there

I’m using Ajax to consume a simple API that lists all my tasks and I can add new items to the list. The problem is that everytime I append a new item to the ul the others all items “disappear” quickly, practically blinking. I just want to append the new item in the end of the ul without needing to re-render all items so the previous things listed won’t blink.

My html:

<h1>All tasks</h1>
    <ul id="items">
    </ul>
    
    <form method="POST">
        <label for="title">Insert a new task</label>
        <input type="text" name="title">
        <button type="submit" id="submit">Submit</button>
    </form>

My JS:

$.ajax({
    url: "http://localhost:4000/todo",
    contentType: "application/json",
    dataType: 'json',
    success: function(result){
        for(let i = 0; i < result.list.length; i++){
            $('#items').append(`<li>${result.list[i].title}</li>`);
        }
    },
    error: function(result){
        console.log('Error');
    }
});


$("#submit").click(function() {
    $.post("http://localhost:4000/todo", {
        title : $('input[name="title"]').val()
    }, function(){
        $('#items').append('<li>' + $('input[name="title"]').val() + '</li>');
    });

}); 

How to keep a reference to component created within a loop?

I’m learning Svelte and I’m trying to make a component (a color palette). I blindly went for a solution where each ColorSelector (the color div you click on) is a Svelte component. (I’d gladly take an example where no child components are used)

I export a selected property in the ColorSelector.svelte component file. I’d like to set that property to false on every ColorSelectors instantiated when one of them is clicked except on the one that has been clicked.

However, I’m struggling to find how to keep a reference to an instantiated component in a loop. How can I achieve this?

<script lang="ts">
  import { Colors, Color } from "./modules/colors";
  import ColorSelector from "./ColorSelector.svelte";

  const DEFAULT_COLOR = Colors.LIGHT_WHITE;
  let selectedColor:Color = DEFAULT_COLOR;

function handleClick(event, i) {
  selectedColor = event.detail.color;
  // When clicked set ColorSelector.selected = false on evert ColorSelectors 
  // except the one that has been clicked
}
</script>

<div>
  {#each Object.values(Colors) as color, i}
    <ColorSelector on:selected={handleSelect} color={color}></ColorSelector>
  {/each}
</div>

<style>
  div {
    display: flex;
  }
</style>

How to refer a interface that’s used before it was defined?

I am defining TypeScript interfaces and landed in a situation where I need to define circular interface.

Eg. ISchool have IStudent and IStudent have ISchool, the problem is interface ISchool {} has IStudent which is used before it’s defined. Also, I can’t define interface IStudent before because IStudent has ISchool. How can handle this situation?

interface ISchool {
  id: string;
  name: string;
  students: IStudent[];
}

interface IStudent {
  id: string;
  name: string;
  school: ISchool;
}

Does this code accurately determine if a binary search tree is balanced?

I know I could just look at some examples but I spent a long time trying to get this myself and I’d like to know if I was successful. It passes the tests I gave it, but can I get a sanity check on the code?

Each node is a javascript class with a left & right property that equals either another node or undefined. I also wrote a .hasChildren() method for the Node class which does what it sounds like.

This function is a method of my BinaryTree class, which has another method .height() that takes any node and determines the height of the tree starting with that node. Here is the .isBalanced() method, which also takes a node to start with:

BinaryTree.prototype.isBalanced = function (node = this.root) {
    const rBalanced = (node) => {
    // a node with no children is balanced
    if (!node.hasChildren()) {
      return true
    }

    // get the difference in heights between the branches, using -1 for a missing child
    const left = node.left ? this.height(node.left) : -1
    const right = node.right ? this.height(node.right) : -1

    // if the difference is 1 or less, this node is balanced
    const balanced = Math.abs(left - right) <= 1

    // ensure that every child tree, if it exists, is also balanced
    if (node.left && !node.right) {
      return balanced && rBalanced(node.left)
    }
    if (!node.left && node.right) {
      return balanced && rBalanced(node.right)
    }
    return balanced && rBalanced(node.left) && rBalanced(node.right)
    }
  // a nonexistent tree is balanced (???)
  return node ? rBalanced(node) : true
}

And here is the .height() method just in case:

BinaryTree.prototype.height = function (node = this.root) {
    const rHeight = (node, count) => {
        return Math.max(
            count,
            node.left ? rHeight(node.left, count + 1) : null,
            node.right ? rHeight(node.right, count + 1) : null
        )
    }
    return node ? rHeight(node, 1) : 0
}