Upload multiple files base64

I’m utilizing DropZone for file uploads, where the files are converted to base64 format before being sent to the PHP server, which is built on the PHP/Phalcon framework. When I inspect the network activity in the browser, it indicates that two files have been successfully uploaded. You can view a screenshot of this
2 files uploaded

this is the object send from the front reactjs

const comment = { message, uploads: filesUploaded, };

However, when I check the count of uploaded files in my PHP action using count($this->request->getUploadedFiles()) it only returns 1, whereas it should ideally be 2.

How to create top level error handling in Discord.js

Sometimes the bot are having some unexpected error, while the bot are already on live and I don’t have the log every moment. Which makes me don’t know where the error is occurring from. Therefore, I want to make a top level error handling, so that in every time the bot has error on something, it won’t crash and it can be logging the error to a channel.

To make the code more clean, and without repeating all the same stuff, I want to keep the error handling part at the command handler level since I want to create a universal format of error handling, without editing the lower level file (commands being executed by the handler).

Below is my code, the await commandFile.run part is the code that the handler execute the command file. I have tried using catch method but it just doesn’t work when there are errors when executing the command.

    client.on('interactionCreate', async interaction => {

        if (interaction.isChatInputCommand()) {
            let args = [];

            for (i = 0; i < interaction.options._hoistedOptions.length; i++) {
                args.push({
                    name: interaction.options._hoistedOptions[i].name,
                    value: interaction.options._hoistedOptions[i].value
                })
            }

            let commandFile = client.commands.get(interaction.commandName);
            if (commandFile) await commandFile.run(client, interaction, args, DefaultFooter, LocalMap)
                .catch(err => {
                    console.log('Execution Error: ' + err)
                })
            console.log(`${interaction.member ? interaction.member.user.tag : interaction.user.tag} executed command (Slash): ${interaction}`);
        }

        if (interaction.isContextMenuCommand()) {
            let commandFile = client.commands.get(interaction.commandName);
            if (commandFile) await commandFile.run(client, interaction, DefaultFooter, LocalMap);
            console.log(`${interaction.member ? interaction.member.user.tag : interaction.user.tag} executed command (Context): ${interaction.commandName}`);
        }

    })

For demonstration, below I also have included the command file that I have used for making error on purposely:

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

module.exports = {
    run: async (client, interaction, args, DefaultFooter, LocalMap) => {
        interaction.reply({ content: 'test' });
        interaction.reply({ content: 'test' });
        return;
    },
    config: new SlashCommandBuilder()
        .setName('test')
        .setDescription('testing')
        .setDefaultPermission(false)
}

What is the best way to dynamically add an aria label via javascript?

I am working on a form that has predefined html that I can’t change and I wanted to add an aria label but I am running into difficulties. I have tried a using class name and id but it did not seem to work.

I have loaded the java script in the footer so that it fires once the page loads but I do not get any error messages to show anything is wrong. When I was working with the predefined buttons I was able to add the aria labels manually to the buttons using this method using the classname but I have tried using class name as well and it did not work for the form field. I am out of ideas.

This is the code I have tried so far:

<script>
function myFunction() {
  document.getElementById("ff-6434032271c069faf7824b65-VWlTNFZwa2RU").setAttribute('aria-label', 'firstname'); 
}

Can I get the properties of a file using node.js the same way I can by right clicking and selecting “Properties”?

In Windows, when you right click on a file, you can select “Properties” from the dropdown that’s shown. You can then navigate to a “Details” tab and see a lot of information about the file; like Title, Subtitle, Rating, Length, Bit Rate, Size, File Location, and Type. Is there a way to access all this information using Node.js?

fs.stats(myDirectory) does not return all of this information.

Mui Data table header is not sticky after applying CSS on table body

I Need to show First column of table is sticky , I am able to do for first column of table body but not for header , when I apply CSS for Table body automatically header sticky is not working.

  import { createTheme, ThemeProvider } from '@mui/material/styles';
