prompt box with choices [closed]

var prompt() = prompt('Enter 1, 2, 3, or 4:')
if 1 goto https: //bpay.com.au/
<button type="button" onclick="prompt()">GO TO OTHER PAGES</button>

<script src="../js/jsbass1.js">
</script>

i am trying to create a prompt box when i click on a button in my html that gives me choices to other sites ?

  1. bpay
  2. afterpay
  3. applepay
    enter your selection , enter you number and takes you to the site.

so you enter the number and it directs you to the site very new at js just struggling a bit any help would be appreciated

I want to click a button on my form that creates a prompt with choices to others sites when you enter the number of desired site it directs you to that site?

i have the button but cant get the right code to create the selection criteria and then the loop that takes you to the site?

as you can see I’m lost ??

Is it possible to make my own callback for a certain static variable?

Sometimes function has built-in callback function, “This function is called when something happens”

In my case, I want to make callback function which is called after a certain static value is changed

For example,

class MyVariable(){
    static myVal = 1;
}


const FileUploader = (props) =>{
    myAlert(){
       console.log("val is changed!"); 
    }
    changeValue2(){
      MyVariable.myVal = 2;
      myAlert();
      
    }
    changeValue3(){
      MyVariable.myVal = 3; 
      myAlert();
    } 
    changeValue4(){
      MyVariable.myVal = 4; 
      myAlert();
    } 
}

I want to call myAlert() after myVal is changed.

so currently I write myAlert() third times.

I wonder is it possible to do this automatically like making the callback which is called when myVal is changed

Is there any way for this idea? I am using React

Discord:interaction panel

My code:

const {
  ActionRowBuilder,
  ButtonBuilder,
  EmbedBuilder,
  ButtonStyle,
} = require('discord.js');

async function listRatingButton(interaction, roleId = '1060382379723731097') {
  const guild = interaction.guild;
  const role = await guild.roles.fetch(roleId);

  if (!role) {
    return interaction.reply(
      'Не удалось найти роль. Пожалуйста, проверьте ID роли.',
    );
  }

  const membersWithRole = guild.members.cache.filter((member) =>
    member.roles.cache.has(roleId),
  );
  const membersArray = Array.from(membersWithRole.values());

  const pages = [];
  const membersPerPage = 15;

  for (let i = 0; i < membersArray.length; i += membersPerPage) {
    pages.push(membersArray.slice(i, i + membersPerPage));
  }

  const row = new ActionRowBuilder().addComponents(
    new ButtonBuilder()
      .setCustomId('previous')
      .setEmoji(':previous:1102791113988898837')
      .setStyle(ButtonStyle.Primary),
    new ButtonBuilder()
      .setCustomId('next')
      .setEmoji(':next:1102791111774306365')
      .setStyle(ButtonStyle.Primary),
  );

  await interaction.reply({
    embeds: [getEmbed(pages[0], role.name, 0, membersPerPage)],
    components: [row],
  });

  const filter = (i) => i.user.id === interaction.user.id;
  const collector = interaction.channel.createMessageComponentCollector({
    filter,
    time: 60000,
  });

  let currentPage = 0;
  collector.on('collect', async (i) => {
    try {
      if (i.customId === 'previous' && currentPage !== 0) {
        currentPage--;
      } else if (i.customId === 'next' && currentPage < pages.length - 1) {
        currentPage++;
      }
      if (!i.deferred && !i.replied) {
        await i.deferUpdate();
        await i.editReply({
          embeds: [
            getEmbed(
              pages[currentPage],
              role.name,
              currentPage,
              membersPerPage,
            ),
          ],
          components: [row],
        });
      }
    } catch (error) {
      console.error(error);
    }
  });
}

function getEmbed(page, roleName, pageNumber, membersPerPage) {
  let memberList = '';
  for (let i = 0; i < page.length; i++) {
    memberList += `${pageNumber * membersPerPage + i + 1}. ${
      page[i].user.tag
    }n`;
  }

  const embed = new EmbedBuilder()
    .setTitle(`Участники с ролью ${roleName}`)
    .setDescription('```fixn' + memberList + '```')
    .setColor('#0099ff');

  return embed;
}

