Create methods inside a class to sort employees by different parameters and to filter by age

Add a JS class called Employee and create methods in it to sort employees by different parameters and to filter by age. Can someone complete this according to their understanding of problem.

class Employee{
    sortAge(){
 }
}
let employeeList = [
    {
       "id":1,
      "name": "avi",
      "salary":700000,
      "age":26
    },
    {
       "id":2,
      "name": "om",
      "salary":600000,
      "age":22
    },
    {
       "id":3,
      "name": "shubham",
      "salary":500000,
      "age":42
    },
    {
       "id":4,
      "name": "Ram",
      "salary":400000 ,
      "age":32
    }
  ]

how important is ‘unsafe-inline’ in js and css CSP

I´m developing an app and I came across with the CSP policies. I´ve already done it but I need to put the ‘unsafe inline’ and ‘unsafe eval’ in most of the pages because I have inline code or style that changes a little bit the view of the content, but it is important. No mention the responsive js that I have that changes the inline content.

My question here is: is it really necesary to change all my inline style and js, to a separate file and create a class of every little modification that I do with my inline css in order to dont use the ‘unsafe’?

I´ve being looking arround and I see that most of the pages uses inline properties, no matter how big the page is.

Thank you for your time!

Input Mask as TextField in MUI with React Hook Form

I’m trying to use the TextInput component from MUI in combination with the MaskInput component from react-input-mask and react-hook-form. Everything seems to be working fine, but I’m getting an error message in the console about using refs. I’ve tried using the useRef hook and directly selecting the second input, as well as registering the input using the useEffect hook, but the error persists. Do you have any ideas on how to fix this issue?

react-dom.development.js:86 Warning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance of InputElement2 which is inside StrictMode. Instead, add a ref directly to the element you want to reference.

import { useFormContext, Controller } from "react-hook-form";
import { Grid, TextField } from "@mui/material";
import InputMask from "react-input-mask";

const FormInputMask = ({ name, label }) => {
  const { control } = useFormContext();

  return (
    <Grid item xs={12}>
      <Controller
        control={control}
        name={name}
        defaultValue=""
        render={({ field }) => (
          <InputMask
            {...field}
            maskChar=""
            mask="999 999"
            label={label}
            variant="outlined"
            fullWidth={true}
          >
            {(inputProps) => (
              <TextField {...inputProps} />
            )}
          </InputMask>
        )}
      />
    </Grid>
  );
};

export default FormInputMask;

Is there a way to compare two mp3 file’s similarity?

I need to do(for a grad. paper) a website that can compare two mp3 files and tell how similar they are. Is there an open source examples of how to compare two mp3 files and give(let’s say a percentage) score of how similar the tracks are.

The first thought i had is to convert the files into spectrograms and compare the images, but i couldn’t find the AI to do so. Is there a way i can interact with the other website from mine? Or should I abandon the idea?

Dropping an image outside of the drop zone two times causes the image preview to disappear

I have a jquery code for drag & drop an image to upload it (later processed by ajax, but it’s not important right now). When dragging an image over the document the placeholder image changes to “drop-here” (upload-image.svg). When I drag the image and drop it inside the #output element (upload drop zone) and after that I drop (other or the same) image anywhere else on the page, the preview image in the #output comes back to the image I’ve set the first time. The problem is when I drop an image outside of the #output element for the second time in a row. The preview of the uploaded image is replaced with alt text and I get an error in the console: GET blob:http://localhost/12334d1d-41a2-4d48-9da0-b6bb35a35d38 net::ERR_FILE_NOT_FOUND
I think it will be more clear with my code:

<input type="file" style="display:none;" id="upload_image" name="image" accept="image/png, image/jpeg" onchange="loadFile(event)" class="required2">

<div class="form-s1-right">
    <img id="output" src="Images/placeholder-image.svg" alt="Uploaded Image">
