Webpacker can’t find script

I have a .html.erb file and I’m trying to import a .js file to it by doing this at the start of the .html.erb:

<%= javascript_pack_tag 'script' %>

I already installed the webpacker in my rails project, the script.js is in ./javascript/packs directory and I still keep getting this error:

Webpacker can’t find script in
/home/mateus/Desktop/zNote/public/packs/manifest.json. Possible
causes:

  1. You want to set webpacker.yml value of compile to true for your environment unless you are using the webpack -w or the
    webpack-dev-server.
  2. webpack has not yet re-run to reflect updates.
  3. You have misconfigured Webpacker’s config/webpacker.yml file.
  4. Your webpack configuration is not creating a manifest. Your manifest contains: { }

My manifest file seems to be ok and also the webpacker.yml, I checked both but I still didn’t figure out how to solve this error. If I comment just this line <%= javascript_pack_tag 'script' %> the page loads without any errors and shows the HTML, but I need the javascript on it!

Unable to convert class-based Linked List to function-based Linked List

Okay so I’m learning Data Structures where my tutorial is following class-based approach. So now I am trying to convert it to functions as I want to practice Linked Lists on Leetcode and Leetcode follows the functional approach. Can anybody help me with the conversion? I need only one method to be converted and I’ll be able to do the rest of them.

Here’s the class-based approach:

class Node {
    constructor( val ) {
        this.val = val;
        this.next = null;
    }
}

class SinglyLinkedList {
    constructor () {
        this.head = null;
        this.tail = null;
        this.length = 0;
    }

    push( val ) {
        const newNode = new Node( val );

        if ( !this.head ) {
            this.head = newNode;
            this.tail = this.head;
        } else {
            this.tail.next = newNode;
            this.tail = newNode;
        }
        this.length++
        return this;
    }

}

const list = new SinglyLinkedList();

list.push( 'HELLO' );
list.push( 'WORLD' );

Here’s what I tried so far to achieve function-based approach:

function Node( val ) {
  this.val = val;
  this.next = null;
}

let head = null;
let tail = null;
let length = 0;

const SinglyLinkedListFunc = function() {
    const newNode = new Node( 'HELLO' );
};

SinglyLinkedListFunc()

This is what I could achieve so far. And I’m stuck with it and I don’t know what to do next. Someone please help

How to gray out unused C++ variables in VSCode?

VSCode grays out unused variables/imports in JS and TS files.

I use VSCode for writing C++ code also and I have the C/C++ extension installed too.
I want VSCode to also gray out unused C++ variables in my code and maybe also show a warning (if possible), which isn’t the case at present in VSCode.

Does anyone know how can I achieve this in VSCode?