module.exports = { execute: listRatingButton };

I have a panel with buttons, if I click a single button and then another, an error is shown:

DiscordAPIError[40060]: Interaction has already been acknowledged.
at handleErrors (C:UsersuserDesktopDiscord Bot Version 1.0.0 (Beta)[email protected]:640:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async BurstHandler.runRequest (C:UsersuserDesktopDiscord Bot Version 1.0.0 (Beta)[email protected]:736:23)
at async REST.request (C:UsersuserDesktopDiscord Bot Version 1.0.0 (Beta)[email protected]:1387:22)
at async ButtonInteraction.deferUpdate (C:UsersuserDesktopDiscord Bot Version 1.0.0 (Beta)node_modulesdiscord.jssrcstructuresinterfacesInteractionResponses.js:200:5)
at async InteractionCollector.<anonymous> (C:UsersuserDesktopDiscord Bot Version 1.0.0 (Beta)buttonsmoderateslistRaiting.js:48:9) {

requestBody: { files: undefined, json: { type: 6 } },
rawError: {
message: ‘Interaction has already been acknowledged.’,
code: 40060
},
code: 40060,
status: 400,
method: ‘POST’,
url: ‘https://discord.com/api/v10/interactions/1107914467368521809/aW50ZXJhY3Rpb246MTEwNzkxNDQ2NzM2ODUyMTgwOTo0S2p0RTFmRkRKcE8xZTR2YnRvT1U2WnRSSmluS21qTjlEWUxoQ05INFZrWUFBNTV2aXhnRjRIYWV2WVhmUUNJMHZlWVQwenNBdDBEY1pRWHUzS3Z4UEM5dXB0NWVPbm1mdlVRTlBHR1RxYmJpV3hvOWV2czFRMndsU25WWFRkUQ/callback’
}

What is wrong with this inverse FFT implementation

I am using the following implementation of an inverse Fast Fourier transform (FFT) for images in which the image of size N by N is stored in a vector of length N x N (with N a square number). When I feed this implementation a matrix of zeros except two 1s, one a few rows above the center and symmetrically below the center, the inverse is correctly an image with vertical bands whose frequency matches the position of the 1s.

However, when the 1s are on the left and on the right of the center, I get horizontal bands, but they are not perfectly horizontal. They have a very small slope. When I do exactly the same in Mathematica with the build-in InverseFourier function, the bands are very precisely horizontal.

Is there something wrong in the JavaScript implementation below?

function invFFT_radix2(out, start, input, N, offset, s ) {
    if (N === 1) {
        out[start] = input[offset];
    } else {
        invFFT_radix2(out, start,     input, N/2, offset,   2*s);
        invFFT_radix2(out, start+N/2, input, N/2, offset+s, 2*s);
        for (var k = 0; k < N/2; k++) {
            var twiddle = cisExp(2*Math.PI*k/N);
            var t = out[start+k];
            out[start+k]     = t.plus ( twiddle.times(out[start+k+N/2]) );
            out[start+k+N/2] = t.minus( twiddle.times(out[start+k+N/2]) );
        }
    }
}

called with

invFFT_radix2(out, 0, input, input.length, 0, 1 )

in which input is the input vector, and out contains the result. All the entries are Complex numbers (as per this response) and the function cisExp is defined as

function cisExp(x) { // e^ix = cos x + i*sin x
    return new Complex(Math.cos(x), Math.sin(x));
}

PDF_LIB Image Clipping with drawEllipse

I am currently using pdf-lib version 1.17.1 in a ReactJS application to generate some documents. Currently I have it writing text into the page, as well as embedding an image and having it show. However, I need to crop the image into a circle and it’s proving difficult with various methods not working from the library like other solutions have suggested:
https://github.com/Hopding/pdf-lib/issues/160#issuecomment-523205152
fit image in ellipse in pdflib

The code I am currently running looks like this:

        // Define the ellipse parameters
        const ellipseX = 338 + (414 / 2);  // X-coordinate of the ellipse center
        const ellipseY = (currentY + 95) - (414 / 2);  // Y-coordinate of the ellipse center
        const ellipseWidth = 200;  // Width of the ellipse
        const ellipseHeight = 200;  // Height of the ellipse
        
        // 
        agentBioPage.pushOperators(
            pushGraphicsState(),
            ...drawEllipse({
                x: ellipseX,
                y: ellipseY,
                xScale: ellipseWidth,
                yScale: ellipseHeight,
                rotate: degrees(0),
                borderColor: rgb(0, 0, 0),  // Border color (black)
                borderWidth: 1,  // Border width (1 point)
                opacity: 1,  // Opacity (fully opaque)
                blendMode: 'Normal'  // Blend mode (normal)
            }),
            clip(),
        )
        
        // Draw the image onto the page
        agentBioPage.drawImage(embeddedProfilePicture, {
            x: ellipseX - ellipseWidth,
            y: ellipseY - ellipseHeight,
            width: ellipseWidth * 2,
            height: ellipseHeight * 2,
        })

        // 
        agentBioPage.pushOperators(popGraphicsState())

It’s drawing on the circle, drawing on the image, but just not clipping the image at all (the ellipse is sat behind the image here):

enter image description here

Any advice, tips and tricks would be greatly appreciated!

Cheers

I am trying to find about carers in javascript

Is a career in tech still worth it, i find that coding is getting more complex and I feel like quitting after few years in working in the industry. Maybe Donald Trump is right about we not depending on technology, the stuff is getting more complex for me. What do you guys advise?

I tried reading a couple of books

Problems with vite.config.ts and Contentful

I am building a React App. I installed aws-amplify @aws-amplify/ui-react, and then updated my vite.config.ts as follows:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  define: {
    'process.env': process.env,
    'global': {}
  },
  plugins: [react()],
  resolve: {
    alias: [
      {
        find: /^~.+/,
        replacement: (val) => {
          return val.replace(/^~/, "");
        },
      },
      {
        find: './runtimeConfig', replacement: './runtimeConfig.browser',
      }
    ],
  },
})

