Is there a way to add a blank data attribute to an element using JavaScript?

I want to create an element like the following with JavaScript:

<div data-boolean-attribute></div>

Passing null or undefined to setAttribute() or the dataset property results in a value of the literal strings 'null' and 'undefined'. Passing an empty string or array to either method results in an empty string value:

<div data-boolean-attribute=""></div>

Is it possible to create a completely empty data attribute in vanilla JavaScript without using something like innerHTML?

Bootstrap-Javascript: How can i compile bootstrap.min.js and exclude unused Javascript plugins?

I would like to compile the Bootstrap source bootstrap.min.js to exclude unused Javascript plugins in order to reduce the KB size of the file.

Let’s say i currently only use offcanvas.js and dropdown.js, how can i remove all js modules from the botstrap.min.js file, and only offcanvas.js and dropdown.js remain in it?

Bootstrap suggest two ways Lean JavaScript or Webpack and bundler, but I failed to apply them. I believe the mechanism is the same as SASS compiling the SCSS file to CSS (which i did fine correctly), but for the Javascript i fail.

Can anyone show me a practical example please? Thank you

Efficiently Get Checks and Pinned Pieces [closed]

I have been trying to figure this out for days, searching on the wiki and figuring out a way to get or find the pinned pieces. The check, however, could be simple.

Currently I’m using the x-ray attacks from the king’s square index, but I still have no idea what to do with the result. Can I even use this method for generating a pinned ray mask?

//* Piece positions; white to move
8 | k  ⋅  ⋅  r  ⋅  ⋅  ⋅  ⋅
7 | ⋅  ⋅  ⋅  P  ⋅  ⋅  b  ⋅
6 | ⋅  ⋅  ⋅  ⋅  ⋅  P  ⋅  ⋅
5 | ⋅  ⋅  ⋅  ⋅  ⋅  ⋅  ⋅  ⋅
4 | r  ⋅  P  K  ⋅  ⋅  ⋅  ⋅
3 | ⋅  ⋅  ⋅  ⋅  ⋅  ⋅  ⋅  ⋅
2 | ⋅  P  ⋅  ⋅  ⋅  ⋅  ⋅  ⋅
1 | b  ⋅  ⋅  ⋅  ⋅  ⋅  ⋅  ⋅
——|————————————————————————
  | a  b  c  d  e  f  g  h

//* X-ray attacks result
 0  0  0  1  0  0  0  0
 0  0  0  0  0  0  1  0
 0  0  0  0  0  0  0  0
 0  0  0  0  0  0  0  0
 1  1  0  0  0  0  0  0
 0  0  0  0  0  0  0  0
 0  0  0  0  0  0  0  0
 1  0  0  0  0  0  0  0

Unable to access web_accessible_resource when using extension_ids options in manifest.json

I have an MV3 extension where I have a file which I want to access via content script.
I am unable to do that when I specify “extension_ids”: [“myextId”] in manifest.json.
However when I use “matches”: [“<all_urls>”], I am able to access it.
According to chrome docs

Each element must include a “resources” element and either a “matches”
or “extension_ids” element.

I am getting the extension ID from extensions management page

enter image description here

Am i getting ID from the wrong place ?

Manifest.json

"web_accessible_resources": [
   {
        "resources": [
            "/sample.html",
        ],
        "extension_ids": ["liecbddmkiiihnedobmlmillhodjkdmb"]
    }
]

Error

Denying load of <URL>. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.
my.com/:40 Denying load of chrome-extension://liecbddmkiiihnedobmlmillhodjkdmb/sample.html. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.

Isnt the extension_Ids array supposed to contain the ids of all extensions that should be able to access it or am i understanding it wrong?

How do I use ffmpeg in my renderer process in electron?

I’m trying to use ffmpeg in my renderer process in my electron app. I expose the modules in my preload.js file like this:

const { contextBridge, ipcRenderer } = require('electron');
const ffmpegStatic = require('ffmpeg-static');
const ffmpeg = require('fluent-ffmpeg');
// make ffmpeg available as a function in the renderer process
contextBridge.exposeInMainWorld('ffmpeg', () => ffmpeg(ffmpegStatic.path));

And I try to acces it in my renderer.js file like this:

video.addEventListener('change', (event) => {
    const file = event.target.files[0];
    const filePath = file.path;
    const fileName = file.name;
    const fileExt = fileName.split('.').pop();
    const newFileName = fileName.replace(fileExt, 'mp4');
    const newFilePath = filePath.replace(fileName, newFileName);

    // Run FFmpeg
    ffmpeg()

        // Input file
        .input(filePath)

        // Audio bit rate
        .outputOptions('-ab', '192k')

        // Output file
        .saveToFile(newFilePath)

        // Log the percentage of work completed
        .on('progress', (progress) => {
            if (progress.percent) {
                console.log(`Processing: ${Math.floor(progress.percent)}% done`);
            }
        })

        // The callback that is run when FFmpeg is finished
        .on('end', () => {
            console.log('FFmpeg has finished.');
        })

        // The callback that is run when FFmpeg encountered an error
        .on('error', (error) => {
            console.error(error);
        });
});

But then I get following error in the console: Uncaught TypeError: ffmpeg(…).input is not a function at HTMLInputElement.
I really don’t know how to fix this, can anyone help me?

I tried writing it differently and defining ffmpeg in my rendere.js but nothing worked…

For loop running twice (object inside of an array)

I am tying to build a todo list.

The part that fills the list as the user enters something and chooses a date is this:

const renderToDoList = () => {

displayStuffJS.innerHTML = ''
for (let i = 0; i <= toDoList.length - 1; i ++){

    
    let toDoObject = toDoList[i];
    let input = toDoObject.input
    let date = toDoObject.date
    html = `<p style = 'display: inline-block;'>` + input + date +
    '<button onclick = "deleteEntry(' + i + ')">Delete</button> + </p>';
    displayStuffJS.innerHTML += HTML;
     
       

    }
}

The array (which has an object inside) is having data put into it here:

const pushToList = () => {

    displayStuffJS.innerHTML = "";
    toDoList.push([{
        input: inputValue.value, // the input where they put their entry
        date: getDate.value // the value of the date chosen

    }])
    inputValue.value =""; 
    getDate.value = "";


    renderToDoList();
}

When I run this code, enter something, choose a date and click add, it shows me that two loops have occurred, filling the array with two objects, the first object being ” for both input and date, the second index in the array is an object with the input and date I select.

enter image description here

it also brings up two delete buttons, but when I click them both they work and delete everything.

pretty stuck now, been on this for an hour and nothing I do works. I have only been programming on and of for a few weeks.

I tried several random things but nothing worked.

How can i get the default options to show again after removing some? Dynamics 365

I implemented a button that has 2 options yes and no. If I change the option from yes to no my script will remove some options from another multioption field. But if I change the option field back to yes the options will stay removed. Is it possible to reset the optionfield with the removed options? Or do I have to add the options back manually with the addOption() methode?

I tried a lot of microsoft methodes already but there seems to be no for my usecase.

Handling refresh tokens from Google via OAuth2

I’m struggling to figure out why my code will not handle refresh tokens when a user reauthenticates. Initial authentication works fine and I am able to receive the token and refresh tokens and save them to my database, but when a user comes back and needs to re-auth then my code hits a problem and throws an error when it hits the line where it tries to retrieve the unread emails.

Error being received is:
/app/node_modules/google-auth-library/build/src/auth/oauth2client.js:272
throw new Error('No access, refresh token, API key or refresh handler callback is set.');
Error: No access, refresh token, API key or refresh handler callback is set.