const getMuiTheme = () =>
  createTheme({
    components: {
      MUIDataTableToolbar: {
        styleOverrides: {
          root: {
            minHeight: '50px',
            display: 'flex',
          },
          actions: {
            display: 'flex',
            flex: 'inherit',
          },
        },
      },
     
        
     
      MUIDataTableHeadCell: {
        styleOverrides: {
          root: {
            
              '&:first-child': {
                opacity: 1, // Set the opacity value you desire (0.0 to 1.0) for the first column cells
                position: 'sticky',
                left: 0,
                zIndex: 1,
                backgroundColor: 'white', // Set the background color as needed
              },
            // borderBottom: 'none !important',
            borderTop: '1px solid #d9d9d9',
            fontSize: '14px !important',
            fontFamily: 'helvetica !important',
            fontWeight: 'bold !important',
            padding: '10px 16px 10px 16px',
            // borderRight: 'none',
          },
          toolButton: {
            fontSize: '14px !important',
            fontFamily: 'helvetica !important',
            fontWeight: 'bold !important',
          },
        },
      },
     
      MuiTableCell: {
        styleOverrides: {
          root: {
            '&:first-child': {
              opacity: 1, // Set the opacity value you desire (0.0 to 1.0) for the first column cells
              position: 'sticky',
              left: 0,
              zIndex: 1,
              backgroundColor: 'white', // Set the background color as needed
            },
            color: "#000000", // This sets the text color for all cells
          },
        },
      },
        
    },
  });

   <TableContainer className={classes.container}>
        <ThemeProvider theme={getMuiTheme()}>
          <MUIDataTable
            // title='Search Results'
            // components={{
            //   TableFooter: CustomFilterList,
            // }}
            data={data}
            columns={headers}
            options={options}
            // components={components}
          />
        </ThemeProvider>
      </TableContainer>

I want to see both table header first column and body first column should be sticky , when i scroll left it should be sticky and opacity should apply

Is there any way to retrieve JSON data via a variable in Cypress?

In JS, if I want to retrieve data in JSON by my own variable, I can use obj[key] as below.

// In JS
const key = 'name'
const obj = {
    name: 'John',
    age: 5
}
console.log(obj['name']); --> OUTPUT: 'John'
console.log(obj[key]); --> OUTPUT: 'John'

I’ve tried this way in Cypress when using fixtures, but it does not work as expected. But, if I create a new variable and assign specific value for it, Cypress will work.

**/fixtures/testData.json**

{
    "name": "John",
    "age": "5"
}
**/integration/testData.spec.cy.js**

describe('Test data retrieved from JSON file', () => {
    let testData;
    beforeEach(() => {
        cy.fixture('testData.json').then(data => {
            testData = data
        })
    })
    it('Verify test data', () => {
        const tempKey = 'name'
        cy.log(testData.name) --> OUTPUT: 'John'
        // Assume that I have written a function and it returned a string **'name'** stored in variable naming **key**
        cy.log(key) --> 'name'
        cy.log(testData[key]) --> OUTPUT: undefined
        cy.log(testData[tempKey]) --> OUTPUT: 'John'
    })
}

I’ve logged my own variable (in example is key) by cy.log(key) and ensure that its returned value is correct, but by somehow the result is not as my expectation. So my question is that, is there any way to retrieve JSON data via a variable in Cypress?
Thanks a lot!

HTML audio autoplay after user interaction

Chrome’s autoplay policies changed in April of 2018. And I would like to use one of its policies: Autoplay with sound is allowed if the user has interacted with the domain (click, tap, etc.). Thus, I have a webpage

<a href="d2.php">dictation</a>

when the user click on the link on the above page, the second webpage, d2.php, is loaded. Its content is shown as following

<!DOCTYPE html>
<html>
<body>

<h1>The audio autoplay attribute</h1>

<p>Click on the play button to play a sound:</p>

<audio controls autoplay>
  <source src="https://www.w3schools.com/tags/horse.ogg" type="audio/ogg">
  <source src="https://www.w3schools.com/tags/horse.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>

</body>
</html>

The audio autoplay works on Chrome as expected. Also it can be verified that the autoplay works with Edge and Opera. However,

  1. It does not work with Firefox 117.0.1 (64-bit), ie, audio is not autoplayed.
  2. With a version of Safari I installed on my Ubuntu using WINE, it give me “Your browser does not support the audio element.” message.

I would consider the Safari message is caused by my Ubuntu – WINE installation. However, could anybody help me with the firefox audio autoplay? I am open to any solution with HTML, PHP, and JaveScript. Thanks in advance.

PS: I have read many popular posts about “html audio autoplay” on the Internet.

I need an application developer [closed]

Peacebe uponyou. Ineed a professionalapplicationdeveloper. ThankyouReach outtome

ViewRootImplDispatchActivity]( 5264): windowFocusChangedhasFocus=falseinTouchMode=trueUpdateCheckerService( 5264call() calledwith: model = [net.jahez.fleets.checkupdate.domain.AppVersion@9646516]

Unable to Edit a Cell (AGGrid Cell Editing) on (Primefaces) Dialog (when modal=true)

Cell editing only works when the modal attribute is false.
The cell input text doesn’t show what the user types.
Specification:

  • Primefaces Version: 13.0.0
  • AG-Grid Version: 30.1.0

Sample Code:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:p="http://primefaces.org/ui"
      lang="en">

<h:head>
   ......
   <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/ag-grid-community.min.js">
</head>

<h:body
  <p:dialog id="maindialog" widgetVar="maindialog" header="Main"  width="800px" modal="true">
     <div id="aggridid"style="width:100%; height: 600px" class="ag-theme-balham"></div>
  </p:dialog>
</h:body>
</html>

<script>
const gridOptions = {
  columnDefs: [
    { field: 'athlete' },
    { field: 'age' },
    { field: 'country' },
    { field: 'year' },
    { field: 'date' },
    { field: 'sport' },
    { field: 'gold' },
    { field: 'silver' },
    { field: 'bronze' },
    { field: 'total' },
  ],
  defaultColDef: {
    editable: true,
    cellDataType: false,
  },
};

// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', () => {
  const gridDiv = document.querySelector('#aggridid');
  new agGrid.Grid(gridDiv, gridOptions);

  // do http request to get our sample data - not using any framework to keep the example self contained.
  // you will probably use a framework like JQuery, Angular or something else to do your HTTP calls.
  fetch('https://www.ag-grid.com/example-assets/olympic-winners.json')
    .then((response) => response.json())
    .then((data) => gridOptions.api.setRowData(data));
});
</script>

