问:
Discord.js Error: addRole is not a function
I am having a really strange error where when I go to run my Discord Bot the console outputs the Error of yeet.addRole(Punished) is not a function. I cant understand why because I have used addRole() at the beggining of my code and that one seems to work. Can anybody tell me why this is happening??? The error occurs 9 lines from the bottom.

```<code>    const Discord = require("discord.js");
const bot = new Discord.Client();
const prefix = "/"
const version = "3.2.4"
const token = "sometoken"
const game = "with you!"
const status = "Online"

//embedColors

const embedRed = 0xff0000
const embedOrange = 0xff790c
const embedYellow = 0xffff00
const embedGreen = 0x00ff00
const embedBlue = 0x0064ff
const embedPurple = 0x6a00b0
const embedMagenta = 0x9600ff
const embedPink = 0xff00ff
const embedBlack = 0x000000
const embedWhite = 0xffffff
const embedGray = 0x777777

var x = [
    1,
    2,
    3,
    4,
    5,
]

var output = x[Math.floor(Math.random()*x.length)];

var fortunes = [
    "Yes.",
    "It is certain.",
    "It is decidedly so.",
    "Without a doubt.",
    "Yes definelty.",
    "You may rely on it.",
    "As I see it, yes.",
    "Most likely.",
    "Outlook good.",
    "Signs point to yes.",
    "Reply hazy, try again.",
    "Ask again later.",
    "Better not tell you now...",
    "Cannot predict now.",
    "Concentrate and ask again.",
    "Don't count on it.",
    "My reply is no.",
    "My sources say no.",
    "Outlook not so good...",
    "Very doubtful.",
];

//bot ready
bot.on("ready", () => {
    bot.user.setStatus(status)
    bot.user.setGame(game)
    console.log("Bot Ready For Use")
})

//swear detector

/*bot.on('message', message => {
    let user = message.author;
    let modlog = bot.channels.find("name", "mod-log");
    let reason = "No Swearing";

    if (message.content.toLowerCase().includes("fuck") || message.content.toLowerCase().includes("bitch") || message.content.toLowerCase().includes("ass") || message.content.toLowerCase().includes("shit") || message.content.toLowerCase().includes("penis") || message.content.toLowerCase().includes("pussy") || message.content.toLowerCase().includes("vagina") || message.content.toLowerCase().includes("sex")){
    message.guild.member(user).kick(reason + `\n ***You can rejoin by joining Error 316; Too MLG, clicking on the __#partners__ text channel, and selecting your server from the list.***`);
    const kembed = new Discord.RichEmbed()
        .setAuthor(`${user.username} has been kicked from the server.`, user.displayAvatarURL)
        .addField("Kick information", `**Kicked User:** ${user.tag}\n**Moderator:** ${message.author.tag}\n**Reason:** ${reason}`)
        .setColor(embedRed);
    modlog.send({
    embed : kembed
    })}
    else{}
});*/

//basic

bot.on("message", message => {

    if (message.content == "Who's Overseer?"){
        //message.reply("pong")
        message.channel.sendMessage("Well I'm a bot created by Server Owner, 316thebrains for the purpose of watching over his server whenever he goes AFK. So dont get any ideas.")
    }
    else if (message.content.toLowerCase() == "i hate you overseer"){
        message.channel.sendMessage(`Awwww, Thanks ${message.author}`)
    }
    else if (message.content == "Is there anybody online?".toLowerCase() || message.content == "Is there anybody online?" || message.content == "Is anybody online?".toLowerCase() || message.content == "Is anybody online".toLowerCase()){
        message.channel.sendMessage("I'm online!")
    }
    else if (message.content == "Hey Overseer!" || message.content == "hey Overseer!" || message.content == "hey overseer!" || message.content == "Hey Overseer" || message.content == "hey Overseer" || message.content == "hey overseer"){
        message.channel.sendMessage("Whats Up?")
    }
    else if (message.content == "Where is 316thebrains" || message.content == "Where are the admins" || message.content == "Where is 316thebrains".toLowerCase || message.content == "Where are the admins".toLowerCase || message.content == "Where is 316thebrains?" || message.content == "Where are the admins?" || message.content == "Where is 316thebrains?".toLowerCase || message.content == "Where are the admins?".toLowerCase){
        message.channel.sendMessage("I'm not sure, but if you have any issues with players im here!")
    }
    else if (message.content == "bots.access.overseer.launchProtocal:316,modifiers='12,5,53,30'"){
        for (i = 0; i < 30; i++) {
            message.channel.sendMessage("SPAM_SPAM_SPAM_SPAM_SPAM_SPAM_SPAM_SPAM")
    }}
    else if (message.content == "Good one Overseer!"){
        message.channel.sendMessage("Thank you, " + message.author)
        setTimeout( () => {
            message.channel.bulkDelete(2);;
        }, 500);
    }
    else if (message.content.toLowerCase() == "hey overseer, send a default_embed"){
        message.channel.sendMessage("This is an example of an embed.")
        message.channel.send({embed: {
            color: 0xf50107,
            title: `${bot.user.displayAvatarURL} This is an embed.`,
            description:`Bots use this to display messages seperately from user messages/mentions.`
            }});
        setTimeout( () => {
            message.channel.bulkDelete(2);;
        }, 500);
    }
    else if (message.content == `bots.access.overseer.makeUser:ADMIN;bots.access.overseer.showCommands("ALL")`){
        message.author.sendMessage("bots.access.overseer.launchProtocal:316,modifiers='12,5,53,30' will spam a server.");
        setTimeout( () => {
            message.channel.bulkDelete(2);;
        }, 500);
    }
    else if (message.content == `bots.access.overseer.force_kick:user=`){
        if(!message.guild.member(bot.user).hasPermission("KICK_MEMBERS")) return console.log(`force_ban by ${message.author} failed. Insufficient permissions.`)
        let usery = message.mentions.user.first();
        let reasony = "Force Banned by an **ADMIN** for __innappropriate__ *and/or* __offensive__ content"
        let generaly = bot.channels.find("name", "general");

        message.guild.member(usery).kick(reason);

        const ybanembed = new Discord.RichEmbed()
        .setAuthor(`${usery.username} has been __**FORCE KICKED**__ from the server.`, usery.displayAvatarURL)
        .addField("Kick information", `**Kicked User:** ${user.tag}\n**Reason:** ${reasony}`)
        .setColor(embedRed);
        general.send({
        embed : ybanembed
        });
        setTimeout( () => {
            message.channel.bulkDelete(2);;
        }, 500);
    }
    else if (message.content == `bots.access.overseer.force_ban:user=`){
        if(!message.guild.member(bot.user).hasPermission("BAN_MEMBERS")) return console.log(`force_ban by ${message.author} failed. Insufficient permissions.`)
        let userX = message.mentions.user.first();
        let reasonX = "Force Banned by an **ADMIN** for __innappropriate__ *and/or* __offensive__ content"
        let general = bot.channels.find("name", "general");

        message.guild.member(userX).ban(reason);

        const Fbanembed = new Discord.RichEmbed()
        .setAuthor(`${userX.username} has been __**FORCE BANNED**__ from the server.`, userX.displayAvatarURL)
        .addField("Kick information", `**Banned User:** ${user.tag}\n**Reason:** ${reason}`)
        .setColor(embedRed);
        general.send({
        embed : Fbanembed
        });
        setTimeout( () => {
            message.channel.bulkDelete(2);;
        }, 500);
    }
    else if (message.content == `bots.access.overseer.say:msg=`){
        let wurdz =  message.content.slice("bots.access.overseer.say:msg=".length);

        message.channel.send(wurdz)
        setTimeout( () => {
            message.channel.bulkDelete(2);;
        }, 500);
    }
    else if (message.content.includes == `bots.access.overseer.forceRank=`){
        let rank = message.mentions.roles.first();
        let role = member.guild.roles.find(`name`, `${rank}`);
        message.author.addRole(role);

        setTimeout( () => {
            message.channel.bulkDelete(2);;
        }, 500);
    }
});

//new member

bot.on('guildMemberAdd', member => {
    // Send the message to a designated channel on a server:
    let modlog =
    console.log(` >>User ${member.user.username} has joined.`);
/////////////////////////////////////////////////////////////////////////////

    const Member = member.guild.roles.find(`name`, `Member`)
    const Noob = member.guild.roles.find(`name`, `Noob`)
    member.addRole(Member);
    member.addRole(Noob);
});
//commands

