Finding the creation date of the guild in the correct format, using discord.js

I’m trying to make a serverinfo command, and I wanted to add Server CreationDate.

This should give the Date, Time and How long ago.

But the issue is when I use message.guild.createdAt the output looks like this:

Sat Sep 04 2021 09:44:44 GMT+0000 (Coordinated Universal Time)

It’s too long AND it looks bad, I’m wondering if I can have the output look something like this?

09/04/2021 11:44 (3 months and 10 days ago)

Here is my code:

const { MessageEmbed } = require('discord.js');

module.exports = {
    name: 'serverinfo',
    category: 'Info',
    description: 'Shows info about the server.',
    aliases: [],
    usage: 'Serverinfo',
    userperms: [],
    botperms: [],
    run: async (client, message, args) => {
  if(message.author.bot) return;

  let staffcount = message.guild.roles.cache.get(process.env.ROLE_STAFF).members.size;
  let botcount = message.guild.roles.cache.get(process.env.ROLE_BOT).members.size;
  let membercount = message.guild.memberCount - botcount
  let verifiedcount = message.guild.roles.cache.get(process.env.ROLE_MEMBER).members.size - staffcount

    const embed = new MessageEmbed()
      .setThumbnail(client.user.displayAvatarURL({ dynamic: true, size: 512 }))
      .setColor("BLUE")
      .setTitle(':desktop: SERVER INFORMATION :desktop:')
      .addField('Server Name', '```' + message.guild.name + '```',true)
      .addField('Server Owner', '```SirDevinci#1998```',true)
      .addField('Server Members ['+ membercount +']', '```' + verifiedcount + ' Verified Members | ' + staffcount + ' Staff Members```',false)
      .addField('Server Tier','```' + message.guild.premiumTier + '```',true)
      .addField('Server Boosts','```' + message.guild.premiumSubscriptionCount + '```',true)
      .addField('Server CreationDate','```' + message.guild.createdAt + '```',false)
      message.channel.send(embed);
  }
}

thanks.

Hide module until everything is loaded

I’m using an interactive module within an article that takes a while to download completely.

I am hoping to have a “Loading…” div in place of the module that sticks until the whole module/article page is fully rendered.

Here’s my CSS:

.loading {
  font-family: "National Book",system-ui;
  color: #26a0a5;
  font-size: 16px;
max-width: 300px;
margin:auto;
}

.loading-wrapper {
background: #fff;
position: absolute;
top: 0;
left:0;
width: 100%;
height:100%;
z-index: 22;
}

.loading-bar {
  height: 2rem;
  background: #26a0a5;
  width: 100%;
  display: block;
  animation-name: loading;
  animation-duration: 2s;
  animation-iteration-count: infinite;
}

@keyframes loading {
  from {
    width: 0%;
  }
  to {
    width: 100%;
  }
}

.relative {
position: relative;
}

Here’s my Javascript:

  let canvasInterval = setInterval(()=>{
    if(window.MentalCanvas){
      clearInterval(canvasInterval)
      GScene = window.MentalCanvas.default.run(
        document.getElementById('render-container'),
        { path: 'https://files.sfchronicle.com/static-assets/mental-canvas/MAQUILADORA',
          fullscreen: false,
          controlsMode: 'scrolly' },
        function(error) {
          console.log(error)
         }
      );
      GScene.addEventListener('startRender', function() {
        document.querySelector('.loading-wrapper').classList.add('hidden');
      })
    }

    //declare box, element, pos
    function writeLayout(percent){
      if(GScene){
        GScene.setAnimationScrubT(percent);
        let captions = document.getElementById('captions');
        // Convert from "% of animation" (dummy.t) to "bookmark index"
        //   e.g., 0.45
        // the integer part (0) means "bookmark #1", the fractional part (0.45)
        // means "45% of the way to bookmark #2".
        //
        // This is important when the bookmark animation has different durations for
        // each bookmark, or linger times, etc.
        const bookmarkIndexFrac = GScene.cameraAnimator.GetSplinePos();
        captions.scrollTop = bookmarkIndexFrac*captions.clientHeight;
      }
    }


    window.addEventListener('scroll', ()=> {
      let scrollY = document.documentElement.scrollTop;
      let scrollRef = document.getElementById('scroll-ref');
      let offsetTop = scrollRef.offsetTop;
      let offsetHeight = scrollRef.offsetHeight-window.innerHeight; //*0.8
      let percent = (scrollY-offsetTop)/offsetHeight;

      if(scrollY>offsetTop && scrollY<offsetTop+offsetHeight){
        requestAnimationFrame(() => {
          writeLayout(percent)
        });
      }
    });

  }, 500)