It works after I try to remove the “ag-cell-inline-editing” and “ag-row-inline-editing” classes in debugging console mode(F12).
Any idea what the issue could be ?

java Script give an error when i make new div

i have this html code

<div class="form-group">
          <label>Debt Type:</label>
          <select id="debtType" placeholder="Chose Type of Debt" required>
            <option value="" disabled selected hidden>Chose Type of Debt</option>
            <option value="Auto Loan"> Auto Loan</option>
            <option value="Student Loan"> Student Loan</option>
            <option value="Debt Card Loan"> Debt Card Loan</option>
            <option value="House Loan"> House Loan</option>
            <option value="others">others</option>
          </select>
          <p class="error"></p>
        </div>
        <div class="form-group">
          <label>Principal Amount:</label>
          <input type="number" id="principal" placeholder="Enter principal amount">
          <p class="error"></p>
        </div>
        <div class="form-group">
          <label>Annual Interest Rate :</label>
          <input type="number" id="rate" placeholder="Enter annual interest rate">
          <p class="error"></p>
        </div>
        <div class="form-group">
          <label>Monthly Payment:</label>
          <input type="number" id="payment" placeholder="Enter monthly payment">
          <p class="error"></p>
        </div>

in which i check the fields should not be empty with this peace of code

class FormValidator {
  constructor(fields) {
    this.fields = fields;
    this.isValid = true;
  }

  initialize() {
    this.validateOnEntry();
  }

  validateOnEntry() {
    let self = this;
    this.fields.forEach(field => {
      const input = document.querySelector(`#${field}`);
     
      input.addEventListener('input', () => {
        self.validateFields(input);
      });
    });
  }

  validateFields(field) {
    console.log(field.parentElement);
   const errorElement = field.parentElement.querySelector('.error');
  
    
    if (field.value.trim() === "") {
      this.setStatus(errorElement, "Please select item", "error");
      this.isValid = false; 
    } else {
      this.setStatus(errorElement, null, "success");
    }

    
    if (field.id === "principal" && isNaN(parseFloat(field.value))) {
      this.setStatus(errorElement, "Please enter principle", "error");
    }
    if (field.id === "rate" && isNaN(parseFloat(field.value))) {
      this.setStatus(errorElement, "Please enter the rate", "error");
    }
    if (field.id === "payment" && isNaN(parseFloat(field.value))) {
      this.setStatus(errorElement, "Please enter payment", "error");
    }
  }

  setStatus(errorElement, message, status) {
    if (status === "success") {
      errorElement.innerText = "";
    }

    if (status === "error") {
      errorElement.innerText = message;
    }
  }
}

const fields = ["debtType", "principal", "rate", "payment"];