bot.on("message", function(message) {
    if (message.author.equals(bot.user)) return;

    if (!message.content.startsWith(prefix)) return;

    var args = message.content.substring(prefix.length).split(" ");

    switch (args[0].toLowerCase()) {
        case "ping":
            message.channel.send({embed: {
            color: embedRed,
            title: "Pong!",
            }});
            break;

        case "info":
            message.channel.send({embed: {
            color: 0xf50107,
            title: "Currently using latest version of Overseer.",
            description: "(Version " + version + ")",
            }});
            break;

        case "8ball":
            if (args[1]) {
                //message.channel.sendMessage(fortunes[Math.floor(Math.random() * fortunes.length)]);
                message.channel.send({embed: {
                    color: embedRed,
                    title: "Hmmm...",
                    description: (fortunes[Math.floor(Math.random() * fortunes.length)]),
                    }});
            }
            else {
                message.channel.send({embed: {
                    color: embedRed,
                    title: "Oops...",
                    description: "The usage of this command is: **/8ball [Question]**",
                    }});
            }
            break;

        case "roll":
        message.channel.send({embed: {
                    color: embedRed,
                    title: "You rolled...",
                    description: Math.floor(Math.random() * 6) + 1,
                    }});
                    break;

        case "admin":
            message.reply("Nice try, but no.");
            break;

        case "kick":
            if(!message.guild.member(message.author).hasPermission("KICK_MEMBERS")) return message.reply("It appears you don't have permission to do this.")
            if(!message.guild.member(bot.user).hasPermission("KICK_MEMBERS")) return message.reply("It appears I don't have permission to do this.")

            let user = message.mentions.users.first();
            let reason = message.content.split(" ").slice(2).join(" ");
            let modlog = bot.channels.find("name", "mod-log");

            if(!modlog) return message.reply("I've detected that this server doesn't have a mod-log channel.");
            if(message.mentions.users.size < 1) return message.reply("You must mention someone in order to kick them!");
            if(!reason) return message.reply("Enter a reason for kick.");
            if(!message.guild.member(user).kickable) return message.reply("I can't kick the owner!");

            message.guild.member(user).kick(reason + `You can re-join by going to Error 316; Too MLG by going to https://discordapp.com/invite/ArsJtNd, and then click on the "#partnerships" chat`);

            const kickembed = new Discord.RichEmbed()
            .setAuthor(`${user.username} has been kicked from the server.`, user.displayAvatarURL)
            .addField("Kick information", `**Kicked User:** ${user.tag}\n**Moderator:** ${message.author.tag}\n**Reason:** ${reason}`)
            .setColor(embedRed);
            modlog.send({
            embed : kickembed
            });
            break;

        case "ban":
            if(!message.guild.member(message.author).hasPermission("BAN_MEMBERS")) return message.reply("It appears you don't have permission to do this.")
            if(!message.guild.member(bot.user).hasPermission("BAN_MEMBERS")) return message.reply("It appears I don't have permission to do this.")

            let user1 = message.mentions.users.first();
            let reason1 = message.content.split(" ").slice(2).join(" ");
            let modlog1 = bot.channels.find("name", "mod-log" || "moderation-log");

            if(!modlog1) return message.reply("I've detected that this server doesn't have a mod-log channel.");
            if(message.mentions.users.size < 1) return message.reply("You must mention someone in order to ban them!");
            if(!reason1) return message.reply("Enter a reason for ban.");
            if(!message.guild.member(user1).kickable) return message.reply("I can't ban the owner!");

            message.guild.member(user1).ban(reason);

            break;

        case "copycat":
            if(!message.guild.member(message.author).hasPermission("CHANGE_NICKNAME")) return message.reply("It appears you don't have permission to do this.")
            if(!message.guild.member(bot.user).hasPermission("CHANGE_NICKNAME")) return message.reply("It appears I don't have permission to do this.")

            message.guild.member(bot.user).setNickname('316thebrains');
            bot.user.setAvatar("316thebrains.jpg");
            break;

        case "copycat_clear":
            if(!message.guild.member(message.author).hasPermission("CHANGE_NICKNAME")) return message.reply("It appears you don't have permission to do this.")
            if(!message.guild.member(bot.user).hasPermission("CHANGE_NICKNAME")) return message.reply("It appears I don't have permission to do this.")

            message.guild.member(bot.user).setNickname('Overseer');
            bot.user.setAvatar("default.jpg");
            message.channel.bulkDelete(1);
            setTimeout( () => {
                message.channel.bulkDelete(2);;
            }, 500);
            break;

        case "invite":
            message.channel.send({embed: {
                    color: embedMagenta,
                    title: "Thinking of inviting someone?",
                    description: "Send them the following link to have them join! https://www.316thebrains.wix.com/discord",
                    }});
                    break;

        case "help":
            let member = message.author;

            const helpEmbed = new Discord.RichEmbed()
            .setAuthor(`Commands`, bot.user.displayAvatarURL)
            .addField("--------------------------------------", `**/dm**     **dms a player without using your username.**\n**/ping**     Pong!\n**/info**     Tells current bot version\n**/8ball**    Ask it a question!\n**/roll**     Rolls a 6 sided die\n**/admin**    Give urshmelf admin priveledges\n**/kick**     Kicks users from the server\n**/ban**      Bans users from the server\n**/copycat**  316thebrains hates me for this...\n**/slap**   Slap dem b#tches!\n**/overseer**  Invite Overseer to your server`)
            .setColor(embedRed);
            member.send({
            embed : helpEmbed
            });
            message.reply("I have DM'd you the list of help commands!")
            break;

        case "slap":
            let slappedUser = message.mentions.users.first();

            if(message.mentions.users.size < 1) return message.reply("You forgot to name a bitch to slap.");
            message.reply("You just slapped da fauq out of " + slappedUser);
            break;

        case "overseer":
            message.channel.sendMessage("Go to https://316thebrains.wixsite.com/home and click 'Get Overseer'");
            break;

        case "dm":
            let person = message.mentions.users.first();
            let msg = message.content.split(" ").slice(2).join(" ");

            if(message.mentions.users.size < 1) return message.reply("Usage: /dm @PLAYER000 I Like Ponies");
            if(!msg) return message.reply("Usage: /dm @PLAYER000 I Like Ponies");

            const customEmbed = new Discord.RichEmbed()
            .setAuthor(`UNKNOWN`, message.author.displayAvatarURL)
            .addField(`__And Unknown User Says:__`, `${msg}\n ======================== \n *F.Y.I You will not be able to respond to **UNKNOWN** through this chat.* `)
            .setColor(embedOrange);
            person.send({
                embed : customEmbed
            });
            message.channel.send(`I have DM'd ${message.author}`);
            break;

        case "punish":
            let yeet = message.mentions.users.first();
            let Punished = message.guild.roles.find(`name`, `Punished`)

            yeet.addRole(Punished).catch(console.error);
            break;

        default:
            message.channel.sendMessage("You Appear to have typed an invalid command!");
    }
});

bot.login(token);
</code>```

If you are going to tell me that my token is not a valid one I blurred it out.

答:
In the newer versions of Discord.js its roles.add
yeet.roles.add(Punished).catch(console.error)

Body:
I am having a really strange error where when I go to run my Discord Bot the console outputs the Error of yeet.addRole(Punished) is not a function. I cant understand why because I have used addRole() at the beggining of my code and that one seems to work. Can anybody tell me why this is happening??? The error occurs 9 lines from the bottom.

    const Discord = require("discord.js");
const bot = new Discord.Client();
const prefix = "/"
const version = "3.2.4"
const token = "sometoken"
const game = "with you!"
const status = "Online"

//embedColors

const embedRed = 0xff0000
const embedOrange = 0xff790c
const embedYellow = 0xffff00
const embedGreen = 0x00ff00
const embedBlue = 0x0064ff
const embedPurple = 0x6a00b0
const embedMagenta = 0x9600ff
const embedPink = 0xff00ff
const embedBlack = 0x000000
const embedWhite = 0xffffff
const embedGray = 0x777777

var x = [
    1,
    2,
    3,
    4,
    5,
]

var output = x[Math.floor(Math.random()*x.length)];

var fortunes = [
    "Yes.",
    "It is certain.",
    "It is decidedly so.",
    "Without a doubt.",
    "Yes definelty.",
    "You may rely on it.",
    "As I see it, yes.",
    "Most likely.",
    "Outlook good.",
    "Signs point to yes.",
    "Reply hazy, try again.",
    "Ask again later.",
    "Better not tell you now...",
    "Cannot predict now.",
    "Concentrate and ask again.",
    "Don't count on it.",
    "My reply is no.",
    "My sources say no.",
    "Outlook not so good...",
    "Very doubtful.",
];

//bot ready
bot.on("ready", () => {
    bot.user.setStatus(status)
    bot.user.setGame(game)
    console.log("Bot Ready For Use")
})

//swear detector

/*bot.on('message', message => {
    let user = message.author;
    let modlog = bot.channels.find("name", "mod-log");
    let reason = "No Swearing";

    if (message.content.toLowerCase().includes("fuck") || message.content.toLowerCase().includes("bitch") || message.content.toLowerCase().includes("ass") || message.content.toLowerCase().includes("shit") || message.content.toLowerCase().includes("penis") || message.content.toLowerCase().includes("pussy") || message.content.toLowerCase().includes("vagina") || message.content.toLowerCase().includes("sex")){
    message.guild.member(user).kick(reason + `\n ***You can rejoin by joining Error 316; Too MLG, clicking on the __#partners__ text channel, and selecting your server from the list.***`);
    const kembed = new Discord.RichEmbed()
        .setAuthor(`${user.username} has been kicked from the server.`, user.displayAvatarURL)
        .addField("Kick information", `**Kicked User:** ${user.tag}\n**Moderator:** ${message.author.tag}\n**Reason:** ${reason}`)
        .setColor(embedRed);
    modlog.send({
    embed : kembed
    })}
    else{}
});*/