And here’s the syntax I’m using right before the code for the module:

<div class="relative">
<div class="loading-wrapper">
<div class="loading">
        Loading... <span class="loading-bar"></span>
      </div>
</div>

<div id="canvas-scroller-30" class="mcscroller-module--render-container--32l70 mcscroller-module--visually-hidden--3v228"></div>

Right now, the “Loading…” shows up as intended, but it does not stay for the duration of the entire module load time.

Any help on adjusting this part of the code so it functions how it should?

GScene.addEventListener('startRender', function() {
        document.querySelector('.loading-wrapper').classList.add('hidden');
      })
    }

Using a JavaScript Prompt as a Password for a Small Website

This is probably not the safest way to do this, but I only have access to html and javascript so this is the best I can think of. I wrote a demo code of how it should work, but for some reason it’s just not!

<h1 id="hiddenContent" style="visiblity: hidden">Hidden Stuff That Requires Password To See!</h1>

window.onload = function() {
  chgDailyImg();
  document.getElementById('answer').innerHTML = imagearray[i]
}
var passwordInput = prompt("Please enter the password to continue...");
const imagearray = new Array();
imagearray[0] = "9G7DcwnWafg*EtMH";
imagearray[1] = "MDe^5qHTG#P9dHBm";
imagearray[2] = "h%$u@2Nfu8FL9H+R";
imagearray[3] = "X&NB5tYdUs5u@G#z";
imagearray[4] = "k#Rc3LGsCdu4q%qZ";
imagearray[5] = "!$p!Ss5BA%#4zeAa";
imagearray[6] = "qz63!tue3WCUxJ@R";
let i = 0;

function chgDailyImg() {
  let d = new Date();
  i = d.getDay();
}

if ((passwordInput, imagearray[i]) === true) {
  document.getElementById('hiddenContent').style.visibility = "visible"
  console.log("RIGHT")
} else {
  document.getElementById('hiddenContent').style.visibility = "hidden"
  console.log("WRONG")

}

I have messed around with this code for days and nothing…

Global memoizing fetch() to prevent multiple of the same request

I have an SPA and for technical reasons I have different elements potentially firing the same fetch() call pretty much at the same time.[1]

Rather than going insane trying to prevent multiple unrelated elements to orchestrate loading of elements, I am thinking about creating a gloabalFetch() call where:

  • the init argument is serialised (along with the resource parameter) and used as hash
  • when a request is made, it’s queued and its hash is stored
  • when another request comes, and the hash matches (which means it’s in-flight), another request will NOT be made, and it will piggy back from the previous one