However, after doing so, I ran npm run build, which could not be completed, as Contentful dependancy crashed in the project, with the following message:
‘Could not resolve “./create-{}-options” from “node_modules/contentful/dist/es-modules/contentful.js’

I’ve been searching for hours any solution without success.

Does anyone know what’s going on or any idea that can help to solve this?
Thanks in advance for your help.

In this promise pool code, when the base case hits here do recursively called functions pop back from the callstack or not

In this code what happens to the previously called helper functions which are in the call stack when base case hits(outer promise is resolved), do they pop from call stack one by one or not.

when inside the helper function when every promise is waiting in the
microtask queue, once time comes it is pushed to the call stack what happens to the chained recursion helper calls which were calling itself again and again do the chain breaks.

var promisePool = async function (functions, n) {
  return new Promise((resolve) => {
    let inProgressCount = 0;
    let functionIndex = 0;
    function helper() {
    // base case
      if (functionIndex >= functions.length) {
        if (inProgressCount === 0) resolve();
        return;
      }

      while (inProgressCount < n && functionIndex < functions.length) {
        inProgressCount++;
        const promise = functions[functionIndex]();
        functionIndex++;
        promise.then(() => {
          inProgressCount--;
          helper();
        });
      }
    }
    helper();
  });
};

How to login to a react application using an API key for user authentication?

I have to use the API-Football in my application in react.
The application must have a Login screen and a Dashboard screen (which must be shown after login). To access the application, the user must create an account on API-Football, thus, he will have access to the X-RapidAPI-Key to allow access to the API.