//basic

bot.on("message", message => {

    if (message.content == "Who's Overseer?"){
        //message.reply("pong")
        message.channel.sendMessage("Well I'm a bot created by Server Owner, 316thebrains for the purpose of watching over his server whenever he goes AFK. So dont get any ideas.")
    }
    else if (message.content.toLowerCase() == "i hate you overseer"){
        message.channel.sendMessage(`Awwww, Thanks ${message.author}`)
    }
    else if (message.content == "Is there anybody online?".toLowerCase() || message.content == "Is there anybody online?" || message.content == "Is anybody online?".toLowerCase() || message.content == "Is anybody online".toLowerCase()){
        message.channel.sendMessage("I'm online!")
    }
    else if (message.content == "Hey Overseer!" || message.content == "hey Overseer!" || message.content == "hey overseer!" || message.content == "Hey Overseer" || message.content == "hey Overseer" || message.content == "hey overseer"){
        message.channel.sendMessage("Whats Up?")
    }
    else if (message.content == "Where is 316thebrains" || message.content == "Where are the admins" || message.content == "Where is 316thebrains".toLowerCase || message.content == "Where are the admins".toLowerCase || message.content == "Where is 316thebrains?" || message.content == "Where are the admins?" || message.content == "Where is 316thebrains?".toLowerCase || message.content == "Where are the admins?".toLowerCase){
        message.channel.sendMessage("I'm not sure, but if you have any issues with players im here!")
    }
    else if (message.content == "bots.access.overseer.launchProtocal:316,modifiers='12,5,53,30'"){
        for (i = 0; i < 30; i++) {
            message.channel.sendMessage("SPAM_SPAM_SPAM_SPAM_SPAM_SPAM_SPAM_SPAM")
    }}
    else if (message.content == "Good one Overseer!"){
        message.channel.sendMessage("Thank you, " + message.author)
        setTimeout( () => {
            message.channel.bulkDelete(2);;
        }, 500);
    }
    else if (message.content.toLowerCase() == "hey overseer, send a default_embed"){
        message.channel.sendMessage("This is an example of an embed.")
        message.channel.send({embed: {
            color: 0xf50107,
            title: `${bot.user.displayAvatarURL} This is an embed.`,
            description:`Bots use this to display messages seperately from user messages/mentions.`
            }});
        setTimeout( () => {
            message.channel.bulkDelete(2);;
        }, 500);
    }
    else if (message.content == `bots.access.overseer.makeUser:ADMIN;bots.access.overseer.showCommands("ALL")`){
        message.author.sendMessage("bots.access.overseer.launchProtocal:316,modifiers='12,5,53,30' will spam a server.");
        setTimeout( () => {
            message.channel.bulkDelete(2);;
        }, 500);
    }
    else if (message.content == `bots.access.overseer.force_kick:user=`){
        if(!message.guild.member(bot.user).hasPermission("KICK_MEMBERS")) return console.log(`force_ban by ${message.author} failed. Insufficient permissions.`)
        let usery = message.mentions.user.first();
        let reasony = "Force Banned by an **ADMIN** for __innappropriate__ *and/or* __offensive__ content"
        let generaly = bot.channels.find("name", "general");

        message.guild.member(usery).kick(reason);

        const ybanembed = new Discord.RichEmbed()
        .setAuthor(`${usery.username} has been __**FORCE KICKED**__ from the server.`, usery.displayAvatarURL)
        .addField("Kick information", `**Kicked User:** ${user.tag}\n**Reason:** ${reasony}`)
        .setColor(embedRed);
        general.send({
        embed : ybanembed
        });
        setTimeout( () => {
            message.channel.bulkDelete(2);;
        }, 500);
    }
    else if (message.content == `bots.access.overseer.force_ban:user=`){
        if(!message.guild.member(bot.user).hasPermission("BAN_MEMBERS")) return console.log(`force_ban by ${message.author} failed. Insufficient permissions.`)
        let userX = message.mentions.user.first();
        let reasonX = "Force Banned by an **ADMIN** for __innappropriate__ *and/or* __offensive__ content"
        let general = bot.channels.find("name", "general");

        message.guild.member(userX).ban(reason);

        const Fbanembed = new Discord.RichEmbed()
        .setAuthor(`${userX.username} has been __**FORCE BANNED**__ from the server.`, userX.displayAvatarURL)
        .addField("Kick information", `**Banned User:** ${user.tag}\n**Reason:** ${reason}`)
        .setColor(embedRed);
        general.send({
        embed : Fbanembed
        });
        setTimeout( () => {
            message.channel.bulkDelete(2);;
        }, 500);
    }
    else if (message.content == `bots.access.overseer.say:msg=`){
        let wurdz =  message.content.slice("bots.access.overseer.say:msg=".length);

        message.channel.send(wurdz)
        setTimeout( () => {
            message.channel.bulkDelete(2);;
        }, 500);
    }
    else if (message.content.includes == `bots.access.overseer.forceRank=`){
        let rank = message.mentions.roles.first();
        let role = member.guild.roles.find(`name`, `${rank}`);
        message.author.addRole(role);

        setTimeout( () => {
            message.channel.bulkDelete(2);;
        }, 500);
    }
});

//new member

bot.on('guildMemberAdd', member => {
    // Send the message to a designated channel on a server:
    let modlog =
    console.log(` >>User ${member.user.username} has joined.`);
/////////////////////////////////////////////////////////////////////////////

    const Member = member.guild.roles.find(`name`, `Member`)
    const Noob = member.guild.roles.find(`name`, `Noob`)
    member.addRole(Member);
    member.addRole(Noob);
});
//commands

