Role Select Menu discord.js v14

so, im making a sleect menu roles right, and i was wondering how would i make it so the followup text would all the role names that the person chose and not just 1 role name like how i added it to be

this is my code:

const samplemebed = new EmbedBuilder()
                .setColor("Red")
                .setTitle("test")
                .setDescription(`Hi, this is a menu test`)
                const roleadded = new Array();
                const roleremoved = new Array();

            if (interaction.values == 'server') {
                const mashiro = interaction.guild.roles.cache.get("1063076488594862130");
                if(interaction.member.roles.cache.has(mashiro.id)){
                    roleremoved.push(mashiro)
                    interaction.member.roles.remove(mashiro)
                    interaction.followUp({embeds:[samplemebed], ephemeral:true })
                  } else {
                    roleadded.push(mashiro)
                    interaction.member.roles.add(mashiro)
                    interaction.followUp({embeds:[samplemebed], ephemeral:true })
                  }
                await interaction.followUp({ embeds: [samplemebed], ephemeral: true })
            }

How to use React canary in plain HTML? Or, how can I include react-dom/client?

So for reasons that I’m not going to explain, I’m developing a React application without bundlers (e.g., webpack). So basically I just include React and ReactDOM in a couple of <script> tags in my index.html, fetching those scripts from a CDN, for example:

https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js
https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js

So far so good, but now I decided to try and experiment with Suspense and use. The latter being a canary-only feature.

The first issue I faced is how to find the latest canary build, I assume it can be found in the CHANGELOG-canary.md file. Is this reliable?

Then I just updated the above URLs in my application, using the 18.3.0-canary-546178f91-20231005 version. But now I get two errors:

  • TypeError: Cannot read properties of undefined (reading 'unstable_cancelCallback');

  • TypeError: ReactDOM.createRoot is not a function.

It seems that, now, createRoot has been moved in react-dom/client. But what does it mean in terms of CDNs? It seems I cannot find it anywhere…

How can I filter the rows’ table while typing in the searchbar using react since the beginning?

I have two components in the App file, the Header and the Table.
Based on the styleNumber, I have to filter the rows that match those styleNumber using the API endpoint.
In the Header, I have a searchbar, so when I type I can filter and get the rows with that styleNumber. So, I’m passing the styleNumber to both components and the state is in App.
My issue is that I have to type the entire styleNumber to do the rows’ table filtering.
Instead I’d like to start doing the filtering when I start typing and at the same time, the table has to show , on every input, the rows that have those numbers. It’s like a dynamic filtering as all the searchbar do, right?
How can I fix this issue?
This is my header component:

interface HeaderProps {
  styleNumber: string;
  setStyleNumber: React.Dispatch<React.SetStateAction<string>>;
}