<script>
var currentFile = null;
var loadFile = function(event){
    var output = document.getElementById('output');
    if (event.target.files[0]) {
        currentFile = event.target.files[0];
    }
    if (currentFile){
        output.src = URL.createObjectURL(currentFile);
        output.onload = function(){
            URL.revokeObjectURL(output.src);
        }
    }
};
</script>
</div>

And the code for the drag & drop:

let imageSrc = null;
$(document).on('dragenter', function(e){

    const items = e.originalEvent.dataTransfer.items;
    for (let img = 0; img < items.length; img++){
        let type = items[img].type;
        if (type === "image/png" || type === "image/jpeg"){

            var dropZone = $('#output');

            dropZone.on('dragover', handleDragOver);
            dropZone.on('drop', handleFileSelect);

            function handleDragOver(e){
                e.stopPropagation();
                e.preventDefault();
                e.originalEvent.dataTransfer.dropEffect = 'copy';
            }

            function handleFileSelect(e){
                e.stopPropagation();
                e.preventDefault();

                var files = e.originalEvent.dataTransfer.files;
                imageSrc = URL.createObjectURL(files[0]);
                let type = files[0].type;
                if (type === "image/png" || type === "image/jpeg"){
                    $('#upload_image').prop('files', files);
                    var output = document.getElementById('output');

                    output.src = URL.createObjectURL(files[0]);

                    output.onload = function(){
                        URL.revokeObjectURL(output.src);
                    }

                    // Remove the event listeners - without it you can drop png or jpg and later drop not accepted file (gif, txt) and it will be accepted
                    dropZone.off('dragover', handleDragOver);
                    dropZone.off('drop', handleFileSelect);
                }
            }

        }
    }

});
    // When dropping the image outside of the #output replace the image to placeholder
    $(document).on('drop', function(e){
        console.log(imageSrc);
        e.preventDefault(); // Stop the file from opening in the other tab when dropping outside of #output
        if (imageSrc != null){
            console.log("defined")
            if ($("#output").attr("src") === "Images/placeholder-image.svg" || $("#output").attr("src") === "Images/upload-image.svg"){
                $("#output").attr("src", imageSrc);
            }
        } else {
            console.log("undefined")
            if ($("#output").attr("src") === "Images/placeholder-image.svg" || $("#output").attr("src") === "Images/upload-image.svg"){
                $("#output").attr("src", "Images/placeholder-image.svg");
            }
        }
    });

    // Replace the image to upload when dragging over the window (if png or jpg)
    var isDraggingOver = false;
    var dragTimer;

    function dragOver(e){
        e.preventDefault();
        let items = e.originalEvent.dataTransfer.items;

        for (let img = 0; img < items.length; img++){
            const type = items[img].type;
            if (type === "image/png" || type === "image/jpeg"){
                isDraggingOver = true;
                $("#output").attr("src", "Images/upload-image.svg");
                clearTimeout(dragTimer);
            }
        }
    }
    $(document).on('dragover', function(e){
        dragOver(e);
    });
    $("#output").on('dragover', function(e){
        dragOver(e);
    });

    $(document).on('dragleave', function(e) {
        e.preventDefault();
        let items = e.originalEvent.dataTransfer.items;

        for (let img = 0; img < items.length; img++){
            const type = items[img].type;
            if (type === "image/png" || type === "image/jpeg"){
                clearTimeout(dragTimer);
                dragTimer = setTimeout(function(){
                    isDraggingOver = false;
                    $("#output").attr("src", "Images/placeholder-image.svg");
                }, 20);
            }
        }
    });

Sorry for the amount of code, but I don’t think I can show less for you to be able to understand how it works. How can I fix the issue?

How get back my original androidsystem and settings

I got hacked and my Phone is under controll. I cannot admin this Phone. And ive seen permissioncontroll and much more in hidden apps. This is a Android galaxy s22.
Pleeeease help me detect phonecontroller/host and get back my system.opp