Here is the relevant part of the code:

    for (let user of users) {
        const email = user.email;
        let tokens = user.tokens;

        const oauth2Client = new google.auth.OAuth2(process.env.G_CLIENT_ID, process.env.G_CLIENT_SECRET, process.env.G_REDIRECT_URL);

        if (oauth2Client.isTokenExpiring()) {
            const refreshedTokens = await oauth2Client.refreshAccessToken();
            oauth2Client.setCredentials(refreshedTokens.tokens);

            await usersCollection.updateOne({ email: email }, { $set: { tokens: refreshedTokens.tokens } }); // <-- Use the tokens property
        }

        oauth2Client.setCredentials(tokens);

        const gmail = google.gmail({ version: 'v1', auth: oauth2Client });
        const response = await gmail.users.messages.list({
            userId: 'me',
            q: 'in:inbox is:unread',
        });

Facing problem with Javascript mathmatical equation

I’m facing problem with javascript code where I’ve to get a results of 173 out of these 4 variables:

let d = "-100";
let e = "20";
let f = 30;
let g = true;

console.log( -d , +e , f , +g ); 
console.log(-d * +e + f * --g);
console.log( d , e , f , g ); 
// here I need to make an equation to get a result of 173


Fruastrated me and can’t find solution for it!!!

let d = "-100";
let e = "20";
let f = 30;
let g = true;

console.log( -d , +e , f , +g ); 
console.log(-d * +e + f * --g);
console.log( d , e , f , g ); 
// here I need to make an equation to get a result of 173


Firebase remoteConfig doesnt override in app default

I hooked up a website to Firebase for its backend and I intend to change some elements value using the firebase remoteconfig. I installed and configured the firebase and Firebase remoteConfig and write the code to get the remoteConfig value I set in the firebase console.

when I console log the remoteConfig value, it logs an object with a “_source” and “_value” properties but the “source” property is still set as “default ” and the value property is still the in app value and not the remoteConfig value I set, so this means its not getting modified by the remoteConfig I set in the Firebase console??!
I also made sure I used the same parameter key both in my code and Firebase console. Please help me out someone

Discord.js – Bot code seems to fire off before the it even has the chance to get called

I’ve written some code to check and notify the user that they’re not supposed to be using a specific channel if they’re not in voice chat. The code is as follows:

const { Client, GatewayIntentBits } = require('discord.js');
require('dotenv/config')

var guildID = "1128642534483****"

const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,
        GatewayIntentBits.GuildMembers,
        GatewayIntentBits.GuildPresences
    ],
});

client.on('ready', (c) => {
    console.log('The bot is ready')
})

client.on('messageCreate', message => {
    console.log(1)
    if (message.content !== "") {
        console.log(2)
        if(!message.author.bot) {
            const Guild = client.guilds.cache.get(guildID); // Getting the guild.
            const Member = Guild.members.cache.get(message.author.id); // Getting the member.
                if (Member.voice.channel) {
                console.log(`${Member.user.tag} is connected to ${Member.voice.channel.name}!`);
                } 
                if (!Member.voice.channel) {
                console.log(`${Member.user.tag} is not connected.`);
                message.reply({ content: 'This is the voice chat channel.'})
                    .then(msg => {
                setTimeout(() => msg.delete(), 7500)
                })
            };            
        }             
    }
})

client.login(process.env.TOKEN)

The issue I’m having is that, let’s say I join voice chat -> save the code (deploy the node) -> leave voice chat -> then type something, it seems to think I’m still in VC and throws me the ‘This is the voice chat channel’ message (I believe it’s being run on deployment, and then never again).

And it just keeps on returning the same value, regardless of how many times I leave/join VC. I need to restart the node in order to get the bot to actually run the code again.

I must add I’m very new to both JS and Discord.js, I’ve read a bit on async functions thinking that might’ve been the issue but I still can’t get my head around it. I appreciate any and all help.

How can I get autocompletion for pdf.js in Visual Studio Code?

I did the following:

npm init -y
npm install pdfjs-dist

Then I created a JavaScript file test.js in Visual Studio Code which contains:

const pdfjsLib = require("pdfjs-dist/build/pdf.js");

const pdfPath = "test.pdf";
const doc = await pdfjsLib.getDocument(pdfPath).promise;

I would have expected auto completion e.g. when typing await pdfjsLib.getDocument(pdfPath). but there wasn’t. Is that the expected behaviour? Otherwise, how to enable autocompletion for such things?

Can I call a Web API from another Web API, javascript

So what I want to is calling another API after editing the request
is that possible ?

export const getNewArrivals: RequestHandler = async (req, res) => {
  req.query.isNew = '1';
  await getProducts;
};
export const getProducts: RequestHandler = async (req, res) => {
  const filter = createFilter(req.query);

  let products: Product[];
  products = await Product.findAll({
    where: filter,
  });

  return res.status(200).json(products);
};

this is in my route file

router.get('/', getProducts);
router.get('/NewArrivals', getNewArrivals);

I tried calling getProducts(req,res)
but it return an error

array reduce return concat number

I wanted to use Reduce() method to get the product id and the corresponding amount

apiArray is may array get from ApiRest

 
const newArray = apiArray.map((items) => {
          return {
            article_id: items.article_id,
            montant : items.montant
          }
        })

 const finalArray = newArray.reduce((acc:any, curr)=>{
          if (!acc[curr.article_id]) {
            acc[curr.article_id] = '';
          }
          acc[curr.article_id] += -(-curr.montant) ;
          return acc;
        },{});
        console.log('finalArray==',finalArray)
      }