IE doesn’t detect Prt Scn key’s keyup event (keyCode: 44) before other keyup event fire

Here’s my code

$(document).on("keyup", function(e) {
    console.log(e.key);
    if (e.key == "PrintScreen") {
        e.preventDefault();
        clearClipBoard();
    }
})

function clearClipBoard() {
    if (navigator.clipboard) { // Chrome or Edge
        navigator.clipboard.writeText(""); 
    }
    else if (window.clipboardData) { // Internet Explorer
        window.clipboardData.setData("Text", "");
    }
}

When the page loaded first time, or blur and focus back again, the keyup event of PrintScreen cannot be detected. But if I press other key first and then press the Prt Scn key, it can be detected successfully.

I’ve tried to trigger a keyup event of other key when the page focus back, but the Prt Scn key still cannot be detected.

$(window).on("focus", function() {
    $.alert("focus");
    let e = $.Event('keyup');
    e.key = 'a'; 
    $("body").trigger(e);
})

I found someome has the same question but no answer.
IE 11 Print screen issue

Any one have any ideas what might be causing this issue?

How can I change the color of MUI styled component?

I have a MUI styled component that renders a green circular badge.

const StyledGreenBadge = styled(Badge)(({ theme }) => ({
    '& .MuiBadge-badge': {
      backgroundColor: '#44b700',
      color: '#44b700',
      width: '15px',
      height: '15px',
      borderRadius: '100%',
      boxShadow: `0 0 0 2px ${theme.palette.background.paper}`,
      '&::after': {
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        borderRadius: '50%',
        animation: 'ripple 1.2s infinite ease-in-out',
        border: '1px solid currentColor',
        content: '""',
      },
    },
    '@keyframes ripple': {
      '0%': {
        transform: 'scale(.8)',
        opacity: 1,
      },
      '100%': {
        transform: 'scale(2.4)',
        opacity: 0,
      },
    },
  }));

Now, I want my code to be DRY, so I want to create a StyledYellowBadge.

All I have to do is somehow just change the color property of StyledGreenBadge.

Yet, I could not figure out how for 3 hours.

I have tried something like this:

