I am trying to make Nested commands in my command_handler.js discord.js

I am trying to create Nested commands in discord.js to make my bot read subfolders in my command folder (discord.js) Everything is basically in the title

command_handler.js:

const fs = require('fs')
module.exports = (client, Discord) => {
  const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'))

  for (const file of command_files) {
    const command = require(`../commands/${file}`);
    if (command.name) {
      client.commands.set(command.name, command);
    } else {
      continue;
    }
  }
}

Most of Index.js:

const Discord = require('discord.js');

const client = new Discord.Client({ partials: ["MESSAGE", "CHANNEL", "REACTION" ]});

const token = process.env['DISCORD_TOKEN']

const fs = require('fs');

client.commands = new Discord.Collection();
client.events = new Discord.Collection();

['command_handler', 'event_handler'].forEach(handler => {
  require(`./handlers/${handler}`)(client, Discord);
})

// Command Handler
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
  const command = require(`./commands/${file}`)

  client.commands.set(command.name, command)
}

// client.login token
client.login(token)

Thanks in advance

How to set random image in IFTTT from Gify, if PostImageUrl is null

I am trying to append a random image from Giphy in IFTTT, if PostImageUrl is null.

let myImageURL = WordPress.anyNewPostWp.PostImageUrl;
let noImageURL = `http://ifttt.com/images/no_image_card.png`;
let myGifImageURL = Giphy.historyOfRandomGifBasedOnKeyword[0].ImageURL;
let wpPostContent = WordPress.anyNewPostWp.PostContent;
let msg = '<img src= myGifImageURL>'+ '<br>' + wpPostContent ;


if (myImageURL == noImageURL) {
  Blogger.createPostBlogger.setBody(msg);
  //Blogger.createPostBlogger.skip(`Skipping post as No image URL present`);
}

By defaulti if PostImageUrl is null, IFTTT automaticaly append http://ifttt.com/images/no_image_card.png in place of PostImageUrl .

I am trying to set Blogger Post body with existing post content + Random Giphy Image.

Pl suggest.

functional component to class component in react native

is it right or wrong please help

This is my functional component code

 setaddCategories((prevState) => {
      return [...prevState, { category_name: "", expense_categories_id: 0 }];
    });

and here I turn it into class component

    this.setState({
      addCategories: (prevState) => {
        return [...prevState, { category_name: "", expense_categories_id: 0 }];
      },
    });

how can i transfer the data from my browser console to my php code. I am using a javascript in the browser console

 This is the code I am using for the browser console
 <!DOCTYPE html>
    <html lang="en">
        <head>
            <title>Firebase</title>
            <script src="https://www.gstatic.com/firebasejs/7.19.1/firebase-app.js"></script>
            <script src="https://www.gstatic.com/firebasejs/7.19.1/firebase-database.js"></script>
    
            <style type="text/css">
                /* Set the size of the div element that contains the map */
                #map {
                  height: 400px;
                  /* The height is 400 pixels */
                  width: 100%;
                  /* The width is the width of the web page */
                }
              </style>
        </head>
        
        <!-- <body>
            <div id="root"></div>
        </body> -->
    

This is to connect the browser console to firebase database

const firebaseConfig = {

      apiKey: "AIzaSyD2SevZI0FJV4jew4Z-c9pl7CxntknqEQY",
      authDomain: "thesisesp8266.firebaseapp.com",
      databaseURL: "https://thesisesp8266-default-rtdb.firebaseio.com",
      projectId: "thesisesp8266",
      storageBucket: "thesisesp8266.appspot.com",
      messagingSenderId: "316864477515",
      appId: "1:316864477515:web:56b460e9ce1d3a088550ce",
      measurementId: "G-F3SG81M2L6"  
    };

This is to print the data from database to browser console
firebase.initializeApp(firebaseConfig);
database = firebase.database();

     var ref = database.ref('GPS');
     ref.on('value', gotData, errData);
     
     function gotData(data){
     console.log(data.val());
     var GPS = data.val();
     var keys = Object.keys(GPS);
     console.log(keys);
     }
     function errData(err){
     console.log('Error!');
     console.log(err);
     }
       </script>
    </body>
    </html>

Array searching and slicing

Given a string nums that contains only digits and an array of numbers predefinedNumbers, I have to add colons in nums to construct a new string, where each number between colons has to be a valid number from predefinedNumbers and return all possibilities

EX: nums = “143163421154143” predefinedNumbers = [“21154”, “143”, “21154143”, “1634”, “163421154”]

Output: [ “:143:1634:21154:143:”, “:143:163421154:143:”, “:143:1634:21154143:” ]

So far I tried this code but it’s not the result I need and I’m stuck trying to understand how to go over it recursively.

Any hint is very much appreciated.

let nums = "143163421154143";
predefinedNumbers = ["21154", "143", "21154143", "1634", "163421154"];


let newArray=[];
function makeNumSentences (nums, predefinedNumbers) {
    predefinedNumbers.map(item => {
        if (nums.includes(item)) {
            newArray.push(item)
        }
    })
    
    console.log(newArray.join(':'));
        };
        
        