Ive tried gihub for answers and searched all over Google. Androids hidden apps, ive found out.
Need to know who is my admin and permission controller??remotecontroller.??

Js Progess bar, additinal functions required

I have this progress Bar that I am trying to add some control elements too. I have done some and removed them to keep understanding clear. It is a useful bar for all newbees to learn and understand and also apply in their work.

The progress bar works, when the click me button below is clicked it will start the progress bar and it wil stop on 100%.
The intended use will be with an Ajax call, when data is returned by the ajax call it will click (button B), but let me keep things to the point for understanding and newbies sake. Thank you all for your help.

Additional Functions required to the progress bar please, your help appreciated.

  1. When the bar reaches between 70% and 90% please slow it down to setInterval(frame, 300);

  2. When the progress bar reaches 90% stop it, wait 30seconds, click button B below) and show a custom time out message in the div below.

  3. Create another button (button B) that fills the progress bar to 100% when clicked and resets the progress bar to empty. (ending the progress wait and also when data is returned from a ajax call.)

The code:

<html>
<style>
#myProgress {
  width: 100%;
  background-color: #ddd;
}

#myBar {
  width: 1%;
  height: 30px;
  background-color: #04AA6D;
}
</style>
<body>

<h1>JavaScript Progress Bar</h1>

<div id="myProgress">
  <div id="myBar"></div>
</div>

<div> time out messages</div> - Time out message here after 30sec

<button> Button B </button>.  - When clicked the button Fills in 100%  and resets it

<br>
<button onclick="move()">Click Me</button> 

<script>
var i = 0;
function move() {
  if (i == 0) {
    i = 1;
    var elem = document.getElementById("myBar");
    var width = 1;
    var id = setInterval(frame, 10);
    function frame() {
      if (width >= 100) {
        clearInterval(id);
        i = 0;
      } else {
        width++;
        elem.style.width = width + "%";
      }
    }
  }
}
</script>