Problem with react Route (rendering a blank page

I am trying to render Register Component using Route, but instead it renders a blank page (the div tag with id=”root” is emty

this is what i did:
-This is the Register component File containing Register component

-This is the App component without using react Route
App component without React Route

-This is what it looks like in the browser:
component on the after being rendered

but then after using react Route in the App component:
App component using React route

it became like this in the web page:
The Register and the Header and the Footer components are gone

Javascript – Error: ENOENT: no such file or directory

I am currently working on a project containing several functions from various files in my project. I exported them with :

module.exports.nomFonction= function{...}

I would like to compile everything in an index.js file that would call all these functions, here is where I am (rudimentary code that I am looking to improve):

var fs = require('fs');
const mt = require("./mainTweet"); // from mainTweet.js
const rp = require("./Reply"); // from Reply.js
const od = require("./getcsv"); // from Reply.js

 async function sendTweet(err, data) {
    if (err) {
      console.log(err)
    } else {
        await od.onDownload();
        await mt.mainTweet();
        await rp.Reply();
    }
} 

sendTweet();

The first function onDownload (code below) allows to download a file each time it is updated. When I launch the sendTweet function, this error appears: Error: ENOENT: no such file or directory, open ‘files/data.csv’. She works when i call it lonely but not in index.js, however i added a waiting time between the execution of the first and second function.getcsv.js (onDownload) :

const fetch = require('isomorphic-fetch');
const converterCsvToJson = require("csvtojson");
const fs = require('fs');
const path = require('path');

// created a folder to store the downloaded files
const PATH_FOLDER_DOWNLOAD = path.join(__dirname, "./files");

if(!fs.existsSync(PATH_FOLDER_DOWNLOAD)) {
    // if the download folder does not exist we create it
    fs.mkdirSync(PATH_FOLDER_DOWNLOAD);
}

async function onDownload() {
    // get the link of the last CSV file
    const response = await fetch('https://www.data.gouv.fr/api/2/datasets/6010206e7aa742eb447930f7/resources/?page=1&type=main&page_size=1', {
        method: "GET"
    });

    const data = await response.json();
    // console.log(data)

    const lastItem = data.data[0];

    // check if the file is not already owned, using a hash to uniquely identify the data
    const integrity = 'data';

    // Using simple `fs.readdirSync` would give you filenames as well as directories.
    // This approach creates objects called `Dirent`s where you can check if the the entry is a file or a directory.
    // Then you can simply filter out the directories and get the filenames.
    const filenames = fs.readdirSync(PATH_FOLDER_DOWNLOAD, {withFileTypes: true, encoding: "utf-8"})
        .filter(dirent => dirent.isFile())
        .map(dirent => dirent.name);

    // Check if some of the filenames contains the integrity hash
    const exists = filenames.some(filename => filename.indexOf(integrity) !== -1);

    // we already have this file it has not been updated yet we give up the operation
    if(exists) {
        const {published} = lastItem;
        console.log(`operation cancelled, no file has been published since: ${published}`);

    } else {
        // we don't own this file we download it
        const urlCsvFile = lastItem.url;
        const response = await fetch(urlCsvFile, {method: "GET"});
        const csvContent = await response.text();

        // writes the new file to the download folder
        // using the hash as the file name, which will allow later to check if you already have it

        fs.writeFileSync(
            path.join(PATH_FOLDER_DOWNLOAD, (integrity + ".csv")),
            csvContent,
            {encoding: "utf-8"}
        );

        // the CSV file has been downloaded and saved in a file at: /download/{hash}.csv
        console.log('File downloaded!')
    }
}

// onDownload();

So Im looking for a solution to correct this problem, i tried some tricks usings different docs but nothing works Good evening and thank you in advance for your help

Hoisting vs Scope Chain

How come, in the first block of code, I get “Hello”, but in the second block of code, I get undefined, then “bye”?

For the first block of code, I get that it is going up the scope chain to get the hoisted variable “Hello”, which I get the expected result.

    var greet = "Hello";

    var sayHi = () => {
        console.log(greet);
    }

    sayHi();

However, I’m struggling to understand how come, if I declare the variable greet after the first instance of console.log, I get undefined first? Shouldn’t the JS engine go up the scope chain to find “Hello” first?

        var greet = "Hello";

    var sayHi = () => {
        console.log(greet);

        var greet = "Bye"; 
        console.log(greet);
    }

    sayHi();

Add Facebook Messenger Chat Plugin to HTML ont working

Add Facebook Messenger Chat Plugin to HTML not working.
We have tried to integrate Facebook Customer Plugin to one of our websites. We followed the instructions in the developer documentation, but it‘s not working.

we use this code after body tag

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

<!-- Your Chat Plugin code -->
<div id="fb-customer-chat" class="fb-customerchat">
</div>

<script>
  var chatbox = document.getElementById('fb-customer-chat');
  chatbox.setAttribute("page_id", "102791148828460";
  chatbox.setAttribute("attribution", "biz_inbox";
</script>

<!-- Your SDK code -->
<script>
  window.fbAsyncInit = function() {
    FB.init({
      xfbml            : true,
      version          : 'v12.0'
    });
  };

  (function(d, s, id) {
    var js, fjs = d.getElementsByTagName[0];
    if (d.getElementById(id)) return;
    js = d.createElement; js.id = id;
    js.src = 'https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js';
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));
</script>

Is there an alternative approach than using player.h?

Is there a different approach that is more stable and works no matter whether it is j or h or anything else?

Can that part be written a different way in the code?

const iframe = player.h; https://jsfiddle.net/eo8s4zt9/

function onPlayerReady(event) {
    player = event.target;
    player.setVolume(100);
    shufflePlaylist(player);
    const iframe = player.h;
    iframe.dispatchEvent(events.afterPlayerReady);
  }

    const iframe = player.h;
    const eventHandler = eventHandlers.afterPlayerReady;
    iframe.addEventListener("afterPlayerReady", eventHandler);
  }

How to display a preview of file from local storage in a react native component?

I am working on a App in which there’s an upload button through which user can select a file to be sent to the server. But before the file is send i would like to display a preview of the file below the upload button. How can that be implemented? I don’t want to preview it separately.. It should be visible below the upload button inside a react native component.

How to change the range of x axis through drowpdown menu – javascript plotly

I am trying to create a chart with plolty.js that displays a time series with different values. I have already added rangeselectors to change the time period of the displayed values. I also want to add a dropdown menu to change the range of xaxis (actually the beginDate). I tried to change xaxis.range with the update method. Unfortunately nothing happens.
It would be great if you could help me!
enter image description here

buttonsDates = [];
first = beginDate.getFullYear();
end = endDate.getFullYear();
for (i = first; i <= end; i++) buttonsDates.push({ label: i, method: 'update', args: ['xaxis.range', '[new Date(i, 0, 1, 0, 0, 0, 0), endDate]]'] });


var myPlot = node.children[0],
    trace1 = {
        x: values.map(a => a.xvalue), y: values.map(a => a.yvalue),
        type: 'scatter',
        name: 'Messwert des Patienten',
        locale: 'de_DE',
        hovertemplate: '<b>Wert: </b> %{y}' +
            '<br><b>Datum: </b> %{x}<br>'
    },
    data = [
        trace1
    ],
    layout = {
        title: 'Verlaufswert: ' + vitSigTitle,
        hovermode: "closest",
        showlegend: true,
        xaxis: {
            autorange: true,
            range: [beginDate, endDate],
            rangeselector: {
                buttons: [
                    {
                        count: 1,
                        label: 'Tag',
                        step: 'day',
                        stepmode: 'backward'
                    },
                    {
                        count: 1,
                        label: 'Woche',
                        step: 'week',
                        stepmode: 'backward'
                    },
                    {
                        count: 1,
                        label: 'Monat',
                        step: 'month',
                        stepmode: 'backward'
                    },
                    {
                        count: 6,
                        label: '6 Monate',
                        step: 'month',
                        stepmode: 'backward'
                    },
                    {
                        count: 1,
                        label: 'Jahr',
                        step: 'year',
                        stepmode: 'backward'
                    },
                    {
                        count: 1,
                        label: 'Dieses Jahr',
                        step: 'year',
                        stepmode: 'todate'
                    },
                    {
                        label: 'Gesamt',
                        step: 'all'
                    }
                ]
            },
            rangeslider: { range: [beginDate, endDate] },
            type: 'date'
        },
        yaxis: {
            title: vitSigUnit,
            autorange: false,
            range: [minValue - 10, maxValue + 10],
            type: 'linear',
            locale: 'de_DE'
        }, updatemenus: [{
            buttons:
                buttonsDates

        }]
    };




Plotly.newPlot(node.children[0], data, layout, { locale: 'de-DE' });
console.log(Plotly.BUILD);

skip creating arrays of same data [duplicate]

I am extracting the objects from the array team which have the same year value using the array.filter() function. The only problem it creates twice or n times the arrays depending how many times the same date appears because am looping the array. I want to find a way to bypass already created array with same name and date value.

  const team = [{
    name: 'John',
    date: '2022-01-08T00:00:00.000Z',
    team: 'teamA'
  },
  {
    name: 'James',
    date: '2021-03-10T00:00:00.000Z',
    team: 'teamB'
  },
  {
    name: 'Trevor',
    date: '2022-01-08T00:00:00.000Z',
    team: 'teamC'
  },
  {
    name: 'Mike',
    date: '2021-01-08T00:00:00.000Z',
    team: 'teamC'
  },
  {
    name: 'aggelos',
    date: '2019-01-08T00:00:00.000Z',
    team: 'teamC'
  }
];
for (var i = 0; i < team.length; i++) {
  d1 = new Date(team[i].date)
  let currentDate = d1.getFullYear();

  result(currentDate)
}

function result(currentDate) {
  const extracted = team.filter(el => new Date(el.date).getFullYear() === currentDate)
  console.log(extracted)
}

Output:

{
  date: "2022-01-08T00:00:00.000Z",
  name: "John",
  team: "teamA"
}, {
  date: "2022-01-08T00:00:00.000Z",
  name: "Trevor",
  team: "teamC"
}]
[{
  date: "2021-03-10T00:00:00.000Z",
  name: "James",
  team: "teamB"
}, {
  date: "2021-01-08T00:00:00.000Z",
  name: "Mike",
  team: "teamC"
}]
[{
  date: "2022-01-08T00:00:00.000Z",
  name: "John",
  team: "teamA"
}, {
  date: "2022-01-08T00:00:00.000Z",
  name: "Trevor",
  team: "teamC"
}]
[{
  date: "2021-03-10T00:00:00.000Z",
  name: "James",
  team: "teamB"
}, {
  date: "2021-01-08T00:00:00.000Z",
  name: "Mike",
  team: "teamC"
}]
[{
  date: "2019-01-08T00:00:00.000Z",
  name: "aggelos",
  team: "teamC"
}]

Labeling of parameters within function to pull arguments from rest parameter

I’m working my way through the Odin Project and have a simple question about rest parameters:

One of the tutorial asks to ‘Implement a function that takes an array and some other arguments then removes the other arguments from that array:’ and the solution they provide is below

I understand the arguments[0] bit pulls out the first argument from …args, but does the ‘val’ parameter just work to pull any additional arguments from …args? no matter how many other arguments after the first?

const removeFromArray = function(...args) {
    const array = arguments[0];
    return array.filter((val) => !args.includes(val));
};

Vue Js: count number is not resetting to zero

in my code below, i have set a counter to notification in sidebar and i created a component in app.vue to pass the number and counter as well to sidebar … the count number works good and i’m getting number updated whenever a new notification received, but i wanted to set count back to zero when i click on the notification icon but it didn’t work.
below i passed function onReset by using emit but it’s not accessing function and i can’t even see my console.log inside the function

am i doing something wrong here? please help

//app.vue

<template>
  
<router-view :number="count" @send="getNewCount">

<sidebar :number="count" @reset="onReset" />

</router-view>
</template>

<script>
// @ts-ignore
import sidebar from "@/views/Layout/DashboardLayout.vue";
import axios from "axios";
import {
    io
} from "socket.io-client";

let socket = io("h*****.com/");
export default {
components: {
    sidebar,


  },
    data() {
        return {
            user2: JSON.parse(sessionStorage.getItem("user")),
            count: 0,
            today: null,
            
        };
        
    },
       props: {
    number: {
      type: Number,
      default: 0,
    },},
    async created() {
        console.log(this.count);
        const response = await axios.get(
            `*******api/${this.user2._id}/`, {
                headers: {
                    Authorization: "Bearer " + sessionStorage.getItem("user"),
                },
            }
        );



        socket.emit("user_connected", this.user2.username);
        // console.log(this.user2,"userr")
        socket.on("verify_connection", (data) => {
            this.verify_connection = data;
            console.log(data, "s")
        });

        socket.emit("user_connected", this.user2.username);
        socket.on("verify_connection", (data) => {
            console.log("heyy", data);
            this.verify_connection = data;
        });
        socket.on("updated_flat", (data) => {

            console.log("heyy", data);
            this.makeToast(" success ", "'b-toaster-top-center");

     

        });
        socket.on("test", (data) => {

            console.log("heyy", data);
  

          

        });

        ;
    },

    methods: {
  
        getNewCount(data) {
            this.count = data;
        },
           onReset() { //not working
      // api calls, etc.
     this.count = 0;
     console.log(this.count,"reser")
    },
        makeToast(variant = null, toaster, append = false) {
            this.$bvToast.toast(" edited ", {
                title: "BootstrapVue Toast",
                variant: variant,
                autoHideDelay: 10000,
                toaster: toaster,
                position: "top-right",

                appendToast: append,
            });
            // this.playSound();
            this.count = this.count + 1;
                console.log(this.count,"count");
        },

    },

}
</script>
//sidebar.vue

<sidebar-item v-if="roles ==='Admin'" 
 
                  :link="{ 
                    name: ' notification',
                    path: '/notifications',
                    icon: 'ni ni-bell-55 text-green'
                  }">  
               
          
        </sidebar-item>
   
<p class="notifCount" v-if="roles ==='Admin'"  @click="$emit('reset')">  {{ number }}  </p> //not working

Adding subcommands to interaction discord.js v13

I am trying to make a discord bot with / commands. I already got a lot working, but if I try to use subcommands it doesnt work. I followed the discordjs guide, even completely copying it doesnt work. I use the event handler and the command handler from the guide. I get the error:

TypeError: command.execute is not a function

index.js code:

console.clear();

const fs = require('fs');
const { Client, Collection ,Intents } = require('discord.js');
const { token } = require('./config.json');

const client = new Client({ intents: [Intents.FLAGS.GUILDS] });

const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('js'));