color: { desiredColor === 'yellow' ? 'yellow' : #44b700'},

where desiredColor is a second argument, after

{ theme }

How can I make achieve this?

Why I got “,” in my JS Set when use Union method. Although I don’t let “,” in my any set [duplicate]

I write this code:

let set1 = new Set([1,2,3,4,5])
console.log(...set1)
let set2 = new Set([2,3,4,5,6,7,8,9,10])
console.log(...set2)
//I wanna make this two get union together
const union = new Set(([...set1]+[...set2]))
 console.log(...union)
//I got in log : 1 , 2 3 4 5 6 7 8 9 0

I don’t know why “,” is in my union set.
and I just want “1 2 3 4 5 6 7 8 9 10” in my console.log(…union) but I don’t know how to do that.
Ps : Sorry for my confusing English.

Can we take python code as input in browser and return the output?

I tried some ways but I cannot figure out a way if we can take input (Python Code) in browser (JS) and run the code and return the output online without creating an online compiler?
I tried hitting some online interpreters urls with the code but it does not work.

I was wondering if I take input and can run it in my personal IDE/Editor and return the output online.

Is there any way or tool to make this possible?

How do I make a button to switch between two functions that populate the DOM?

I am trying to fix the forEach loop in the populateRepsDiv and It keeps giving me a cannot read properties of undefined reading ‘forEach’ error. I am ultimately trying to get a button to switch between showing the senators or the Representatives but I am having a lot of trouble… Should I just have one function for populating the DOM and have a button switch what array to show or should I have to functions to populate the DOM?

import { senators } from "../data/senators.js";
import { representatives } from "../data/representatives.js"


const allCongressMembers = [...senators, ...representatives]

const senatorDiv = document.querySelector('.senatorsDiv')
const seniorityHead = document.querySelector('.seniority')
const loyaltyList = document.querySelector('.loyaltyList')
const vacationerList = document.querySelector('.vacationerList')
const senatorButton = document.createElement('button')

senatorButton.textContent = 'Switch'
senatorButton.addEventListener('click',function (){
  populateSenatorDiv(simpleSenators)})

function simplifiedReps() {
  return representatives.map(representative => {
    const rmiddleName = representative.middle_name ? ` ${representative.middle_name} ` : ``
    return {
      id: representative.id,
      name: `${representative.first_name}${middleName}${representative.last_name}`,
      imgURL: `https://www.govtrack.us/static/legislator-photos/${senator.govtrack_id}-200px.jpeg`,
      gender: representative.gender
    }
  })
}

const simpleReps = simplifiedReps

function populateRepsDiv(repsArray) {
  repsArray.forEach(representative => {
    const repFigure = document.createElement('figure')
    const repImg = document.createElement('img')
    const repCaption = document.createElement('figcaption')

    repImg.src = representative.imgURL
    repCaption.textContent = representative.name

    repFigure.appendChild(repImg)
    repFigure.appendChild(figCaption)
    senatorDiv.appendChild(repFigure)
  })
}

populateRepsDiv()

//senators array function
function simplifiedSenators() {
    return senators.map(senator => {
      const middleName = senator.middle_name ? ` ${senator.middle_name} ` : ` `
      return {
        id: senator.id,
        name: `${senator.first_name}${middleName}${senator.last_name}`,
        party: senator.party,
        gender: senator.gender,
        imgURL: `https://www.govtrack.us/static/legislator-photos/${senator.govtrack_id}-200px.jpeg`,
        seniority: +senator.seniority,
        missedVotesPct: senator.missed_votes_pct,
        loyaltyPct: senator.votes_with_party_pct
      }
    })
  }

  const simpleSenators = simplifiedSenators()

//populate dom with senators
function populateSenatorDiv(senatorArray) {
    senatorArray.forEach(senator => {
        const senFig = document.createElement('figure')
        const figImg = document.createElement('img')
        const figCaption = document.createElement('figcaption')

        figImg.src = senator.imgURL
        figCaption.textContent = senator.name
        senFig.appendChild(figImg)
        senFig.appendChild(figCaption)
        senatorDiv.appendChild(senFig)
    })
}


populateSenatorDiv(simpleSenators)
Header.appendChild(senatorButton)










Typescript JSON.stringify, remove key property name

The following JSON Stringify is not working. I just realized my API Request should look like this without a Key, for api to execute correctly.

{[{"resource":"Providers"},{"resource":"ServiceLocation"}]}. // this is the json request

instead of this with key bootStrapInputList.

{"bootStrapInputList":[{"resource":"Providers"},{"resource":"ServiceLocation"}]}

How do I create a proper header, without a key?

Data Types:

export type BootStrapInput = {
  resource: string;
  query?: any;
};

export type BootStrapResponse = {
  status: number;
  resource: string;
  body: any;
};

Service:

export const getBootstrap = (
  bootStrapInputList: Array<BootStrapInput>,
): any => {
  return kfetch(`/api/BootStrap`, {
    method: 'put',
    body: JSON.stringify({ bootStrapInputList }),
  });
};

// this json stringify creates {"bootStrapInputList":[{"resource":"Providers"},{"resource":"ServiceLocation"}]}

Service Execute:

(async () => {
  let bootStrapList: Array<BootStrapInput> = [
    { resource: 'Providers' },
    { resource: 'ServiceLocation' },
  ];
  const datatest = await getBootstrap(bootStrapList); // this is not working correctly

Restart video on hover of another element using embed HTML (in Webflow)?

I am using Webflow and have been struggling with writing basic code within an embed HTML editor to control a video.

I am trying to start a video class="video" each time I hover on a button class="btn" sitting inside another container class="videoContainer" which sits in under the same parent. All via html embed only, mind you.

How would I reference that class and hover action inside the video embed code editor? I think I’m struggling with the proper syntax here.

Essentially I want the video embed to know when I hover over the button so that I can restart the video from 0:00 each time a hover happens

Reference for what I'm trying to do here

<video width="100%"  
preload="preload" 
class="ignore-observer" 
loop="loop" muted="muted" 
autoplay="autoplay" 
playsinline="playsinline"> 

<source src="videoURL" type="video/mp4">
</video>

React: How to correctly call a function to load images

As the title states, I’m attempting to load images as soon as my react app loads.

I have a .jsx file, where there is a function called getHomePage().
The getHomePage() contains 4 functions.

When the getHomePage() function is called, it renders a dropdown. The dropdown contains an onChange event, where a user is able to select a collection of images. When this collection is selected, it calls a function called collectionChanged(e.target.value).

Goals:

What I want is for the images to load as soon as the application starts. Essentially, I want to call the collectionChanged(e.target.value) function when the application loads. So, I no longer want a user to select a collection, but for the collection of images to load as soon as the app loads.

How do I go about doing this? I hope all the above explanation made sense.

File: home.jsx

function getHomePage() {
      const [token, setToken] = useState("");
      const [visibility, setVisibility] = useState(false);
      const [NFTBalances, setNFTBalances] = useState();
      const [collection, setCollection] = useState();
      const [nft, setNft] = useState();
      const { Moralis } = useMoralis();
    
      const handleChangeCollection = async (col) => {
        const dbNFTs = Moralis.Object.extend(col);
        const query = new Moralis.Query(dbNFTs);
        query.ascending("rank");
        const topNFTs = query.limit(8);
        const results = await topNFTs.find();
        setNFTBalances(results);
      };
    }
    
    
    const handleSelectToken = async (num, col) => {
        if (num && col) {
          const dbNFTs = Moralis.Object.extend(col);
          const query = new Moralis.Query(dbNFTs);
          console.log(num);
          query.equalTo("tokenId", num);
          let selectedNFT = await query.first();
          selectedNFT = selectedNFT.attributes;
          console.log(selectedNFT);
          setNft(selectedNFT);
          setVisibility(true);
        }
      };
    
// FUNCTION I WANT TO CALL ONLOAD
      const collectionChanged = async (col) => {
        setCollection(col);
        handleSelectToken(token, col);
        handleChangeCollection(col);
      };
    
    
      const addToNFTs = async (col) => {
        const dbNFTs = Moralis.Object.extend(col);
        const query = new Moralis.Query(dbNFTs);
        query.ascending("rank");
        query.limit(4);
        const topNFTs = query.skip(NFTBalances.length);
        const results = await topNFTs.find();
        setNFTBalances(NFTBalances.concat(results));
      }
    
    return (
      <>
    // DROP DOWN SECTION
    <div>
      <select onChange={(e) => collectionChanged(e.target.value) }>
            <option value="">Select a Collection</option>
            <option value={"myCollection"}>My Collection</option>
      </select>
    </div>
    
    <div className="row">
         {NFTBalances && NFTBalances.map((nft, index) => {
             return (
                   <div className="col-xxl-3 col-xl-3 col-lg-6 col-md-6">
                     <div className="card items">
                       <Card key={index} onClick={() => 
                          handleSelectToken(nft.attributes.tokenId,collection)}
                              cover={ <Image src={nft.attributes.image} /> }>
                       </Card>
                      </div>     
                    </div> 
                     );
         })}
   </div>               
      </>        
);
}

export default getHomePage;

I am having trouble adding react to html

So I wanted to add react cdn links to my html, but nothing is happening. I don’t know what I’m doing wrong. I looked up so many tutorials and examples and I even copied other examples with the same cdn links and they work just fine. But for some reason I can’t get my project to render.

Here is my code for the html:

<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Random Quote Machine</title>
    <script
      src="https://unpkg.com/react@16/umd/react.development.js"
      crossorigin
    ></script>
    <script
      src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
      crossorigin
    ></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head>
<body>

    <div id="root"></div>

     <script src="./script.js" type="text/babel"></script>

</body>
</html>

Javascript file:

const quotes= [
    {
      quote:
        "Life is too short and sweet to be spent by cribbing and complaining about things. Here are some random quotes about the most wonderful gift that we've got",
      author: " Life"
    },
  {
   quote: "Programming is not a science. Programming is a craft.",
  author: "Richard Stallman"  
  },
  {
    quote: "Most good programmers do programming not because they expect to get paid or get adulation by the public, but because it is fun to program.",
    author: "Linus Torvalds"
  },
   {
    quote: "In real open source, you have the right to control your own destiny",
    author: "Linus Torvalds"
  },
  {
  quote: "We don't make mistakes; we just have happy accidents.",
    
    author: "Bob Ross"
  }
  
  ];

class Quote extends React.Component {
constructor(props) {
  super(props);
  this.state = {
   quote: '----',
   author: '----'
   };
  
  this.handleChange=this.handleChange.bind(this);
}
  
  handleChange(){
    let i= Math.floor(Math.random() * quotes.length)
    this.setState({
      quote: quotes[i].quote,
      author: quotes[i].author
    });
  }
  
 render() {
  return (
    <div>
    <div id="quote-box">
      <div id="text"> 
      <button id="new-quote" onClick={this.handleChange}>Click Me</button>
      <p>Quote: {this.state.quote}</p>
        <div id="author">
        <p>Author: {this.state.author}</p>
           
         </div>
       </div>
     </div>
     </div>
  );
 }
}

ReactDOM.render(<Quote />, document.getElementById("root"));

Re-initialize scripts after Barba.js transition?

Have been digging through old threads on this topic but nothing has quite worked for me yet. After routing to another page (w Barba), I’m having a hard time re-initializing my script tags.

I have multiple CDN links, along with a main App.js file that need to be loaded (in almost every page).

Eg:

<script src="https://unpkg.com/splitting/dist/splitting.min.js"></script>
<script src="https://jeromeetienne.github.io/threex.terrain/threex.terrain.js">. 
</script>
<script class="app" src="./app.js" type="module" defer></script>

I have tried a few things, including some hacky ones (like below) to fix it, but still no luck.

barba.hooks.after((data) => {
let js = [...document.getElementsByTagName("script")];
for (var g of js) {
   next.container.appendChild(g.innerHTML);
}
});

Still new to Barba & having to figure these out, but any help would be greatly appreciated!

is there a way of returning an object without a specified key value pair? [duplicate]

In this instance I have created a newUser object, with the following key value pairs. username, email, password, avatar, I am then returning the newUser to the client, but I would like to remove the password before doing so. Is there a way in javascript to essentially remove a pair from the object before returning it?

const newUser = {username, password, email, avatar}

// remove password from user here
return {user: newUser}

mongoDB mongoose group by month and total sum

I have this orderdetails model

const model = new Schema(
  {
    district: { type: String },
    category: String,
    producer: String,
    variety: String,
    qty: String,
    price: String,
    subtotal: String,
  },
  { timestamps: true }
);

I want to get the monthly sales report by variety.
First I filter the variety and then group it by the month and after calculating the sum of qty

This is my query

 const monthly = await OrderDetails.aggregate([
      {
        $match: {
          variety,
        },
      },
      {
        $group: {
          _id: {
            
            month: { $month: "$createdAt" },
            qty: { $sum: { $toInt: "$qty" } },
          },
        },
      },

      { $sort: { _id: 1 } },
      {
        $project: {
          qty: "$_id.qty",
          Month: {
            $arrayElemAt: [
              [
                "",
                "Jan",
                "Feb",
                "Mar",
                "Apr",
                "May",
                "Jun",
                "Jul",
                "Aug",
                "Sep",
                "Oct",
                "Nov",
                "Dec",
              ],
              "$_id.month",
            ],
          },
        },
      },
    ]);

But the output comes like this

Output for this query is this

[
  { _id: { month: 4, qty: 1 }, qty: 1, Month: 'Apr' },
  { _id: { month: 4, qty: 5 }, qty: 5, Month: 'Apr' }
]

But the expected output is one record with a total qty is 6 like this

[
  { _id: { month: 4, qty: 6 }, qty: 6, Month: 'Apr' },
 
]

What’s wrong in my query?