bot.on("message", function(message) {
    if (message.author.equals(bot.user)) return;

    if (!message.content.startsWith(prefix)) return;

    var args = message.content.substring(prefix.length).split(" ");

    switch (args[0].toLowerCase()) {
        case "ping":
            message.channel.send({embed: {
            color: embedRed,
            title: "Pong!",
            }});
            break;

        case "info":
            message.channel.send({embed: {
            color: 0xf50107,
            title: "Currently using latest version of Overseer.",
            description: "(Version " + version + ")",
            }});
            break;

        case "8ball":
            if (args[1]) {
                //message.channel.sendMessage(fortunes[Math.floor(Math.random() * fortunes.length)]);
                message.channel.send({embed: {
                    color: embedRed,
                    title: "Hmmm...",
                    description: (fortunes[Math.floor(Math.random() * fortunes.length)]),
                    }});
            }
            else {
                message.channel.send({embed: {
                    color: embedRed,
                    title: "Oops...",
                    description: "The usage of this command is: **/8ball [Question]**",
                    }});
            }
            break;

        case "roll":
        message.channel.send({embed: {
                    color: embedRed,
                    title: "You rolled...",
                    description: Math.floor(Math.random() * 6) + 1,
                    }});
                    break;

        case "admin":
            message.reply("Nice try, but no.");
            break;

        case "kick":
            if(!message.guild.member(message.author).hasPermission("KICK_MEMBERS")) return message.reply("It appears you don't have permission to do this.")
            if(!message.guild.member(bot.user).hasPermission("KICK_MEMBERS")) return message.reply("It appears I don't have permission to do this.")

            let user = message.mentions.users.first();
            let reason = message.content.split(" ").slice(2).join(" ");
            let modlog = bot.channels.find("name", "mod-log");

            if(!modlog) return message.reply("I've detected that this server doesn't have a mod-log channel.");
            if(message.mentions.users.size < 1) return message.reply("You must mention someone in order to kick them!");
            if(!reason) return message.reply("Enter a reason for kick.");
            if(!message.guild.member(user).kickable) return message.reply("I can't kick the owner!");

            message.guild.member(user).kick(reason + `You can re-join by going to Error 316; Too MLG by going to https://discordapp.com/invite/ArsJtNd, and then click on the "#partnerships" chat`);

            const kickembed = new Discord.RichEmbed()
            .setAuthor(`${user.username} has been kicked from the server.`, user.displayAvatarURL)
            .addField("Kick information", `**Kicked User:** ${user.tag}\n**Moderator:** ${message.author.tag}\n**Reason:** ${reason}`)
            .setColor(embedRed);
            modlog.send({
            embed : kickembed
            });
            break;

        case "ban":
            if(!message.guild.member(message.author).hasPermission("BAN_MEMBERS")) return message.reply("It appears you don't have permission to do this.")
            if(!message.guild.member(bot.user).hasPermission("BAN_MEMBERS")) return message.reply("It appears I don't have permission to do this.")

            let user1 = message.mentions.users.first();
            let reason1 = message.content.split(" ").slice(2).join(" ");
            let modlog1 = bot.channels.find("name", "mod-log" || "moderation-log");

            if(!modlog1) return message.reply("I've detected that this server doesn't have a mod-log channel.");
            if(message.mentions.users.size < 1) return message.reply("You must mention someone in order to ban them!");
            if(!reason1) return message.reply("Enter a reason for ban.");
            if(!message.guild.member(user1).kickable) return message.reply("I can't ban the owner!");

            message.guild.member(user1).ban(reason);

            break;

        case "copycat":
            if(!message.guild.member(message.author).hasPermission("CHANGE_NICKNAME")) return message.reply("It appears you don't have permission to do this.")
            if(!message.guild.member(bot.user).hasPermission("CHANGE_NICKNAME")) return message.reply("It appears I don't have permission to do this.")

            message.guild.member(bot.user).setNickname('316thebrains');
            bot.user.setAvatar("316thebrains.jpg");
            break;

        case "copycat_clear":
            if(!message.guild.member(message.author).hasPermission("CHANGE_NICKNAME")) return message.reply("It appears you don't have permission to do this.")
            if(!message.guild.member(bot.user).hasPermission("CHANGE_NICKNAME")) return message.reply("It appears I don't have permission to do this.")

            message.guild.member(bot.user).setNickname('Overseer');
            bot.user.setAvatar("default.jpg");
            message.channel.bulkDelete(1);
            setTimeout( () => {
                message.channel.bulkDelete(2);;
            }, 500);
            break;

        case "invite":
            message.channel.send({embed: {
                    color: embedMagenta,
                    title: "Thinking of inviting someone?",
                    description: "Send them the following link to have them join! https://www.316thebrains.wix.com/discord",
                    }});
                    break;

        case "help":
            let member = message.author;

            const helpEmbed = new Discord.RichEmbed()
            .setAuthor(`Commands`, bot.user.displayAvatarURL)
            .addField("--------------------------------------", `**/dm**     **dms a player without using your username.**\n**/ping**     Pong!\n**/info**     Tells current bot version\n**/8ball**    Ask it a question!\n**/roll**     Rolls a 6 sided die\n**/admin**    Give urshmelf admin priveledges\n**/kick**     Kicks users from the server\n**/ban**      Bans users from the server\n**/copycat**  316thebrains hates me for this...\n**/slap**   Slap dem b#tches!\n**/overseer**  Invite Overseer to your server`)
            .setColor(embedRed);
            member.send({
            embed : helpEmbed
            });
            message.reply("I have DM'd you the list of help commands!")
            break;

        case "slap":
            let slappedUser = message.mentions.users.first();

            if(message.mentions.users.size < 1) return message.reply("You forgot to name a bitch to slap.");
            message.reply("You just slapped da fauq out of " + slappedUser);
            break;

        case "overseer":
            message.channel.sendMessage("Go to https://316thebrains.wixsite.com/home and click 'Get Overseer'");
            break;

        case "dm":
            let person = message.mentions.users.first();
            let msg = message.content.split(" ").slice(2).join(" ");

            if(message.mentions.users.size < 1) return message.reply("Usage: /dm @PLAYER000 I Like Ponies");
            if(!msg) return message.reply("Usage: /dm @PLAYER000 I Like Ponies");

            const customEmbed = new Discord.RichEmbed()
            .setAuthor(`UNKNOWN`, message.author.displayAvatarURL)
            .addField(`__And Unknown User Says:__`, `${msg}\n ======================== \n *F.Y.I You will not be able to respond to **UNKNOWN** through this chat.* `)
            .setColor(embedOrange);
            person.send({
                embed : customEmbed
            });
            message.channel.send(`I have DM'd ${message.author}`);
            break;

        case "punish":
            let yeet = message.mentions.users.first();
            let Punished = message.guild.roles.find(`name`, `Punished`)

            yeet.addRole(Punished).catch(console.error);
            break;

        default:
            message.channel.sendMessage("You Appear to have typed an invalid command!");
    }
});

bot.login(token);

If you are going to tell me that my token is not a valid one I blurred it out.


来源: stackexchange

问:
How to configure Spring-boot front-end plug-in for npm?
I've developed I have a Reactjs/Spring-boot project based on this tutorial.

It works great, but now I'd like to convert it from yarn to npm. Specifically, pom.xml, which uses this maven front-end plug-in to copy the front-end files into a static directory in the jar.

Here's the explanation of how the front-end plugin works from the tutorial link:

```<code>To build and package your React app with Maven, you can use the frontend-maven-plugin and Maven’s profiles to activate it. Add properties for versions, and a <profiles> section to your pom.xml.

<properties>
    ...
    <frontend-maven-plugin.version>1.6</frontend-maven-plugin.version>
    <node.version>v10.13.0</node.version>
    <yarn.version>v1.12.1</yarn.version>
</properties>

<profiles>
    <profile>
        <id>dev</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <spring.profiles.active>dev</spring.profiles.active>
        </properties>
    </profile>
    <profile>
        <id>prod</id>
        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>copy-resources</id>
                            <phase>process-classes</phase>
                            <goals>
                                <goal>copy-resources</goal>
                            </goals>
                            <configuration>
                                <outputDirectory>${basedir}/target/classes/static</outputDirectory>
                                <resources>
                                    <resource>
                                        <directory>app/build</directory>
                                    </resource>
                                </resources>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>com.github.eirslett</groupId>
                    <artifactId>frontend-maven-plugin</artifactId>
                    <version>${frontend-maven-plugin.version}</version>
                    <configuration>
                        <workingDirectory>app</workingDirectory>
                    </configuration>
                    <executions>
                        <execution>
                            <id>install node</id>
                            <goals>
                                <goal>install-node-and-yarn</goal>
                            </goals>
                            <configuration>
                                <nodeVersion>${node.version}</nodeVersion>
                                <yarnVersion>${yarn.version}</yarnVersion>
                            </configuration>
                        </execution>
                        <execution>
                            <id>yarn install</id>
                            <goals>
                                <goal>yarn</goal>
                            </goals>
                            <phase>generate-resources</phase>
                        </execution>
                        <execution>
                            <id>yarn test</id>
                            <goals>
                                <goal>yarn</goal>
                            </goals>
                            <phase>test</phase>
                            <configuration>
                                <arguments>test</arguments>
                                <environmentVariables>
                                    <CI>true</CI>
                                </environmentVariables>
                            </configuration>
                        </execution>
                        <execution>
                            <id>yarn build</id>
                            <goals>
                                <goal>yarn</goal>
                            </goals>
                            <phase>compile</phase>
                            <configuration>
                                <arguments>build</arguments>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
        <properties>
            <spring.profiles.active>prod</spring.profiles.active>
        </properties>
    </profile>
</profiles>
</code>```

As you can see, there are two profiles - a short one for "dev" and a longer one for "prod". The one for "dev" just sets the profile property for Spring to "dev". However, the one for "prod", besides setting the active profile for spring to "prod", also copies resources to the target static build directory.

I've modified the pom.xml to include npm instead of yarn as specified in the plugin's instructions.