</body>
</html>  ```





How to deal with nested lists ( and tags ) using Vuetify?

Given the following sample nested list using plain HTML

<ul>
  <li>Fruit
    <ul>
      <li>Bananas</li>
      <li>Apples
        <ul>
          <li>Green</li>
          <li>Red</li>
        </ul>
      </li>
      <li>Pears</li>
    </ul>
  </li>
  <li>Vegetables</li>
  <li>Meat</li>
</ul>

I want to use this approach in my Vuetify app since v-treeview is not supported in v3 ( yet ). When copying the HTML code I get this result ( reproduction link )

enter image description here

The bullet points are missing. When wrapping the root <ul> tag inside a <v-container> I get this result

enter image description here

so still margins are missing. What is a common way to deal with nested lists when using Vuetify? I would like to achieve the same result like using plain HTML

Getting data from axios using eventListeners and having no response

I’m trying to make a get request from an api using axios + eventListeners because I only want the data to be loaded on my screen AFTER I click on an especific button. Everything was working out fine before I tried to add the eventListener logic, now I simply don’t get aby results from the api (plus, no errors are shown in the console).
this is my code:

const[game,setGame]= React.useState([]);
    
    React.useEffect(()=>{
            axios.get("http://localhost:8080/games/1").then((response)=>{
            setGame(response.data);
            });
    }, []);
    if (!game) return null;
    
    window.onload=function(){
        let button = document.getElementById("button");
        button.addEventListener('click', ()=>{
            game.map((game, index) => {
                return(
                    <>
                        <p className="n1">{game}</p>
                    </>
                )
            });
        })
    }

and, on the same page, this is the code for the button that I’m trying to make it work:

<a href="#" className="button" id="button" >
     <p className="bttn-p" >GERAR NÚMEROS</p>
</a>

This is my first time using eventListeners and I’m actually kind of new at react so if anyone knows anything that could help I’d be extremely grateful 😀

How do i find the error with the import and export statements?

Ive hit a bit of a wall with this. It is a Codecademy project “flashcards”. I am assuming that the reducers are either not importing or exporting. I have checked the syntax and even gone through the solution given but still having an issue with these three errors.

If someone could point me in the right direction that would be great

ERROR in ./src/app/store.js 6:0-56
Module not found: Error: Can’t resolve ‘../features/cards/cardsSlice’ in ‘/Users/matt/Projects/flashcards-starter/src/app’

ERROR in ./src/components/NewQuizForm.js 12:0-55
Module not found: Error: Can’t resolve ‘../features/cards/cardsSlice’ in ‘/Users/matt/Projects/flashcards-starter/src/components’

ERROR in ./src/features/cards/Card.js 8:0-43
Module not found: Error: Can’t resolve ‘./cardsSlice’ in ‘/Users/matt/Projects/flashcards-starter/src/features/cards’

webpack compiled with 3 errors and 1 warning

App.js

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  NavLink,
  useRouteMatch,
} from "react-router-dom";
import NewQuizForm from "../components/NewQuizForm";
import NewTopicForm from "../components/NewTopicForm";
import Topics from "../features/topics/Topics";
import Topic from "../features/topics/Topic";
import Quiz from "../features/quizzes/Quiz";
import Quizzes from "../features/quizzes/Quizzes";
import ROUTES from "./routes";

export default function App() {
  return (
    <Router>
      <nav>
        <ul>
          <li>
            <NavLink to={ROUTES.topicsRoute()} activeClassName="active">
              Topics
            </NavLink>
          </li>
          <li>
            <NavLink to={ROUTES.quizzesRoute()} activeClassName="active">
              Quizzes
            </NavLink>
          </li>
          <li>
            <NavLink to={ROUTES.newQuizRoute()} activeClassName="active">
              New Quiz
            </NavLink>
          </li>
        </ul>
      </nav>

      <Switch>
        <Route path="/topics">
          <TopicsRoutes />
        </Route>
        <Route path="/quizzes">
          <QuizRoutes />
        </Route>
      </Switch>
    </Router>
  );
}

function TopicsRoutes() {
  let match = useRouteMatch();

  return (
    <>
      <Switch>
        <Route path={`${match.path}/new`}>
          <NewTopicForm />
        </Route>
        <Route path={`${match.path}/:topicId`}>
          <Topic />
        </Route>
        <Route path={`${match.path}`}>
          <Topics />
        </Route>
      </Switch>
    </>
  );
}

function QuizRoutes() {
  let match = useRouteMatch();

  return (
    <>
      <Switch>
        <Route path={`${match.path}/new`}>
          <NewQuizForm />
        </Route>
        <Route path={`${match.path}/:quizId`}>
          <Quiz />
        </Route>
        <Route path={`${match.path}`}>
          <Quizzes />
        </Route>
      </Switch>
    </>
  );
}

store.js

import { configureStore } from "@reduxjs/toolkit";
import topicsReducer from '../features/topics/topicsSlice';
import quizzesReducer from '../features/quizzes/quizzesSlice';
import cardsReducer from '../features/cards/cardsSlice';

export default configureStore({
  reducer: {
    topics: topicsReducer,
    quizzes: quizzesReducer,
    cards: cardsReducer
  },
});

newQuizForm.js

import React, { useState } from "react";
import { useHistory } from "react-router-dom";
import { v4 as uuidv4 } from "uuid";
import ROUTES from "../app/routes";
import { useSelector, useDispatch } from 'react-redux';
import { selectTopics } from '../features/topics/topicsSlice';
import { addQuizThunk } from '../features/quizzes/quizzesSlice';
import { addCard } from '../features/cards/cardsSlice';

export default function NewQuizForm() {
  const [name, setName] = useState("");
  const [cards, setCards] = useState([]);
  const [topicId, setTopicId] = useState("");
  const history = useHistory();
  const topics = useSelector(selectTopics);
  const dispatch = useDispatch();

  const handleSubmit = (e) => {
    e.preventDefault();
    if (name.length === 0) {
      return;
    }

    const cardIds = [];

    cards.map((card, index)=>{
      const uniqueId = uuidv4();
      cardIds.push(uniqueId);
        dispatch(addCard({
          id: uniqueId,
          front: cards[index].front,
          back: cards[index].back

        }))
    });


    dispatch(addQuizThunk({
      id: uuidv4(),
      name: name,
      topicId: topicId,
      cardIds: cardIds
    }));

    history.push(ROUTES.quizzesRoute());
  };

  const addCardInputs = (e) => {
    e.preventDefault();
    setCards(cards.concat({ front: "", back: "" }));
  };

  const removeCard = (e, index) => {
    e.preventDefault();
    setCards(cards.filter((card, i) => index !== i));
  };

  const updateCardState = (index, side, value) => {
    const newCards = cards.slice();
    newCards[index][side] = value;
    setCards(newCards);
  };

  return (
    <section>
      <h1>Create a new quiz</h1>
      <form onSubmit={handleSubmit}>
        <input
          id="quiz-name"
          value={name}
          onChange={(e) => setName(e.currentTarget.value)}
          placeholder="Quiz Title"
        />
        <select
          id="quiz-topic"
          onChange={(e) => setTopicId(e.currentTarget.value)}
          placeholder="Topic"
        >
          <option value="">Topic</option>
          {Object.values(topics).map((topic) => (
            <option key={topic.id} value={topic.id}>
              {topic.name}
            </option>
          ))}
        </select>
        {cards.map((card, index) => (
          <div key={index} className="card-front-back">
            <input
              id={`card-front-${index}`}
              value={cards[index].front}
              onChange={(e) =>
                updateCardState(index, "front", e.currentTarget.value)
              }
              placeholder="Front"
            />

            <input
              id={`card-back-${index}`}
              value={cards[index].back}
              onChange={(e) =>
                updateCardState(index, "back", e.currentTarget.value)
              }
              placeholder="Back"
            />

            <button
              onClick={(e) => removeCard(e, index)}
              className="remove-card-button"
            >
              Remove Card
            </button>
          </div>
        ))}
        <div className="actions-container">
          <button onClick={addCardInputs}>Add a Card</button>
          <button>Create Quiz</button>
        </div>
      </form>
    </section>
  );
}

cardSlice.js

import { createSlice } from '@reduxjs/toolkit';

export const cardsSlice = createSlice({
    name: 'cards',
    initialState: {
        cards: {}
    },
    reducers: {
        addCard: (state, action) => {
            const newCard = { 
                id: action.payload.id, 
                front: action.payload.front, 
                back: action.payload.back
            };
            state.cards[action.payload.id] = newCard;
        }
    }
})

export const selectCards = state => state.cards.cards;
export const { addCard } = cardsSlice.actions;
export default cardsSlice.reducer;

Card.js

import React, { useState } from "react";
import { Link, useParams } from "react-router-dom";
import { useSelector } from 'react-redux';
import { selectCards } from './cardsSlice';

export default function Card({ id }) {
  const cards = useSelector(selectCards); 
  const card = cards[id];
  const [flipped, setFlipped] = useState(false);

  return (
    <li>
      <button className="card" onClick={(e) => setFlipped(!flipped)}>
        {flipped ? card.back : card.front}
      </button>
    </li>
  );
}

I did find a suggestion to say that it could be to do with the Node modules, but no further info was given.

TypeError: Class extends value undefined is not a constructor or null when trying to create an embed using discord.js v14.7.1

The specific problem part is
**module.exports = class HelpCommand extends Command {**

The entire help.js file is (excluding urls and stuff):

const fs = require('fs');
const { Command } = require('discord.js');
const { MessageEmbed } = require('discord.js');
 
module.exports = class HelpCommand extends Command {
  constructor() {
    super('help', {
      description: 'List all available commands.',
    });
  }
 
  async exec(message) {
    const help = new MessageEmbed()
      .setColor('#F8F7D8')
      .setTitle('TITLE')
      .setURL('URL')
      .setAuthor({
        name: 'NAME',
        iconURL: 'URL',
        url: 'URL',
      })
      .setDescription('Commands for NAME')
      .setThumbnail('URL')
      .addFields(
        { name: '/play', value: 'Used to play the music' },
        { name: 'u200B', value: 'u200B' },
        { name: '/pause', value: 'Used to pause the music', inline: true },
        { name: '/mp3', value: 'Used to convert a youtube link to an mp3', inline: true },
        { name: '/skip', value: 'Used to skip the music', inline: true }
      )
      .setImage('URL')
      .setTimestamp()
      .setFooter({
        text: 'NAME',
        iconURL: 'URL',
      });
 
    await message.channel.send({ embed: help });
  }
};

I tried changing it around but i’m new to coding and don’t know what i’m doing. I’m using discord.js v14.7.1 and have been trying to convert my code into an embed. The code is a slash command and will send the embed when the user sends /help.

How to call an async function inside an if statement?

To keep variables in background.js in chrome extension I need to reinitiate some global variables, and I meet some difficulties.

Here is the code(fiddle) that I want to illustrate the problem:

var temp = null; 

function someTimeConsumingThing() {
  return new Promise(function(resolve,reject) {
    setTimeout(resolve, 2000);
    temp = 10;
  })
}

async function a(){
  if(temp==null){
    await someTimeConsumingThing();
  }
  return temp
}

function b(){
  let localTemp = a();
  console.log(localTemp);
}

b();

In the above code snippet, the temp variable would sometimes be null and to ensure that temp is not null I should call an async function someTimeConsumingThing. As we can see, the console.log outputs a Promise rather than 10; and an error would occur if I add await before a():

Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules”

How can I tackle this problem? I have read many related but unhelpful answers here and I don’t know how to optimize my search input to get the most related question. This problem would be very naive for JS experts and there are certainly available answers on this site.

I want to deact scroll and show component when user scrolled to top in react native

When the user scroll to the top and then scrolls event returns a higher number like – 10 or 20 or 2000 or 300 based on the content and when the user scrolled to the button then it will return 0

  const [scrolledRecord, setScrolledRecord] = useState(false);
  const scrolledEvent = scroll => {
    if (scroll?.contentOffset?.y > 0) {
      setScrolledRecord(true);
    } else {
      setScrolledRecord(false);
    }
  };
return   {scrolledRecord ? <ChatHeader item={userData} /> : null}

In the about I have implemented the logic I think i am not correct

Wrapping class in Proxy object TS

I am trying to write a function that accepts an API interface (I’ve created a sample here), and wraps a Proxy around it, so that any calls to the that API’s methods get intercepted, and I can do some logging, custom error handling etc. I am having a terrible time with the types. This is similar to another question I have asked (Writing wrapper to third party class methods in TS), but uses a completely different approach than that one, based on some feedback I got.

Currently I am getting
Element implicitly has an 'any' type because expression of type 'string | symbol' can't be used to index type 'API'. No index signature with a parameter of type 'string' was found on type 'API'. which makes sense given that sayHello is not strictly a string as far as typescript is concerned, but I do not know the best way to be able to get methods on this class without uses the property accessor notation.

class API {
 sayHello(name: string) {
    console.log("hello" + name)
  }
}

export default <T extends API>(
  api: T,
) =>
  new Proxy(api, {
    get(target, prop) {
      if (typeof target[prop] !== "function") { // type error here with "prop"
        return target[prop]; // and here
      }
      return async (...args: Parameters<typeof target[prop]>) => {

        try {
          const res = await target[prop](...args); // and here
          // do stuff
          return res.data;
        } catch (e) {
          // do other stuff
        }
      };
    },
  });

Is this possible in TS?