const validator = new FormValidator(fields);
validator.initialize();

document.getElementById("calculateButton").addEventListener("click", function () {
  // Reset isValid before revalidation
  validator.isValid = true;

  fields.forEach(field => {
    const input = document.querySelector(`#${field}`);
    validator.validateFields(input);
  });

  if (validator.isValid) {
    addDebt(); // Call addDebt only if all fields are valid
  }
});

it work good but

when i add a new div on input tag like this

<div class="form-group">
          <label>Monthly Payment:</label>
          <div>

            <input type="number" id="payment" placeholder="Enter monthly payment">
          
          </div>
          <p class="error"></p>
        </div>

it give error so tell me how i can solve it and what should i use except field.parentElemet. this div i’m putting this div for put the svg in the input field

Sending an email in JavaScript on client side

Perhaps someone can tell me why this is happening and what I can do about it. I’m trying to send an email from the client side.

Code follows (all client-side) …

HTML:

    <button type="button" onclick="PrepEmail()">Contact Creator/Maintainer/Provider of This Data via email</button>

JS:

    <script type="text/javascript">
    function PrepEmail() {
        var DBinfo, pnt, email, version, header;
        const ws = new WebSocket('ws://localhost:3000/');

        ws.onopen = function() {
            ws.send("DBInfo");
            ws.onmessage = function(e) {
                if (e.data == -1 || e.data == -2)
                    alert ('Email address for Creator of DataBase not available.');
                else {
                    DBinfo = e.data;
                    pnt = DBinfo.indexOf("DBCreatorEmail =");
                    if (pnt == -1)
                        alert ('Email address for Creator of DataBase not available.');
                    else {
                        email = getData(DBinfo, pnt);
                        if (email == "not specified")
                            alert ('Email address for Creator of DataBase not available.');
                        else {
                            header = "mailto:";
                            header += email + "?subject=";
                            pnt = DBinfo.indexOf("DBName =");
                            if (pnt == -1)
                                header += "DataBase";
                            else {
                                header += getData(DBinfo, pnt);
                                pnt = DBinfo.indexOf("DBVersion =");
                                if (pnt != -1) {
                                    version = getData(DBinfo, pnt);
                                    header += " (" + version + ")";
                                }
                            }
                        }
                    }
                }
            }
        }
        const terminationEvent = 'onpagehide' in self ? 'pagehide' : 'unload';
        window.addEventListener(terminationEvent, (event) => {
            if (event.persisted === false) {
                // client is gone
                ws.onclose = function () { };
                ws.close();
            }
        });

        SendEmail(header);
    }

    function SendEmail (header) {
        const windowRef = window.open(header, '_blank');

        windowRef.focus();
        setTimeout(function() {
            if(!windowRef.document.hasFocus()) {
                windowRef.close();
            }
        }, 500);
    }

    function getData (DB, p) {
        var pos1 = DB.indexOf('"', p) + 1;
        var pos2 = DB.indexOf('"', pos1);
        var data = DB.substring(pos1, pos2);
        if (data == "")
            return ("not specified")
        else
            return (data);
    }

    </script>

The WebSocket call works as expected, returning:

DBName = “The Real DB”
DBVersion = “20230101”
DBCreator = “Joe Blow”
DBCreatorEmail = “[email protected]

Clicking the button gives a new tab with a completely blank page. The address line of the new tab contains “about:blank”.

However, if I make the header variable a global and refrain from passing it – the first time I click the button I get the same thing: a new tab with a completely blank page and an address line containing “about:blank”; BUT if I click the button a second time it works fine and I get the following console messages in Inspect (the messages only appear after the second click):

Storage access automatically granted for origin “moz-nullprincipal:{c3a06e0d-3847-421d-b143-df87ff91029d}” on “http://999.999.9.999:8080”.
Uncaught DOMException: Permission denied to access property “document” on cross-origin object
SendEmail http://999.999.9.999:8080/~devdir/Misc.html:65
setTimeout handler*SendEmail http://999.999.9.999:8080/~devdir/Misc.html:64
PrepEmail http://999.999.9.999:8080/~devdir/Misc.html:56
onclick http://999.999.9.999:8080/~devdir/Misc.html:1

check if two strings have similar characters

i have a database model that accepts “first_name” but I want it to accept different versions of the word first name. A user might try to save it by choosing to enter it this way “first name” or “first name ” (notice the white space between them). I want it to convert to “first_name” so it can be saved in the model