makeNumSentences("143163421154143",["21154", "143", "21154143", "1634", "163421154"])

Why do you need deep comparison?

reference: https://dmitripavlutin.com/how-to-compare-objects-in-javascript/

Following to the reference, deep comparison is:

The deep equality is similar to the shallow equality, but with one difference. During the shallow check, if the compared properties are objects, a recursive shallow equality check is performed on these nested objects.

const objA = {
  propA: 123
  propB: 'a'
  propObj1: { // assume reference: 1234
     propObj1: 'abc'
  }
}

const objB = {
  propA: 123
  propB: 'a'
  propObj1: { // assume reference: 1234
     propObj1: 'abc'
  }
}

Is it possible for objA and objB to be equal in shallow comparison but not in deep comparison?

Because their propObj1 have the same reference, change to objA.propObj1 will be also reflected to objB.propObj1 which means they will also be equal in deep comparison. Can you give an example where it is true in shallow comparison but false in deep comparison?

How to record audio and video using JAVASCRIPT ? (REACT JS)

I have tried but there is a error “TypeError: Cannot read properties of undefined (reading ‘stop’)”
I am calling function on button click
here is function as well 🙂

const getAudio=()=>{

         let device = navigator.mediaDevices.getUserMedia({audio: true});
         let chunks = [];
         let recorder;
         device.then(stream => {
             recorder = new MediaRecorder(stream);
             recorder.ondataavailable = e => {
                 chunks.push(e.data);
                 if (recorder.state === 'inactive') {
                     this.blob = new Blob(chunks, {type: 'audio/webm'});
                     let testAudioRecord  = URL.createObjectURL(this.blob);
                     console.log(testAudioRecord)
                 }
             }
             recorder.start(1000);
         });
         setTimeout(() => {
             recorder.stop();     //   Cannot read ('stop') =error
         }, 2000)
     }

Add QR on top of html Canvas

I’m trying to load a QR code into HTML5 canvas on top of a background image but it’s not working for whatever reason. If I change the QR code to a normal it works fine but this is no good for my purposes.

I’ve tried a million variations but here’s where I’m at right now:

setTimeout(function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var qr = document.getElementById('qrcode');
var imageObj = new Image();
        
imageObj.onload = function(){

context.drawImage(imageObj, 10, 10);
context.font = "40pt Arial";
context.fillStyle = "red";
context.fillText("Hello") 
context.drawImage(qr, 10, 10);  
     };    

     imageObj.src = "https://via.placeholder.com/350x150"; 
}, 300);
<script src="https://cdn.rawgit.com/davidshimjs/qrcodejs/gh-pages/qrcode.min.js"></script>

<script type="text/javascript">
new QRCode(document.getElementById("qrcode"), "TESTQR");
</script>

<div style="width:100px; height:100px" id="qrcode"></div>


<canvas id="myCanvas" width="350" height="150"
style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>

Any help would be appreciated.

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.)

Looping through nested array of objects

I have following array of objects with nested arrays in it. I wanted to traverse through those arrays and extract all those impact information to separate array:

this is how my input data looks like:

{
  "violations": [
    {
      "impact": "serious",
      "nodes": [
        {
          "any": [
            {
              "impact": "critical"
            },
            {
              "impact": "serious"
            }
          ],
          "all": [
            {
              "impact": "moderate"
            }
          ],
          "none": [
            {
              "impact": "minor"
            }
          ]
        }
      ]
    },
    {
      "impact": "serious",
      "nodes": [
        {
          "any": [
            {
              "impact": "serious"
            },
            {
              "impact": "minor"
            }
          ],
          "all": [
            {
              "impact": "moderate"
            }
          ],
          "none": [
            {
              "impact": "serious"
            }
          ]
        }
      ]
    },
    {
      "impact": "serious",
      "nodes": [
        {
          "any": [
            {
              "impact": "critical"
            },
            {
              "impact": "critical"
            }
          ],
          "all": [
            {
              "impact": "moderate"
            }
          ],
          "none": [
            {
              "impact": "moderate"
            }
          ]
        },
        {
          "any": [
            {
              "impact": "critical"
            },
            {
              "impact": "critical"
            }
          ],
          "all": [
            {
              "impact": "moderate"
            }
          ],
          "none": [
            {
              "impact": "moderate"
            }
          ]
        }
      ]
    }
  ]
}

expected output:

[
  {
    "impact": "serious"
  },
  {
    "impact": "critical"
  },
  {
    "impact": "serious"
  },
  {
    "impact": "moderate"
  },
  {
    "impact": "minor"
  },
  {
    "impact": "serious"
  },
  {
    "impact": "serious"
  },
  {
    "impact": "minor"
  },
  ......
]

I’m currently trying with forEach loop like below:

const results = [];
violations.forEach(({ nodes, impact }) => {
  results.push({ impact });
  // flattening nodes
  nodes.forEach(({ any, all, none }) => {
    any.forEach((v) => results.push(v));
    all.forEach((v) => results.push(v));
    none.forEach((v) => results.push(v));
  });
});

is there any better and shorter way to do the same?

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?

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);
       }
});