In the login screen, the user must insert the authentication API key provided by API-Football;
Note: The application must use the API key informed by the user to make requests to the API

User and password will not be required to login, only the API key;

It must not be possible to login with an invalid API key;

It should not be possible to access the dashboard page without the user logging in;

I tried to make a login screen to receive the API key in an input, to check if it is valid, however, it did not work.

import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';

const Login: React.FC = () => {
  const [apiKey, setApiKey] = useState('');
  const [error, setError] = useState('');
  const history = useHistory();

  const handleLogin = async () => {
    const isValidApiKey = await validateApiKey(apiKey);
    if (isValidApiKey) {
      sessionStorage.setItem('apiKey', apiKey);
      history.push('/dashboard');
    } else {
      setError('API key no exist');
    }
  };

  return (
    <div>
      <h1>Login</h1>
      {error && <p>{error}</p>}
      <input
        type="text"
        value={apiKey}
        onChange={(e) => setApiKey(e.target.value)}
        placeholder="API Key"
      />
      <button onClick={handleLogin}>Login</button>
    </div>
  );
};

export default Login;
import axios from 'axios';

const validateApiKey = async (apiKey: string): Promise<boolean> => {
  try {
    const response = await axios.get('api-football', {
      headers: {
        'X-RapidAPI-Key': apiKey,
        'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com',
      },
    });
    if (response.status === 200 && response.data && response.data.api) {
      return true; // API key validates
    } else {
      return false; // A API invalid
    }
  } catch (error) {
    return false; // A API key invalid or error in call
  }
};

OBS: The API expects the API key to be included in all API requests to the server in a header similar to the following:

Be sure to replace XxXxXxXxXxXxXxXxXxXxXxXx with API key.

EXAMPLE:

import axios from 'axios';

const options = {
  method: 'GET',
  url: 'https://api-football-v1.p.rapidapi.com/v3/timezone',
  headers: {
    'X-RapidAPI-Key': 'xxxxXXXXxxxxxXXXXXxxxxxXXXXXxxxxXXXX',
    'X-RapidAPI-Host': 'api-football-v1.p.rapidapi.com'
  }
};

try {
    const response = await axios.request(options);
    console.log(response.data);
} catch (error) {
    console.error(error);
}

URL: https://rapidapi.com/api-sports/api/api-football

how can I remove white area and how can I make single tile?

enter image description here
I’m rendering tiff image using geoserver, and I render map using react-leaflet.
I want remove white area and tiles not separate when I zoom in.

    const wmsLayerParams = {
        url: url,
        layers: "gis:VH_dB",
        transparent: true,
        quantity: 0,
        opacity: 1,
        format: "image/png",
        interplation: "bilinear",
    }

this is my wms LayerParams.

I don’t know how to fix params

Socket.io not using specified endpoint in front end

I am trying to use socket.io to listen for WS messages from the BE. The BE is not using socket.io to send WS messages. Perhaps this is my problem? I create a connection:

import { io } from "socket.io-client";

const socket = io(`http://localhost:8090/v1/my-endpoint/ws`, {
  autoConnect: false,
});

Then I connect to that endpoint and attach some listeners:

const onConnect = () => {
  console.log("Connected to APOTs WS");
};
const onDisconnect = () => {
  console.log("Disconnected from APOTs WS");
};
const onMessage = (e) => {
  console.log(e);
};

socket.on("connect", onConnect);
socket.on("disconnect", onDisconnect);
socket.on("message", onMessage);
socket.on("connect_error", (err) => {
  console.log(`connect_error due to ${err.message}`);
});

socket.connect();

When looking at console, I see lots of attempts to connect to a socket, but its not using the endpoint I specified, but rather some endpoint with /socket.io in it:

enter image description here

I don’t get it. Is socket.io-client only meant for connecting to sockets specifically created with socket.io on the back end? Can I not use it to connect to any generic websocket protocol available at a given endpoint? If so, what am I doing wrong in my setup?