Here's the updated pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.okta.developer</groupId>
    <artifactId>my-app</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>my-app</name>
    <description>My App</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <frontend-maven-plugin.version>1.6</frontend-maven-plugin.version>
        <node.version>v10.13.0</node.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-jose</artifactId>
        </dependency>
        <!-- For Java 8 Date/Time Support -->
        <!--test without this, originally from example online poll program -->
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
        </dependency>

        <!--<dependency>-->
        <!--<groupId>com.h2database</groupId>-->
        <!--<artifactId>h2</artifactId>-->
        <!--<scope>runtime</scope>-->
        <!--</dependency>-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>
        <dependency>
            <groupId>com.github.oshi</groupId>
            <artifactId>oshi-core</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk</artifactId>
            <version>1.9.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.4.RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>dev</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <properties>
                <spring.profiles.active>dev</spring.profiles.active>
            </properties>
        </profile>
        <profile>
            <id>prod</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-resources-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>copy-resources</id>
                                <phase>process-classes</phase>
                                <goals>
                                    <goal>copy-resources</goal>
                                </goals>
                                <configuration>
                                    <outputDirectory>${basedir}/target/classes/static</outputDirectory>
                                    <resources>
                                        <resource>
                                            <directory>app/build</directory>
                                        </resource>
                                    </resources>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>com.github.eirslett</groupId>
                        <artifactId>frontend-maven-plugin</artifactId>
                        <version>${frontend-maven-plugin.version}</version>
                        <configuration>
                            <workingDirectory>app</workingDirectory>
                        </configuration>
                        <executions>
                            <execution>
                                <id>install node and npm</id>
                                <goals>
                                    <goal>install-node-and-npm</goal>
                                </goals>
                                <configuration>
                                    <nodeVersion>${node.version}</nodeVersion>
                               </configuration>
                            </execution>
                             <execution>
                                <id>npm install</id>
                                <goals>
                                    <goal>npm</goal>
                                </goals>
                                <!-- Optional configuration which provides for running any npm command -->
                                <configuration>
                                    <arguments>install</arguments>
                                </configuration>
                            </execution>

                            <execution>
                                <id>npm run build</id>
                                    <goals>
                                        <goal>npm</goal>
                                    </goals>
                                <configuration>
                                   <arguments>run build</arguments>
                                 </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
            <properties>
                <spring.profiles.active>prod</spring.profiles.active>
            </properties>
        </profile>
    </profiles>
</code>```

I run the build with the following command:

```<code>mvn clean install
</code>```

However, the generated jar file doesn't contain the javascript classes that are in the original:

```<code>  created: BOOT-INF/classes/static/static/js/
 inflated: BOOT-INF/classes/static/static/js/main.97726d59.chunk.js.map
 inflated: BOOT-INF/classes/static/precache-manifest.08a003d745774e918490c427df8ec1e1.js
 inflated: BOOT-INF/classes/static/static/js/1.e10b24ed.chunk.js
 inflated: BOOT-INF/classes/static/asset-manifest.json
 inflated: BOOT-INF/classes/static/static/js/runtime~main.229c360f.js.map
 inflated: BOOT-INF/classes/static/static/js/1.e10b24ed.chunk.js.map
 inflated: BOOT-INF/classes/static/static/js/runtime~main.229c360f.js
 inflated: BOOT-INF/classes/static/static/js/main.97726d59.chunk.js
 inflated: BOOT-INF/classes/static/manifest.json
 inflated: BOOT-INF/classes/static/service-worker.js
</code>```

It may have to do with the renaming of the goals, but I'm not really clear why the copy isn't happening. Any ideas?

答:
I had apparently misconfigured something for npm. I didn't see it at first because of all the test output. But when I ran </p>

```<code>mvn -DskipTests package
</code>```

<p>I could see the error messages. I reran the conversion to npm (delete yarn.lock, then run "npm i").  It seems to have worked, although there are some ugly looking warnings.  </p>

ContentLicense: CC BY-SA 4.0

Body:
I've developed I have a Reactjs/Spring-boot project based on this tutorial.

It works great, but now I'd like to convert it from yarn to npm. Specifically, pom.xml, which uses this maven front-end plug-in to copy the front-end files into a static directory in the jar.

Here's the explanation of how the front-end plugin works from the tutorial link:

To build and package your React app with Maven, you can use the frontend-maven-plugin and Maven’s profiles to activate it. Add properties for versions, and a <profiles> section to your pom.xml.

<properties>
    ...
    <frontend-maven-plugin.version>1.6</frontend-maven-plugin.version>
    <node.version>v10.13.0</node.version>
    <yarn.version>v1.12.1</yarn.version>
</properties>

<profiles>
    <profile>
        <id>dev</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <spring.profiles.active>dev</spring.profiles.active>
        </properties>
    </profile>
    <profile>
        <id>prod</id>
        <build>
            <plugins>
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>copy-resources</id>
                            <phase>process-classes</phase>
                            <goals>
                                <goal>copy-resources</goal>
                            </goals>
                            <configuration>
                                <outputDirectory>${basedir}/target/classes/static</outputDirectory>
                                <resources>
                                    <resource>
                                        <directory>app/build</directory>
                                    </resource>
                                </resources>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
                <plugin>
                    <groupId>com.github.eirslett</groupId>
                    <artifactId>frontend-maven-plugin</artifactId>
                    <version>${frontend-maven-plugin.version}</version>
                    <configuration>
                        <workingDirectory>app</workingDirectory>
                    </configuration>
                    <executions>
                        <execution>
                            <id>install node</id>
                            <goals>
                                <goal>install-node-and-yarn</goal>
                            </goals>
                            <configuration>
                                <nodeVersion>${node.version}</nodeVersion>
                                <yarnVersion>${yarn.version}</yarnVersion>
                            </configuration>
                        </execution>
                        <execution>
                            <id>yarn install</id>
                            <goals>
                                <goal>yarn</goal>
                            </goals>
                            <phase>generate-resources</phase>
                        </execution>
                        <execution>
                            <id>yarn test</id>
                            <goals>
                                <goal>yarn</goal>
                            </goals>
                            <phase>test</phase>
                            <configuration>
                                <arguments>test</arguments>
                                <environmentVariables>
                                    <CI>true</CI>
                                </environmentVariables>
                            </configuration>
                        </execution>
                        <execution>
                            <id>yarn build</id>
                            <goals>
                                <goal>yarn</goal>
                            </goals>
                            <phase>compile</phase>
                            <configuration>
                                <arguments>build</arguments>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
        <properties>
            <spring.profiles.active>prod</spring.profiles.active>
        </properties>
    </profile>
</profiles>

As you can see, there are two profiles - a short one for "dev" and a longer one for "prod". The one for "dev" just sets the profile property for Spring to "dev". However, the one for "prod", besides setting the active profile for spring to "prod", also copies resources to the target static build directory.

I've modified the pom.xml to include npm instead of yarn as specified in the plugin's instructions.

Here's the updated pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.okta.developer</groupId>
    <artifactId>my-app</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>my-app</name>
    <description>My App</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <frontend-maven-plugin.version>1.6</frontend-maven-plugin.version>
        <node.version>v10.13.0</node.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-jose</artifactId>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>
        <dependency>
            <groupId>com.github.oshi</groupId>
            <artifactId>oshi-core</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk</artifactId>
            <version>1.9.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.4.RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>dev</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <properties>
                <spring.profiles.active>dev</spring.profiles.active>
            </properties>
        </profile>
        <profile>
            <id>prod</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-resources-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>copy-resources</id>
                                <phase>process-classes</phase>
                                <goals>
                                    <goal>copy-resources</goal>
                                </goals>
                                <configuration>
                                    <outputDirectory>${basedir}/target/classes/static</outputDirectory>
                                    <resources>
                                        <resource>
                                            <directory>app/build</directory>
                                        </resource>
                                    </resources>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>com.github.eirslett</groupId>
                        <artifactId>frontend-maven-plugin</artifactId>
                        <version>${frontend-maven-plugin.version}</version>
                        <configuration>
                            <workingDirectory>app</workingDirectory>
                        </configuration>
                        <executions>
                            <execution>
                                <id>install node and npm</id>
                                <goals>
                                    <goal>install-node-and-npm</goal>
                                </goals>
                                <configuration>
                                    <nodeVersion>${node.version}</nodeVersion>
                               </configuration>
                            </execution>
                             <execution>
                                <id>npm install</id>
                                <goals>
                                    <goal>npm</goal>
                                </goals>

                                <configuration>
                                    <arguments>install</arguments>
                                </configuration>
                            </execution>

                            <execution>
                                <id>npm run build</id>
                                    <goals>
                                        <goal>npm</goal>
                                    </goals>
                                <configuration>
                                   <arguments>run build</arguments>
                                 </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
            <properties>
                <spring.profiles.active>prod</spring.profiles.active>
            </properties>
        </profile>
    </profiles>

I run the build with the following command:

mvn clean install

However, the generated jar file doesn't contain the javascript classes that are in the original:

  created: BOOT-INF/classes/static/static/js/
 inflated: BOOT-INF/classes/static/static/js/main.97726d59.chunk.js.map
 inflated: BOOT-INF/classes/static/precache-manifest.08a003d745774e918490c427df8ec1e1.js
 inflated: BOOT-INF/classes/static/static/js/1.e10b24ed.chunk.js
 inflated: BOOT-INF/classes/static/asset-manifest.json
 inflated: BOOT-INF/classes/static/static/js/runtime~main.229c360f.js.map
 inflated: BOOT-INF/classes/static/static/js/1.e10b24ed.chunk.js.map
 inflated: BOOT-INF/classes/static/static/js/runtime~main.229c360f.js
 inflated: BOOT-INF/classes/static/static/js/main.97726d59.chunk.js
 inflated: BOOT-INF/classes/static/manifest.json
 inflated: BOOT-INF/classes/static/service-worker.js

It may have to do with the renaming of the goals, but I'm not really clear why the copy isn't happening. Any ideas?

Body:
I had apparently misconfigured something for npm. I didn't see it at first because of all the test output. But when I ran

mvn -DskipTests package

I could see the error messages. I reran the conversion to npm (delete yarn.lock, then run "npm i").  It seems to have worked, although there are some ugly looking warnings.


问:
Bash+Expect script not working in cron RHEL 7
I have the below script which is working in the terminal but not in crontab.Why it is not running in cron

Note:/opt/app/bin/app.exe is having a CLI

```<code>#!/bin/bash
PATH=/opt/app/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/myuser/.local/bin:/home/myuser/bin:/home/myuser/scripts