export const Header = ({ styleNumber, setStyleNumber }: HeaderProps): ReactElement => {

  const [inputValue, setInputValue] = useState<string>('');
  const { login } = useContext(AuthorizationContext);
  const [hasFocus, setHasFocus] = useState<boolean>(false);
  const inputRef = useRef<ElementRef<'input'>>(null);
  const { palette } = useTheme();
  const theme = useTheme();
  const { instance, accounts } = useMsal();
  const isAuthenticated = useIsAuthenticated();
  const account = useAccount(accounts[0] || {});
  const [openDialog, setOpenDialog] = useState(false);
  const [openCreateCertificateDialog, setOpenCreateCertificateDialog] = useState(false);

  const iconSize = 24;
  const boxHeightSearchBar = 56;
  const fontFamilySeachBar = 18;

  // I fetch the style number in the API
const fetchCertificatesByStyleNumber = async (
  // eslint-disable-next-line @typescript-eslint/no-shadow
  styleNumber: string,
  // eslint-disable-next-line @typescript-eslint/no-shadow
  setStyleNumber: React.Dispatch<React.SetStateAction<string>>
): Promise<void> => {
  try {
    // Convert styleNumber to a number
    const numericStyleNumber = parseInt(styleNumber, 10);

    // Check if it's a valid number before making the request
    if (!isNaN(numericStyleNumber)) {
      const response = await axios.get(
        `https://hello.com/safety-certificate/certificate/certificate/${numericStyleNumber}`
      );

      const certificates = response.data.certificates;
      // eslint-disable-next-line no-console
      console.log('API Response:', response);

      // Update the parent component's styleNumber state
      setStyleNumber(styleNumber);
    } else {
      console.error('Invalid styleNumber:', styleNumber);
    }
  } catch (error) {
    console.error('Error fetching certificates:', error);
  }
};

  // this manages the input value
const handleInputChange = async (event: ChangeEvent<HTMLInputElement>): Promise<void> => {
  const value = event.target.value;
  setInputValue(value);

  // Assuming I want to fetch certificates when the input changes
  await fetchCertificatesByStyleNumber(value, setStyleNumber);
};
  // eslint-disable-next-line no-console
  console.log(inputValue);
  // // Function to clear the input
  const handleClearInput = (): void => {
    setInputValue('');
  };

const handleShowDialog = (): void => {
    setOpenDialog(true);
  };

const handleCloseDialog = (): void => {
    setOpenDialog(false);
  };

  const handleOnSignIn = (): void =>{
    login();
  };

  const handleSignOut = (): void => {
    instance.logoutRedirect({
      account,
    }).then(() => {
    })
.catch((error) => {
      // Handle logout error if needed
      console.error('Logout error:', error);
    });
  };

  const handleCreateCertificate = (): void => {
    setOpenCreateCertificateDialog(true);
  };

  return (
    <Box
      sx={{
        paddingLeft: 10,
        paddingRight: 10,
        paddingTop: 10,
        paddingBottom: 3,
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center',
      }}
    >
      <Box
        alignItems='center'
        justifyContent='center'
        display='flex'
        sx={{
          marginRight: '20px',
        }}
      >
        <Typography variant="h1">BESTSELLER</Typography>
      </Box>
      <Box sx={{ flex: '5', display: 'flex', justifyContent: 'center', marginLeft: '12px' }}>
        <TextField
          variant="outlined"
          placeholder='Search by style number'
          value={inputValue}
          sx={{
            ['& .MuiInputBase-root']: {
              height: boxHeightSearchBar,
            },
            ['& .MuiOutlinedInput-root']: {
              mt: '0 !important',
              pr: inputValue ? 2 : !hasFocus ? 5 : 0,
            },
            ['& .MuiOutlinedInput-input']: {
              fontSize: fontFamilySeachBar,
            },
          }}
          InputProps={{
            inputProps: {
              id: innerInputId,
              ref: inputRef,
            },
            startAdornment: (
              <InputAdornment position="start" sx={{ mr: 0 }}>
                <SearchIcon color={palette.text.primary} style={{ width: iconSize, height: iconSize }} />
              </InputAdornment>
            ),
            endAdornment: (
              <InputAdornment position="end">
                {inputValue && (
                  <IconButton onClick={handleClearInput}>
                    <CrossIcon
                      style={{ width: iconSize, height: iconSize }}
                    />
                  </IconButton>
                )}
              </InputAdornment>
            ),
          }}
          fullWidth
          // eslint-disable-next-line @typescript-eslint/no-misused-promises
          **onChange={handleInputChange}**
          onFocus={(): void => void setHasFocus(true)}
          onBlur={(): void => void setHasFocus(false)}
        />
      </Box>

My table component:

export interface CertificateData {
  certificateNumber: string;
  brandNumber: string;
  styleNumber: number;
  ceDocumentName: string;
  ceDocumentUrl: string;
  createdBy: string;
  changedBy: string;
  isDeleted: boolean;
  createdDate: string;
}

export interface BrandData {
  brandName: string;
  brandNumber: string;
  isDeleted: boolean;
}

interface FilteredTable {
  styleNumber: string;
}

export const TableComponent = ({ styleNumber }: FilteredTable) => {
  const [certificates, setCertificates] = useState<Array<CertificateData>>([]);
  const [brands, setBrands] = useState<Array<BrandData>>([]);
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(5);
  const isAuthenticated = useIsAuthenticated();
  const [isDialogOpen, setDialogOpen] = useState(false);
  const [selectedCertificate, setSelectedCertificate] = useState<CertificateData | null>(null);

  useEffect(() => {
    // Fetch certificates
    axios
      .get('https://hello.com/safety-certificate/certificate/certificates')
      .then((response) => {
        console.log('Certificates Response:', response.data);
        setCertificates(response.data.certificates);
      })
      .catch((error) => {
        console.error('Certificates Error:', error);
      });

    // Fetch brands
    axios
      .get('https://hello.com/safety-certificate/brand/brands')
      .then((response) => {
        console.log('Brands Response:', response.data);
        setBrands(response.data.brands);
      })
      .catch((error) => {
        console.error('Brands Error:', error);
      });
  }, []);

  const handleChangePage = (event: unknown, newPage: number) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event: React.ChangeEvent<HTMLInputElement>) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };


const handleEditIconClick = (event: React.MouseEvent<HTMLButtonElement>, certificate: CertificateData): void => {
  setSelectedCertificate(certificate);
  setDialogOpen(true);
};

// Convert styleNumber to a number
const numericStyleNumber = parseInt(styleNumber, 10);

// Filter certificates based on the numericStyleNumber
const filteredCertificates = !isNaN(numericStyleNumber)
  ? certificates.filter((certificate) => certificate.styleNumber === numericStyleNumber)
  : certificates;

return (
  <Box>
    <TableContainer component={Paper}>
      <Table sx={{ minWidth: 700 }} aria-label="safety-certificates table">
        <TableHead>
          <TableRow>
            <StyledTableCell align="right">Style Number</StyledTableCell>
            <StyledTableCell align="right">Brand Name</StyledTableCell>
            {isAuthenticated && <StyledTableCell align="right">Created By</StyledTableCell>}
            <StyledTableCell align="right">CE-document</StyledTableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {filteredCertificates.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((certificate) => (
            <StyledTableRow key={certificate.certificateNumber}>
              <StyledTableCell align="right">{certificate.styleNumber}</StyledTableCell>
              <StyledTableCell align="right">
                {brands.find((brand) => brand.brandNumber === certificate.brandNumber)?.brandName ?? 'Brand Not Found'}
              </StyledTableCell>
              {isAuthenticated && (
                <StyledTableCell align="right">{certificate.createdBy}</StyledTableCell>
            )}
              <StyledTableCell align="right">
                <Box>
                  <a
                    href={`https://buying-dev.bestseller.com/safety-certificate/certificate/certificatePdf/${certificate.certificateNumber}`}
                    target="_blank"
                    download={certificate.ceDocumentName}
                    rel="noreferrer"
                    style={{ color: 'black', textDecoration: 'none' }}
                  >
                    <span>{certificate.ceDocumentName}</span>
                  </a>
                  {isAuthenticated && (
                    <IconButton onClick={(event): void => void handleEditIconClick(event, certificate)}>
                      <EditIcon />
                    </IconButton>
                )}
                </Box>
              </StyledTableCell>
            </StyledTableRow>
        ))}
        </TableBody>
      </Table>
      <TablePagination
        rowsPerPageOptions={[5, 10, 25, 50]}
        component="div"
        count={certificates.length ?? 0}
        rowsPerPage={rowsPerPage}
        page={page}
        labelRowsPerPage="Documents per page"
        onPageChange={handleChangePage}
        onRowsPerPageChange={handleChangeRowsPerPage}
      />
    </TableContainer>

My app file:

const [styleNumber, setStyleNumber] = useState<string>('');

  return (
    <MsalProvider instance={msalService.msalInstance}>
      <AuthenticationProvider>
        <ThemeProvider theme={theme}>
          <Header styleNumber={styleNumber} setStyleNumber={setStyleNumber} />
          <TableComponent styleNumber={styleNumber} />
        </ThemeProvider>
      </AuthenticationProvider>
    </MsalProvider>

  );

Making simple digital clock page in React (facing errors)

I am making a simple clock, but want data to be in a single object (Rather than making 3 different states for hours, minutes and seconds. This way its more meaningful. But I am getting error. Pls help.

import React from "react";
import { useState } from "react";

export default function Ex6() {

    const date = new date();
    const [time, setTime] = useState({hours:'00', minutes:'00', seconds:'00'});

    const updatetime = () => {
        setTime({hours:date.getHours(), minutes:date.getMinutes(), seconds: date.getSeconds()});
    }

    updatetime();

    return (
        <div>
            <p>{time.hours}:{time.minutes}:{time.seconds}</p>
        </div>
    )
}

Error:

enter image description here

How can I update the live gold and silver prices based on the customer’s commercial addition? [closed]

I greet you with respect, gentlemen

Let me explain, later I will put the code here in the meantime.

On the WordPress platform in WooCommerce I added 120+ products (gold and silver)

I made a java script with someone’s help based on an API that converts from EURO to RON. The script has the following location: public_html/wp-content/themes/name of the theme/js/custom-scripts.js

The code is over here:

// Scriptul JavaScript cu functia de conversie

// Functia pentru a face cereri catre API folosind AJAX
function fetchMetalPrices() {
   // Foloseste AJAX pentru a face cererea catre API
   var xhr = new XMLHttpRequest();
   var apiKey = '24cbf4a48e25885d3b8ff42474c80747';
   xhr.open('GET', 'https://api.metalpriceapi.com/api/v1/latest', true);
   xhr.setRequestHeader('x-access-token', apiKey);
   xhr.onload = function () {
       if (xhr.status == 200) {
           // Proceseaza datele primite de la API
           var data = JSON.parse(xhr.responseText);
           // Actualizeaza preturile pe pagina
           updatePrices(data);
           // Calculeaza si actualizeaza preturile in RON
           updatePricesInRON(data);
       } else {
           console.error('Cererea catre API a esuat. Cod de eroare: ' + xhr.status);
       }
   };
   xhr.send();
}

{

}
async function getExchangeRate() {
        const apiKey = "69b2d358023e988b804b4e61aca6413d";
         const apiUrl = https://open.er-api.com/v6/latest/EUR?apikey=${apiKey};
        try {
          const response = await fetch(apiUrl);
          const data = await response.json();
          debugger;
          if (response.ok) {
            const eurToRonRate = data.rates.RON;
            //console.log(EUR to RON exchange rate: ${eurToRonRate});
            return eurToRonRate;
          } else {
            console.error(Error: ${data.error});
          }
        } catch (error) {
          console.error("Error fetching exchange rate:", error.message);
        }
      }

     
 });


// Functia pentru a actualiza preturile pe pagina
function updatePrices() {
   // Verificăm dacă data.gold și data.silver există înainte de a încerca să accesăm 'price'
   let data;
    getExchangeRate().then((exchangeRate) => {
        data = exchangeRate.toFixed(3);
         //parseFloat(exchangeRate.toFixed(3))
    }
   if (data && data.gold && data.gold.price && data.silver && data.silver.price && data.exchange_rates && data.exchange_rates.EUR) {
       // Actualizeaza elementele HTML cu noile preturi in EURO si DOLARI
       document.getElementById('goldPriceEUR').innerText = data.gold.price + ' EUR';
       document.getElementById('silverPriceEUR').innerText = data.silver.price + ' EUR';
       document.getElementById('goldPriceUSD').innerText = data.gold.price * data.exchange_rates.EUR + ' USD';
       document.getElementById('silverPriceUSD').innerText = data.silver.price * data.exchange_rates.EUR + ' USD';
   } else {
       console.error('Datele primite de la API lipsesc sau sunt definite incorect.');
   }
}

// Functia pentru a calcula si actualiza preturile in RON
function updatePricesInRON(data) {
# Conversie din EURO/DOLARI in RON folosind o rata de schimb fictiva (poate fi ajustata)
   var exchangeRateRON = 4.9; // Exemplu de rata de schimb
   var goldPriceRON = data.gold.price * exchangeRateRON;
   var silverPriceRON = data.silver.price * exchangeRateRON;

   // Actualizeaza elementele HTML cu noile preturi in RON
   document.getElementById('goldPriceRON').innerText = goldPriceRON.toFixed(2) + ' RON';
   document.getElementById('silverPriceRON').innerText = silverPriceRON.toFixed(2) + ' RON';
}

// Facem cereri periodice catre API pentru a mentine actualizate preturile
setInterval(fetchMetalPrices, 60000);  // Facem cereri la fiecare 60 de secunde (poate fi ajustat)

Now what must be done.

From the database with the added products, depending on the weight of each one, a calculation should be made and the final price displayed for each product
For gold, it must be as follows:

Gold product depending on the weight + commercial surcharge imposed by the customer = final price

For silver it must be as follows:

The weight of the silver product + commercial surcharge imposed by the customer + VAT 19% = final price

with the help of a friend who wrote the java script for me, I don’t know what to do next, how to connect to the database for each individual product depending on the weight to make a calculation for me as I specified above.

how to override javascript array of objects?

I am trying to override item and add new item/object in given array of objects .

here is my code

const replaceOrAdd = (sourceArray, overrideArray, key = "name") => {
  const existingIndex = sourceArray.findIndex(
    (item) => item[key] === overrideArray[key]
  );

  if (existingIndex >= 0) {
    sourceArray[existingIndex] = overrideArray;
  } else {
    sourceArray.push(overrideArray);
  }

  return sourceArray;
};

const source = [
  {
    label: "WORK_ORDER_NUMBER",
    name: "job_order_number",
    visible: true,
  },
  {
    label: "WORK_ORDER_VALIDITY_DATE",
    name: "validity_date",
    visible: true,
  },
  {
    label: "BOOKING_ID",
    name: "booking_number",
    visible: true,
  },
  {
    label: "BOOKING_TYPE",
    name: "booking_type",
    rules: {},
    visible: true,
  },
];

const replace = [
  {
    label: "WORK_ORDER_NUMBER",
    name: "job_order_number",
    visible: false,
  },
  {
    label: "BOOKING_ID",
    name: "booking_number",
    visible: false,
  },
  {
    label: "XXXXX",
    name: "XXXXXX",
    visible: false,
  },
];

replaceOrAdd(source, replace);

console.log(source);

Expected output :

 [
  {
    label: "WORK_ORDER_NUMBER",
    name: "job_order_number",
    visible: false,
  },
  {
    label: "WORK_ORDER_VALIDITY_DATE",
    name: "validity_date",
    visible: true,
  },
  {
    label: "BOOKING_ID",
    name: "booking_number",
    visible: false,
  },
  {
    label: "BOOKING_TYPE",
    name: "booking_type",
    rules: {},
    visible: true,
  },
  {
    label: "XXXXX",
    name: "XXXXXX",
    visible: false,
  },
];

I am trying to override in the source array if “name” key match .. if they there is extra object in replace object . I am trying to add that object.

Here in example name: “job_order_number”, , name: “booking_number”, match .. I want to override this object and add this object name: “XXXXXX”, as it is not found

I can’t add the method by using addEventListner in Angular Project

getCheckStatus(checkStatus: string) {
    let statusClass = '';
    if (checkStatus === 'Completed') {
      statusClass = 'mat-focus-indicator btn--primary__button mat-raised-button mat-button-base';
    } else {
      statusClass = 'mat-focus-indicator mat-raised-button mat-button-base mat-button-disabled';
    }
    const button = document.createElement('button');
    button.className = statusClass;
    button.textContent = 'Close';
    button.addEventListener("click", () => this.popUp());
    const container = document.createElement('div');
    container.appendChild(button);    
    return container.innerHTML;
  }
popUp() {console.log('Finally this is working');}

I’m trying to call this method by adding addEventListner in my Angular Project. But this is not working, this popUp() method is never called.

MyAssumption: this is a JavaScript code, but we have to write in typescript in Angular, but I can’t find any different syntax especially for typescript.

Javascript function to identify duplicates and ignore duplicates only in a certain thing

This below js code checks for duplicate aliases in html code given in textarea and if the alias is repeated it shows duplicate alias found error I want to ignore and don’t show duplicate error only in this case

`<!--[if mso]>
    <a href="https://www.w3schools.com" alias="test">Visit W3Schools</a> 
<![endif]-->
`
`<a href="https://www.w3schools.com" alias="test">Visit W3Schools</a>
`
It should not display duplicate alias only if it is in 
`<!--[if mso]>
    
<![endif]-->
`

Js code

    const checkAliasInNode = (node) => {
      const alias = node.getAttribute("alias");
      const href = node.getAttribute("href");
      if (href === null) {
    // Handle the case where href is null (or undefined) separately
    console.error("Href attribute is null or undefined for the following node:", node);
    return;
  }
      if (alias === null || alias.trim() === "") {
        missingAliases.push(`<span style="color: red;">Missing alias for link with href = "${href}" </span>`);
      } else if (!/^[a-zA-Z0-9_]+$/.test(alias) || alias.endsWith("-")) {
        invalidAliases.push(`<span style="color: #FF641C;">Invalid alias "${alias}" for link with href = "${href}" </span>`);
      } else if (aliases.has(alias)) {
        duplicateAliases.push(`<span style="color: #FF641C;">Duplicate alias "${alias}" found for link with href = "${href}" </span>`);
      } else {
        aliases.add(alias);
      }
     };

It should not display duplicate alias only in mso it can be excused

Why dotenv not able to load environment variables?

I have the following directory structure: enter image description here

I am using dotenv to load environment variables but its not loading them.It gives undefined even though I have defined them in the .env file.

The code in index.js is here:

enter image description here

I’ve even tried the following for requiring:

require('dotenv').config();

require('dotenv').config({path:'C:UsersxuiosDesktopAirlineManagementProjectFlightsAndSearchsrc.env'}); // absolute path

require('dotenv').config({path:'FlightsAndSearchsrc.env'}); //relative path

However it still doesnt load the env variables defined as :enter image description here

How to launch IntelliJ IDEA

How to run IntelliJ IDEA using .exe or .the bat file either .py.
I tried to run using .bat a c .exe hasn’t figured out how yet.I have windows.
You can also help to run it using some program from github.
If someone can help, please do it.
I also tried to run it through java, but I also failed.java -noverify -Xmx2048M -Djava.library.path=.natives;. -cp .minecraft.jar net.minecraft.client.main.Main --username %Nick% User43 854 --height 480 --version Optifine --gameDir C:Minecraftgame --assetsDir .assets --assetIndex 1.12 --uuid N/A --accessToken 0 --userType mojang

How to pin the top header row showing column names in this bootstrap-vue table?

I have a bootstrap-vue table that looks like this;

enter image description here

Here is the code;

<template>
  <div>
    <b-table hover :items="items"></b-table>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        items: [
          { age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
          { age: 21, first_name: 'Larsen', last_name: 'Shaw' },
          {
            age: 89,
            first_name: 'Geneva',
            last_name: 'Wilson',
            _rowVariant: 'danger'
          },
          {
            age: 40,
            first_name: 'Thor',
            last_name: 'MacDonald',
            _cellVariants: { age: 'info', first_name: 'warning' }
          },
          { age: 29, first_name: 'Dick', last_name: 'Dunlap' }
        ]
      }
    }
  }
</script>

Suppose the table has many rows. I would like to pin the top header row such that when I scroll down the table, the header row showing the column names remains at the top. This makes the table more readable.

The table code was provided in bootstrap-vue documentation.

https://bootstrap-vue.org/docs/components/table

I am using Vue v2.6 and BootstrapVue.