async function globalFetch(resource, init) {
  const sigObject = { ...init, resource }
  const sig = JSON.stringify(sigObject)

  // If it's already happening, return that one
  if (globalFetch.inFlight[sig]) {

  // NOTE: I know I don't yet have sig.timeStamp, this is just to show
  // the logic
  if (Date.now - sig.timeStamp < 1000 * 5) {  
    return globalFetch.inFlight[sig]
  } else {
    delete globalFetch.inFlight[sig]
  }

  const ret = globalFetch.inFlight[sig] = fetch(resource, init)
  return ret
}
globalFetch.inFlight = {}

It’s obviously missing a way to have the requests’ timestamps. Plus, it’s missing a way to delete old requests in batch. Other than that… is this a good way to go about it?

Or, is there something already out there, and I am reinventing the wheel…?

[1] If you are curious, I have several location-aware elements which will reload data independently based on the URL. It’s all nice and decoupled, except that it’s a little… too decoupled. Nested elements (with partially matching URLs) needing the same data potentially end up making the same request at the same time.

How can I implement this so that the video only plays when the video is positioned in the center of the screen in react?

This is the code I applied first

main page!!
<MainProduct>
      {products.map((ele, idx) => {
        return (
          <div key={idx}>
            {products.length - 1 === idx ? (
              <ModelImages
                onClick={() => moveDetailPage(ele.product_seq)}
                id={ele.product_seq}
                alt={ele.product_name}
                src={ele.image_url}
                poster={ele.image_url}
                ref={ref}
                autoPlay
                muted
                loop
              />
            ) : (
              <ModelImages
                onClick={() => moveDetailPage(ele.product_seq)}
                id={ele.product_seq}
                alt={ele.product_name}
                src={ele.image_url}
                poster={ele.image_url}
                autoPlay
                muted
                loop
              />
            )}
          </div>
        );
      })}
    </MainProduct>

---------------------------------------------

index.html!!
<script type="text/javascript">
      window.addEventListener('load', videoScroll);
      window.addEventListener('scroll', videoScroll);

      function videoScroll() {
        if (document.querySelectorAll('video[autoplay]').length > 0) {
          var windowHeight = window.innerHeight,
            videoEl = document.querySelectorAll('video[autoplay]');

          for (var i = 0; i < videoEl.length; i++) {
            var thisVideoEl = videoEl[i],
              videoHeight = thisVideoEl.clientHeight,
              videoClientRect = thisVideoEl.getBoundingClientRect().top;

            if (
              videoClientRect <= windowHeight - videoHeight * 0.5 &&
              videoClientRect >= 0 - videoHeight * 0.5
            ) {
              thisVideoEl.play();
            } else {
              thisVideoEl.pause();
            }
          }
        }
      }
    </script>

It works, but I get these errors and it slows down a bit

enter image description here

If there is a way to fix the error or an appropriate method, please share it.

No matter how much I google, I can’t find anything.
No matter how much I google, I can’t find anything.

React : How use ogp tags on differents components

I’m trying to implements meta ogp tags on my app :
I want to do something like this :

If I post on discord, www.myurl.com/, I want “Homepage” in my embed title
If I post www.myurl.com/about, i want “About” in my embed title

I’ve already looked around helmet, and something called react-meta-tags, but It’s wasn’t really working.. the url were duplicated and never updated, and after when i’ve fixed this, url in discord was every time the same..

maybe i’ve messed up something ?

How do transitions work when fading in and out using css classes and javascript

I am trying to find out how transitions work. I am trying to make a thumbs up appear using a fade in fade out transition for a recycling simulator program, however, I do not know how understand how transitions work.
Here is a snippet of my html

<div class="thumbs-up-bg">
    <i  class="fas fa-thumbs-up" id="thumbs-up"></i>
</div>

<div class="thumbs-down-bg">
    <i class="fas fa-thumbs-down" id="thumbs-down"></i>
</div>

Here is the CSS

.thumbs-up-bg {
  position: absolute;
  visibility: hidden;
  background-color: green;
  display: inline-block;
  border-radius: 50%;
  width: 60px;
  height: 60px;
  text-align: center;
  opacity: 0;
  transition: opacity 0.1s ease-in-out;
}

#thumbs-up-bg.visible {
  opacity: 1;
}

#thumbs-up {
  font-size: 50px;
  color: white;
}

.thumbs-down-bg {
  position: absolute;
  visibility: hidden;
  background-color: red;
  display: inline-block;
  border-radius: 50%;
  width: 60px;
  height: 60px;
  text-align: center;
  opacity: 0;
  transition: opacity 0.1s ease-in-out;
}

#thumbs-down {
  font-size: 50px;
  color: white;
}

.visible {
  visibility: visible;
  opacity: 1;
  transition: opacity 2s linear;
}

.hidden {
  opacity: 0;
  transition: visibility 5s, opacity 2s linear;
}

Are transitions supposed to be set on the selector that is going to be changed? Is there a simpler way to complete this task?

Here is the Javascript