for (const file of eventFiles) {
    const event = require(`./events/${file}`);
    if(event.once) {
        client.once(event.name, (...args) => event.execute(...args));
    } else {
        client.on(event.name, (...args) => event.execute(...args))
    }
}

client.commands = new Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    // Set a new item in the collection
    // With the key as the command name and the value as the exported module
    client.commands.set(command.data.name, command);
}



client.on('interactionCreate', async interaction => {
    if (!interaction.isCommand()) return;

    const command = client.commands.get(interaction.commandName);

    if(!command) return;

    try {
        await command.execute(interaction);
    } catch (error) {
        console.error(error);
        await interaction.reply({ content: 'There was an error while executing this command', ephemeral: true});
    }
});

client.login(token)

info.js code:

const { SlashCommandBuilder } = require('@discordjs/builders');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('info')
        .setDescription('Get info about a user or the server!')
        .addSubcommand(subcommand =>
            subcommand
                .setName('user')
                .setDescription('Info about a user')
                .addUserOption(option => option.setName('target').setDescription('The user')))
        .addSubcommand(subcommand =>
            subcommand
                .setName('server')
                .setDescription('Info about the server')),
    async exexute(interaction) {
        if (interaction.options.getSubcommand() === 'user') {
            const user = interaction.options.getUser('target');

            if (user) {
                await interaction.reply(`Username: ${user.username}nID: ${user.id}`);
            } else {
                await interaction.reply(`Your username: ${interaction.user.username}nYour ID: ${interaction.user.id}`);
            }
        } else if (interaction.options.getSubcommand() === 'server') {
            await interaction.reply(`Server name: ${interaction.guild.name}nTotal members: ${interaction.guild.memberCount}`);
        }
    }
}

Command handler “require is not a function” error (JavaScript)

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

Have that, and for some reason the console says “require is not a function”. Error right below:

    require(`./handlers/${handler}`)(client, Discord);
                                    ^

TypeError: require(...) is not a function

What can I do to fix this? I tried everything I could but no luck.