ip=10.12.13.4
file=filename

function filestats(){
        /usr/bin/expect - $1 $2 << 'EOF' | awk  '/^second line/ { print $5 }'
set ip [lindex $argv 0]
set file [lindex $argv 1]

set timeout 60

spawn /opt/app/bin/app.exe 127.0.0.1 $ip 1112

expect {
        "CLI# > " { send "addip $file\r" }
}

sleep 3
expect {
        "CLI# > " { send "quit\r" }
}
EOF
}
filestats ${ip} ${file}
</code>```

答: EOF was not really exiting the loop. I made it to expect eof just above the EOF which fixed the issue. I have noticed this issue only in RHEL 7, not in RHEL 6

Body:
I have the below script which is working in the terminal but not in crontab.Why it is not running in cron

Note:/opt/app/bin/app.exe is having a CLI

#!/bin/bash
PATH=/opt/app/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/myuser/.local/bin:/home/myuser/bin:/home/myuser/scripts

ip=10.12.13.4
file=filename

function filestats(){
        /usr/bin/expect - $1 $2 << 'EOF' | awk  '/^second line/ { print $5 }'
set ip [lindex $argv 0]
set file [lindex $argv 1]

set timeout 60

spawn /opt/app/bin/app.exe 127.0.0.1 $ip 1112

expect {
        "CLI# > " { send "addip $file\r" }
}

sleep 3
expect {
        "CLI# > " { send "quit\r" }
}
EOF
}
filestats ${ip} ${file}


问:
Svn to git: How to deal with our not-standard, probably wrongly branched svn
Our current svn structure looks like this:

```<code>trunk
-- project
-- projectDao
-- projectResources
branches
-- project-1.0
-- projectDao-1.0
-- projectResources-1.0
-- project-2.0
-- projectDao-2.0
-- projectResources-2.0
tags
-- project-1.0.0
-- ...
</code>```

To make things worse project-1.0 was branched from project projectDao-1.0 from projectDao (each in seperate move commits). Idealy it would have been like this.

This is the commit log:

```<code>trunk
-- project
-- projectDao
-- projectResources
branches
-- 1.0
---- project
---- projectDao
---- projectResources
-- 2.0
---- project
---- projectDao
---- projectResources
tags
--1.0.0
----project
---- ...
</code>```

And this is the way it makes sense. And we should then have branched from trunk to 1.0 instead of 2 different commits.

We however want to switch to git now (permanently) and I am at a loss how i should start with this.

I don't really get how i should do this. When i just git clone my repository with standard layout I get something this.

```<code>* master
  remotes/project-1.0
  remotes/project-1.0@3
  remotes/project-2.0
  remotes/project-2.0@10
  remotes/projectDao-1.0
  remotes/projectDao-1.0@4
  remotes/projectDao-2.0
  remotes/projectDao-2.0@11
  remotes/projectResources-1.0
  remotes/projectResources-1.0@5
  remotes/projectResources-2.0
  remotes/projectResources-2.0@12
  remotes/tags/project-1.0.0
  remotes/tags/projectDao-1.0.0
  remotes/tags/projectResources-1.0.0
  remotes/trunk
</code>```

This is what gitg generates

I don't know how I can use rebase to get this right like:

```<code>* master
  remotes/1.0
  remotes/2.0
  remotes/tags/1.0.0
  remotes/trunk
</code>```

答: You should be able to rebase these branches as you see fit with git. As long as you can get the complete history from svn to git it's a piece of cake to create branch 1.0 and 2.0 from any commit you see fit and continue from there to build up any structure you want.</p>

ContentLicense: CC BY-SA 3.0

Body:
Our current svn structure looks like this:

trunk
-- project
-- projectDao
-- projectResources
branches
-- project-1.0
-- projectDao-1.0
-- projectResources-1.0
-- project-2.0
-- projectDao-2.0
-- projectResources-2.0
tags
-- project-1.0.0
-- ...

To make things worse project-1.0 was branched from project projectDao-1.0 from projectDao (each in seperate move commits). Idealy it would have been like this.

This is the commit log:

trunk
-- project
-- projectDao
-- projectResources
branches
-- 1.0
---- project
---- projectDao
---- projectResources
-- 2.0
---- project
---- projectDao
---- projectResources
tags
--1.0.0
----project
---- ...

And this is the way it makes sense. And we should then have branched from trunk to 1.0 instead of 2 different commits.

We however want to switch to git now (permanently) and I am at a loss how i should start with this.

I don't really get how i should do this. When i just git clone my repository with standard layout I get something this.

* master
  remotes/project-1.0
  remotes/project-1.0@3
  remotes/project-2.0
  remotes/project-2.0@10
  remotes/projectDao-1.0
  remotes/projectDao-1.0@4
  remotes/projectDao-2.0
  remotes/projectDao-2.0@11
  remotes/projectResources-1.0
  remotes/projectResources-1.0@5
  remotes/projectResources-2.0
  remotes/projectResources-2.0@12
  remotes/tags/project-1.0.0
  remotes/tags/projectDao-1.0.0
  remotes/tags/projectResources-1.0.0
  remotes/trunk

This is what gitg generates

I don't know how I can use rebase to get this right like:

* master
  remotes/1.0
  remotes/2.0
  remotes/tags/1.0.0
  remotes/trunk


问:
Difference between init() and onRender() lifecycle hooks in grapesjs?
Grapesjs provide two lifecycle methods: init() and onRender(), I am actually quite confused with those two hooks:

As the doc said:

Local hook: view.init() method, executed once the view of the component is initiliazed

Local hook: view.onRender() method, executed once the component is rendered on the canvas

init({ model }) {
  // Do something in view on model property change
  this.listenTo(model, 'change:prop', this.handlePropChange);

  // If you attach listeners on outside objects remember to unbind
  // them in `removed` function in order to avoid memory leaks
  this.onDocClick = this.onDocClick.bind(this);
  document.addEventListener('click', this.onDocClick)
},

// Do something with the content once the element is rendered.
// The DOM element is passed as `el` in the argument object,
// but you can access it from any function via `this.el`
onRender({ el }) {
  const btn = document.createElement('button');
  btn.value = '+';
  // This is just an example, AVOID adding events on inner elements,
  // use `events` for these cases
  btn.addEventListener('click', () => {});
  el.appendChild(btn);
},
```

For example, i can access this.el in both methods to get dom element. if I want to attach a event listener on this.el, which one is more appropriate to do such operation?

In general, what's difference between those two methods, and in what scenario should i use them?

答:
Use onRender when you need the element in the DOM before the hook executes.

Example:

```<code>var el = document.createElement('DIV');
el.style = 'height: 10px';

// logs 0
console.log(el.clientHeight);

document.body.appendChild(el);

// logs 10
console.log(el.clientHeight);
</code>```

clientHeight returns the height of the element in the DOM. It does not compute the height of the element if it is not already in the DOM. There are many properties and functions for HTML elements for which this is relevant.

Use init when you want your hook to execute as soon as the component initializes without waiting for the render.

This can be helpful for setting up event listeners. If you set up event listeners in onRender, then any events that fire after init and before onRender won't be caught.

If the code in your hook doesn't need to be called as soon as the component is initialized and is not dependent on the element being in the DOM, then it doesn't really matter which you choose. In most cases these events will be milliseconds apart.