if (drop === trashDropZone){
    if(!isRecyclable(draggable)){
        alert("Success, it is garbage");
        thumbsUp.classList.toggle("visible");
        setTimeout(() =>{
        thumbsUp.classList.toggle("visible");
        thumbsUp.classList.toggle("hidden"); 
     }, 1000);
     makeInvisible(draggable);
     } else{
     //show thumbs down
     alert("Thumbs down");
     thumbsDown.classList.toggle("visible");
     setTimeout(() =>{
     thumbsDown.classList.toggle("visible");
     thumbsDown.classList.toggle("hidden"); 
     }, 1000);

Onclick requires two clicks for element, when clicking friend element, it requires 2 clicks for it to become true

When I click friend button, it takes 2 clicks to become true I want to click just once and for isFriend to be set true

function FriendChoice({friend, index}) {
    const [showHobbies, setShowHobbies] = useState(false);
    const [friendClicked, setFriendClicked] = useState(false);
    // const[isFriend, setIsFriend] = useState(false);
    // const[showActivity, setShowActivity] = useState(false);
    const db = getDatabase();
    let friendClass = "friend-card";
    const handleClick = async () => {
        try {
            const path = "Friends/" + index + "/isFriend";
            const friendRef = ref(db, path);
            setFriendClicked(!friendClicked);
            await firebaseSet(friendRef, friendClicked);
        } catch (error) {
            console.log(error);
        }
    }

   if(friend.isFriend) {
   friendClass = "friend-card friend-card-clicked";
 }

return (
<div className={friendClass} onClick={handleClick} onMouseEnter={() => setShowHobbies(true)} onMouseLeave={() => setShowHobbies(false)}>
  <img src={friend.img} alt={friend.alt} />
  <div className="d-flex flex-column friend-font">
    {!showHobbies && (
      <p><strong>{friend.name}</strong></p>
    )}
    {showHobbies && (
      <p>
        A:{friend.activity} H:{friend.hobby}
      </p>
    )}
  </div>
</div>
);
}

Thank you for your help javascript class have around 2 hours to submit

Is it possible to getImageData on Firefox without enabling Cors?

I’d like to do this simple task of taking a local file and checking its RGB value. But Firefox’s security makes it difficult… First, getImageData gives an insecure warning, to get around it, I set crossOrigin as “anonymous”, however, this results in “Cross-Origin Request Blocked”.

var ctx = document.getElementById("canvas").getContext("2d");
var img = new Image();
img.crossOrigin = "anonymous";

img.onload = function() {
     var d = ctx.getImageData(0, 0, 1, 1).data;

}
img.src = 'picture.jpeg';

I realize that I could around this by enabling Cors or doing a localhost, but I prefer neither. Are there are any other choices?

Porting php code that extracts public key from certificate and encrypt data to javascript

I wrote these two methods in PHP.
The first method, get_pubkey, extracts the public key from a certificate (certnew.cer) and the second method, encryptit(info) returns the encrypted information using the public key extracted by the first function.
I need to port these 2 functions to their Javascript equivalent. Does anyone know how to do it?

class Assdig 
{

   private $pubkey;

   /* (... )*/

   public function get_pubkey()
   {
       $certificado = __DIR__ . '/certnew.cer';

       $fp=fopen($certificado,"r"); 

       $this->pubkey=fread($fp,8192);

       fclose($fp);

       openssl_get_publickey($this->pubkey);
   }

   public function encryptit($info)
   {
     openssl_public_encrypt($info, $infoencrypted, $this->pubkey);

     return base64_encode($infoencrypted);
   }

}

How to access response body as text in https module

I am trying to do the following to parse an html document:

function process_url_handler(res) {
     // ...
     const node = xpath.fromPageSource(res);
}

for (const url of urls) {
    console.log(`${'-'.repeat(10)} ${url} ${'-'.repeat(10)}`);
    let request = https.get(url, (res) => process_url_handler(res));

Res is of type IncomingMessage. How would I get that as raw text so I can grab the html node?

Wait for For loop to finish – Angular

I have this code that formats the parameters and submits to api.

                for (let a = 0; a < perfCriteria.length; a++) {
                    const element = perfCriteria[a];
                    let newObject = Object.assign({}, paramObject)
                    newObject.performanceCriteria = element.performanceCriteriaId
                    for (let b = 0; b < element.performanceIndicators.length; b++) {
                        const element2 = element.performanceIndicators[b];
                        let newObject2 = Object.assign({}, newObject)
                        newObject2.performanceIndicator = element2.performanceIndicatorId
                        newObject2.numberTarget = element2.divisionTarget ? element2.divisionTarget : ""
                        newObject2.targetDetails = element2.targetDetails
                        for (let c = 0; c < element2.targetDetails.length; c++) {
                            const element = element2.targetDetails[c];
                            element2.targetDetails[c].individualAccountable = element.individualAccountable.map(function(row){
                                return row._id
                            })
                        }

                        divTargetArray.push(newObject2)
                    }
                }

                this.DivisionTarget.create(divTargetArray).subscribe(result =>{
                    console.log('result', result)
                    if(result.success){
                        this.appComponent.showLoadingIndicator = false;
                        this.router.navigate(['/index/app/performanceManagement/divisionTargets']);
                        this.toastService.openSnackBar(result.message, "success");
                    }else{
                        this.appComponent.showLoadingIndicator = false;
                        this.toastService.openSnackBar(result.message, "danger");
                    }
                }, error => {
                    this.appComponent.showLoadingIndicator = false;
                    this.toastService.openSnackBar(error, "danger");
                });

But sometimes, it will not wait for the For loop to finish. Is there a way that I can wait for the For loop to finish before proceeding to submit it to API?

Conditional rendering of svg files in react native

I have an app for buying and selling dogs. In my app each dog breed has its own svg file stored in my assets folder (around 150 svg files). When fetching post data from the backend, I get different information about a the post, including the dogBreed, e.g. {dogBreed: golden-retriver}. I want to render the corresponding svg to each post of dogs, but I am unsure about what the best way to deal with this is.
Should my app import all svg files?
Should I convert all the svg files into JSX files? I have done this in other parts of the application.
If i’m going for the JSX solution, should I render the JSX conditionally based on the name like: <${dogBreed}/> (if it is possible), or should I have one component take in the dog breed as a prop and have logic within for conditional rendering? . This would create a huge file, and I’m not sure if 150 if else/switch statements is the way to go. I feel really stuck here.

vue.runtime.esm.js?TypeError: Cannot read properties of undefined

I create this component from the vuetify documentation.

https://github.com/vuetifyjs/vuetify/blob/master/packages/docs/src/examples/v-card/prop-outlined.vue

<template>
    <v-card class="mx-auto" max-width="344" outlined>
        <v-list-item three-line>
            <v-list-item-content>
                <div class="text-overline mb-4">OVERLINE</div>
                <v-list-item-title class="text-h5 mb-1"> {{ person.name }} </v-list-item-title>
                <v-list-item-subtitle> {{ person.role }} </v-list-item-subtitle>
            </v-list-item-content>

            <v-list-item-avatar tile size="80" color="grey"></v-list-item-avatar>
        </v-list-item>

        <v-card-actions>
            <v-btn outlined rounded text> Message </v-btn>
        </v-card-actions>
    </v-card>
</template>

<script>
export default {
    name: 'Person',
    props: {
        person: Object
    }
}
</script>

I import them like so… was intended to use it in a loop 5 times.

<template>
    <div class="teams">
        <h1 class="subtitle-1 grey--text">Teams</h1>
        <v-container class="my-5">
            <v-card class="mx-12 my-12">
                <v-row>
                    <v-flex xs12 sm6 md4 lg3 v-for="person in team" :key="person.name">
                        <Person :name="person" :role="person" />
                    </v-flex>
                </v-row>
                <v-divider></v-divider>
            </v-card>
        </v-container>
    </div>
</template>
<script>
import Person from '@/components/Person.vue'

export default {
    name: 'Team',
    components: {
        Person
    },
    data() {
        return {
            team: [
                { name: 'The Net Ninja', role: 'Web developer' },
                { name: 'Ryu', role: 'Graphic designer' },
                { name: 'Chun Li', role: 'Web developer' },
                { name: 'Gouken', role: 'Social media maverick' },
                { name: 'Yoshi', role: 'Sales guru' }
            ]
        }
    }
}
</script>

However, it is not compiling… I kept getting

vue.runtime.esm.js?2b0e:1897 TypeError: Cannot read properties of undefined (reading ‘name’)

What did I forget to do ??

If I comment out the

 <Person :name="person" :role="person" />

enter image description here

Result

enter image description here

{{ person.name }} seems accessible…

SQLITE_CANTOPEN: unable to open database file

I’m trying to open SQLite3 database for my node.js app, but it does not seem to work there is the code I wrote to open the database:

const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database("./Users/home/Desktop/webscraping/database.db", sqlite3.OPEN_READWRITE, (err) => {
    if (err) return console.error(err.message);

    console.log("Conncetion succesful");
});

After running it the following message pops up:

SQLITE_CANTOPEN: unable to open database file