Problrm width a jquery form

I realized a overlay form but i am width problem to sumbit
I post the link to the form and the jquery code

Link to the page: http://www.all-forevents.com/test/provaajax.htm

$("#entra").click (function(e){


e.preventDefault();
//recupera tutti i valori del form automaticamente
var dati = $("#area-login").serialize();
var msg = "Invio con successo";

//questo alert per capire come vengono passati i dati
//alert(dati);

//invio
$.ajax
({
type: "POST",
url: "inviaok.asp",
cache: false,
contentType:false,
processData:false,  
dataType: 'text',
data: dati,
dataType: "html",
success: function(xmlHttp) {
       if (xmlHttp.code != 200) 
{top.location.href = '/default.asp';}

    }

 // error: function()
// {alert("Chiamata fallita, si prega di riprovare...");}

});//ajax

});//bottone click

The results that i ecpect can be 2:

1 – I want that the user see the message that It is ok
2 – I want a redirect to a specified page

Alpine JS change data from within a js function

I’m trying to call a function ‘openBag();’ from a larger js file once it has finished loading a product into the bag.

I have this code where ‘changeData’ keeps coming back as undefined.

Is this the correct approach? Do I have something wrong, or should I approach this in a different way?

import Alpine from 'alpinejs'
window.Alpine = Alpine

window.addEventListener('alpine:init', () => {
    Alpine.data('setData', () => ({
        showDrawer:false, drawerTab:'', showNav:false, showBack:false, showMenu:false, showFilters:false, isMobile:(window.innerWidth < 480) ? true : false
    }))
})

Alpine.start()

window.openBag = function() {
    const changeData = Alpine.data('setData');
    if (changeData) {
        changeData.showDrawer = true,
        changeData.drawerTab = 'bag'
    } else {
        console.log(changeData);
    }
}

MongooseServerSelectionError: getaddrinfo ENOTFOUND undefined

tengo un problema al conectar una base a una base de datos en mongo y NodeJS, me tira el siguente error

MongooseServerSelectionError: getaddrinfo ENOTFOUND undefined
    at _handleConnectionErrors (C:UsersbenjaDocumentsProyectosBoutique-project-dbnode_modulesmongooselibconnection.js:792:11)        
    at NativeConnection.openUri (C:UsersbenjaDocumentsProyectosBoutique-project-dbnode_modulesmongooselibconnection.js:767:11)       
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at runNextTicks (node:internal/process/task_queues:64:3)
    at listOnTimeout (node:internal/timers:533:9)
    at process.processTimers (node:internal/timers:507:7) {
  reason: TopologyDescription {
    type: 'Unknown',
    servers: Map(1) { 'undefined:27017' => [ServerDescription] },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: null,
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined
}

el codigo de mi conexion a mi base de datos es el siguiente:

const mongoose = require('mongoose');

const {ARIA_BIT_MONGODB_HOST, ARIA_BIT_MONGODB_PORT,ARIA_BIT_MONGODB_DATABASE} = process.env;
const MONGODB_URI = `mongodb://${ARIA_BIT_MONGODB_HOST}/${ARIA_BIT_MONGODB_DATABASE}`;


mongoose.connect(MONGODB_URI,{
    useNewUrlParser: true,
    useUnifiedTopology: true,
})
.then(db => console.log('Database connected'))
.catch(err => console.log(err));

mis variables que utilizo en el archivo .env son las siguientes:

ARIA_BIT_MONGODB_HOST=127.0.0.1
ARIA_BIT_MONGODB_PORT=27017
ARIA_BIT_MONGODB_DATABASE=aria-bit

el arhicov js para lanzar la aplicacion es el siguiente:

const app = require('./server');
require('./database');
require('dotenv').config;

app.listen(app.get('port'), () => {
    console.log('Server on port ', app.get('port'));
})

agredeceria sus consejos del porque me sucede esto, estoy en aprendizaje con mongo y NodeJS,Muchas gracias