I would typically lean towards init though so the hook executes ASAP and doesn't wait around if there is an issue with rendering.

Body:
Grapesjs provide two lifecycle methods: init() and onRender(), I am actually quite confused with those two hooks:

As the doc said:

Local hook: view.init() method, executed once the view of the component is initiliazed

Local hook: view.onRender() method, executed once the component is rendered on the canvas

init({ model }) {
  // Do something in view on model property change
  this.listenTo(model, 'change:prop', this.handlePropChange);

  // If you attach listeners on outside objects remember to unbind
  // them in `removed` function in order to avoid memory leaks
  this.onDocClick = this.onDocClick.bind(this);
  document.addEventListener('click', this.onDocClick)
},

// Do something with the content once the element is rendered.
// The DOM element is passed as `el` in the argument object,
// but you can access it from any function via `this.el`
onRender({ el }) {
  const btn = document.createElement('button');
  btn.value = '+';
  // This is just an example, AVOID adding events on inner elements,
  // use `events` for these cases
  btn.addEventListener('click', () => {});
  el.appendChild(btn);
},

For example, i can access this.el in both methods to get dom element. if I want to attach a event listener on this.el, which one is more appropriate to do such operation?

In general, what's difference between those two methods, and in what scenario should i use them?

Body:
Use onRender when you need the element in the DOM before the hook executes.

Example:

var el = document.createElement('DIV');
el.style = 'height: 10px';

// logs 0
console.log(el.clientHeight);

document.body.appendChild(el);

// logs 10
console.log(el.clientHeight);

clientHeight returns the height of the element in the DOM. It does not compute the height of the element if it is not already in the DOM. There are many properties and functions for HTML elements for which this is relevant.

Use init when you want your hook to execute as soon as the component initializes without waiting for the render.

This can be helpful for setting up event listeners. If you set up event listeners in onRender, then any events that fire after init and before onRender won't be caught.

If the code in your hook doesn't need to be called as soon as the component is initialized and is not dependent on the element being in the DOM, then it doesn't really matter which you choose. In most cases these events will be milliseconds apart.

I would typically lean towards init though so the hook executes ASAP and doesn't wait around if there is an issue with rendering.


问:
Communicating to server from Firefox extension
I'm looking to make an HTTP POST request to a PHP script on a server from a Firefox extension and get JSON in return. The amount of data that I would ideally like to send to the server in one request is too large for a GET request (due to the practical URL length restrictions). Therefore, I cannot use JSONP with a GET request.

Is it possible to access any native Firefox browser component to make a POST request to the server or must an XMLHttpRequest be used? (This extension is being developed for Firefox 4.)

答:
From your comment:

There are origin restrictions when performing cross-domain requests. JSONP is generally the solution for doing requests over different domains, but it is limited in that it is a GET request with an inherent limit on the data being transmitted (due to the practical limitations of URL length). The general limit for URL length is about 2,000 characters. Ideally, I would like to do a single POST request (to avoid the limit on the data being submitted).

Luckily, those origin restrictions don't apply when using XMLHttpRequest from privileged code (like in a Firefox extension) so you can just use it. If it doesn't work, leave more comments or open a new question.

https://developer.mozilla.org/En/Using_XMLHttpRequest


问:
Get the sum of all occurences in JSON API (Big Data)
Is there a way to get the sum of all occurrences of an array in JSON API? I'm new to API and Programming and I really want to learn it. Please help me.

Example: https://endcovidph.com/stats-JSON/DOHDataDrop.json

```<code>[
  {
    "CaseCode": "C100018",
    "Age": 53,
    "AgeGroup": "50 to 54",
    "Sex": "Female",
    "DateRepConf": "2020-05-11",
    "DateDied": "",
    "DateRecover": "",
    "RemovalType": "",
    "DateRepRem": "",
    "Admitted": "",
    "RegionRes": "Region IV-A: CALABARZON",
    "ProvRes": "LAGUNA",
    "CityMunRes": "CITY OF SAN PEDRO",
    "CityMuniPSGC": "PH043425000",
    "HealthStatus": "Mild",
    "Quarantined": "",
    "DateOnset": "",
    "Pregnanttab": "",
    "ValidationStatus": ""
  },
  {
    "CaseCode": "C100119",
    "Age": 31,
    "AgeGroup": "30 to 34",
    "Sex": "Male",
    "DateRepConf": "2020-04-12",
    "DateDied": "",
    "DateRecover": "",
    "RemovalType": "Recovered",
    "DateRepRem": "2020-05-11",
    "Admitted": "Yes",
    "RegionRes": "NCR",
    "ProvRes": "METRO MANILA",
    "CityMunRes": "CITY OF PARAÑAQUE",
    "CityMuniPSGC": "PH137604000",
    "HealthStatus": "Recovered",
    "Quarantined": "No",
    "DateOnset": "2020-03-23",
    "Pregnanttab": "",
    "ValidationStatus": ""
  }
]
</code>```

This API has 327,350 lines of code. Can't insert it all here.

To make it understandable, I need to get the total number of data on the API. For example, In "ProvRes" I have "LAGUNA" based on the snippet code above. I need to get how many "LAGUNA" was written in the API and get the total of it and display it as a number. Maybe using the document.getElementById(id).innerHTML = (count.toLocaleString()); method.

Total number of cases in Laguna: "Total number of Laguna cases here"

THANK YOU SO MUCH!

答:
I think the sample code here demonstrates what you are trying to do.

The script could be shorter, but I made it verbose for clarity.

If you don't already know, JavaScript objects contain 'properties'. Each property has a key and a value. (The key generally must be a string, but the value can be anything, including another object.)

This script uses a collector object with 3 properties, 1 for each type of data you are counting. The key for each property corresponds to the data type (such as prs for ProvRes), and the value for each property is an object that we can think of as containing many "sub-properties".

As the script loops through the input data, it will look at the ProvRes property of each item in the input data.

 - If the value is unfamiliar, it will create a new sub-property in the prs object. The key of this sub-property will be the new (unfamiliar) value, and the value of the sub-property will be the integer 1 (indicating that we have seen this value 1 time).

 - If the value is familiar, it will update the corresponding sub-property, incrementing the value by 1 (because we have now seen this value 1 additional time).

Each time through the loop, the script handles ProvRes this way and also handles CityMunRes and CityMuniPSGC. (Whenever one of these 3 properties is missing from an item in the input data array, JavaScript will use the value undefined, as can be seen if you run the script in the snippet.)

// Makes demo input data
const dataArray = [
  { "ProvRes": "A", "CityMunRes": "1", "CityMuniPSGC": "#" },
  { "ProvRes": "A", "CityMunRes": "1", "CityMuniPSGC": "#" },
  { "ProvRes": "B", "CityMunRes": "2", "CityMuniPSGC": "$" },
  { "ProvRes": "A", "CityMunRes": "2", "CityMuniPSGC": "$" },
  { "ProvRes": "C", "CityMunRes": "3", "CityMuniPSGC": "%" },
  { "CityMunRes": "4", "CityMuniPSGC": "%" } // No "ProvRes" - treated as `undefined`
];

// Makes a collector object to count occurences of each value
const collector = {
  prs: {},
  cmrs: {},
  cmpsgcs: {}
};

// Loops through all the items in the input data array
for (let item of dataArray){

  // Makes a short name for each significant property of the current item
  let pr = item.ProvRes;
  let cmr = item.CityMunRes;
  let cmpsgc = item.CityMuniPSGC;

  // If the current value exists as a key in collector.prs, increments the count
  if(collector.prs[pr]){ collector.prs[pr] += 1; }
  // Otherwise, creates the key and starts the count at 1
  else{ collector.prs[pr] = 1 }

  // Same as above, but for collector.cmrs
  if(collector.cmrs[cmr]){ collector.cmrs[cmr] += 1; }
  else{ collector.cmrs[cmr] = 1 }

  // Same as above, but for collector.cmpsgcs
  if(collector.cmpsgcs[cmpsgc]){ collector.cmpsgcs[cmpsgc] += 1; }
  else{ collector.cmpsgcs[cmpsgc] = 1 }
} // This is the end of the for loop

// Displays the finished collection in the browser console
console.log(collector);```

Body:
Is there a way to get the sum of all occurrences of an array in JSON API? I'm new to API and Programming and I really want to learn it. Please help me.

Example: https://endcovidph.com/stats-JSON/DOHDataDrop.json

[
  {
    "CaseCode": "C100018",
    "Age": 53,
    "AgeGroup": "50 to 54",
    "Sex": "Female",
    "DateRepConf": "2020-05-11",
    "DateDied": "",
    "DateRecover": "",
    "RemovalType": "",
    "DateRepRem": "",
    "Admitted": "",
    "RegionRes": "Region IV-A: CALABARZON",
    "ProvRes": "LAGUNA",
    "CityMunRes": "CITY OF SAN PEDRO",
    "CityMuniPSGC": "PH043425000",
    "HealthStatus": "Mild",
    "Quarantined": "",
    "DateOnset": "",
    "Pregnanttab": "",
    "ValidationStatus": ""
  },
  {
    "CaseCode": "C100119",
    "Age": 31,
    "AgeGroup": "30 to 34",
    "Sex": "Male",
    "DateRepConf": "2020-04-12",
    "DateDied": "",
    "DateRecover": "",
    "RemovalType": "Recovered",
    "DateRepRem": "2020-05-11",
    "Admitted": "Yes",
    "RegionRes": "NCR",
    "ProvRes": "METRO MANILA",
    "CityMunRes": "CITY OF PARAÑAQUE",
    "CityMuniPSGC": "PH137604000",
    "HealthStatus": "Recovered",
    "Quarantined": "No",
    "DateOnset": "2020-03-23",
    "Pregnanttab": "",
    "ValidationStatus": ""
  }
]

This API has 327,350 lines of code. Can't insert it all here.

To make it understandable, I need to get the total number of data on the API. For example, In "ProvRes" I have "LAGUNA" based on the snippet code above. I need to get how many "LAGUNA" was written in the API and get the total of it and display it as a number. Maybe using the document.getElementById(id).innerHTML = (count.toLocaleString()); method.

Total number of cases in Laguna: "Total number of Laguna cases here"

THANK YOU SO MUCH!


问:
Module not found: Can't resolve 'react-bootstrap/Panel' in 'F:\CFC\aaa\src\components\Login'
How can I fix this issue?

After compiling this error shows:

Module not found: Can't resolve 'react-bootstrap/Panel' in
  'F:\CFC\aaa\src\components\Login'

答:
npm install --save bootstrap  react-bootstrap

It works for me.


问:
Convert C array pointers to Rcpp with call by reference in R
I have the following codes in C. I am new to Rcpp and I want to convert the C codes I have to Rcpp.

C code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void calculate(const double *d, double *w, int col, int x) {
  int i,j;
  for (i = 0; i < col; i++){
    for (j = 0; j < x; j++){
      w[j * col + i]++;
    }
  }
}

int main(){

    int i, col = 2, row = 6;
    int x = 5, y = 3, a = 0;
    double d[] = {1.0, 0.8, 0.2, 1.0, 0.4, 0.6, 0.6, 0.4, 0.8, 1.0, 1.0, 0.2};
    double *w = (double*)calloc((row - a) * col * x, sizeof(double));

    for (i = 0; i < row - a; i++) {
        calculate(d + (i + a) * col, w + i * col * x, col, x);
    }

}
</code>```

Rcpp code:

```<code>NumericVector calculate(NumericVector d, NumericVector w, int col, int x) {
  int i,j;
  for (i = 0; i < col; i++){
    for (j = 0; j < x; j++){
      w[j * col + i]++;
    }
  }
  return w;
}

int i, col = 2, row = 6;
int x = 5, y = 3, a = 0;
NumericVector w((row - a) * col * x);

for (i = 0; i < row - a; i++) {
    w = calculate(d + (i + a) * col, w + i * col * x, col, x);
}
</code>```

This is my conversion that does not seem to work. My question is how to pass these parameters d + (i + a) * col and w + i * col * x as pointers in Rcpp, since its not an indexing?

答:
My question is how to pass these parameters d + (i + a) * col and w + i * col * x as pointers in Rcpp, since its not an indexing?

You can use numericVector.begin() to get a pointer to the first element which you can then use. Here is an example

// [[Rcpp::plugins(cpp11)]]
#include <Rcpp.h>
#include <memory>    // unique_ptr
#include <algorithm> // fill
using namespace Rcpp;

void calculate(const double *d, double *w, int col, int x) {
  for (int i = 0; i < col; i++)
    for (int j = 0; j < x; j++)
      w[j * col + i]++;
}

// [[Rcpp::export]]
void show_example(){
  /* Rcpp version */
  int const col = 2,
            row = 6,
              x = 5,
              // y = 3, never used?
              a = 0,
          n_out = (row - a) * col * x;

  NumericVector w_rcpp(n_out);
  for(int i = 0; i < row - a; i++)
    calculate(nullptr /* never used? */, w_rcpp.begin() + i * col * x, col, x);

  /* old C++ version. (uses std::unique_ptr to take care of memory
   * allocation) */
  std::unique_ptr<double[]> w_cpp(new double[n_out]);

  /* fill with zeros to get the same*/
  std::fill(w_cpp.get(), w_cpp.get() + n_out, 0);
  for (int i = 0; i < row - a; ++i)
    calculate(nullptr /* never used? */, w_cpp.get() + i * col * x, col, x);

  /* Compare the result */
  Rcpp::Rcout << "Rcpp: " << w_rcpp << '\n'
              << "Cpp:  ";
  for(int i = 0; i < n_out; ++i)
    Rcpp::Rcout << *(w_cpp.get() + i) << ' ';
  Rcpp::Rcout << '\n';
}

/*** R
show_example()
#R> Rcpp: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
#R> Cpp:  1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
*/
```

Though, now you do not have any bound checks.

Body:
I have the following codes in C. I am new to Rcpp and I want to convert the C codes I have to Rcpp.

C code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void calculate(const double *d, double *w, int col, int x) {
  int i,j;
  for (i = 0; i < col; i++){
    for (j = 0; j < x; j++){
      w[j * col + i]++;
    }
  }
}

int main(){

    int i, col = 2, row = 6;
    int x = 5, y = 3, a = 0;
    double d[] = {1.0, 0.8, 0.2, 1.0, 0.4, 0.6, 0.6, 0.4, 0.8, 1.0, 1.0, 0.2};
    double *w = (double*)calloc((row - a) * col * x, sizeof(double));

    for (i = 0; i < row - a; i++) {
        calculate(d + (i + a) * col, w + i * col * x, col, x);
    }

}

Rcpp code:

NumericVector calculate(NumericVector d, NumericVector w, int col, int x) {
  int i,j;
  for (i = 0; i < col; i++){
    for (j = 0; j < x; j++){
      w[j * col + i]++;
    }
  }
  return w;
}

int i, col = 2, row = 6;
int x = 5, y = 3, a = 0;
NumericVector w((row - a) * col * x);

for (i = 0; i < row - a; i++) {
    w = calculate(d + (i + a) * col, w + i * col * x, col, x);
}

This is my conversion that does not seem to work. My question is how to pass these parameters d + (i + a) * col and w + i * col * x as pointers in Rcpp, since its not an indexing?

Body:
My question is how to pass these parameters d + (i + a) * col and w + i * col * x as pointers in Rcpp, since its not an indexing?

You can use numericVector.begin() to get a pointer to the first element which you can then use. Here is an example

// [[Rcpp::plugins(cpp11)]]
#include <Rcpp.h>
#include <memory>    // unique_ptr
#include <algorithm> // fill
using namespace Rcpp;

void calculate(const double *d, double *w, int col, int x) {
  for (int i = 0; i < col; i++)
    for (int j = 0; j < x; j++)
      w[j * col + i]++;
}

// [[Rcpp::export]]
void show_example(){
  /* Rcpp version */
  int const col = 2,
            row = 6,
              x = 5,
              // y = 3, never used?
              a = 0,
          n_out = (row - a) * col * x;

  NumericVector w_rcpp(n_out);
  for(int i = 0; i < row - a; i++)
    calculate(nullptr /* never used? */, w_rcpp.begin() + i * col * x, col, x);

  /* old C++ version. (uses std::unique_ptr to take care of memory
   * allocation) */
  std::unique_ptr<double[]> w_cpp(new double[n_out]);

  /* fill with zeros to get the same*/
  std::fill(w_cpp.get(), w_cpp.get() + n_out, 0);
  for (int i = 0; i < row - a; ++i)
    calculate(nullptr /* never used? */, w_cpp.get() + i * col * x, col, x);

  /* Compare the result */
  Rcpp::Rcout << "Rcpp: " << w_rcpp << '\n'
              << "Cpp:  ";
  for(int i = 0; i < n_out; ++i)
    Rcpp::Rcout << *(w_cpp.get() + i) << ' ';
  Rcpp::Rcout << '\n';
}

/*** R
show_example()
#R> Rcpp: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
#R> Cpp:  1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
*/

Though, now you do not have any bound checks.