how to get output 2 with Fibonacci number in array

function isPerfectSquare(num)
{
    let n = parseInt(Math.sqrt(num));
    return (n * n == num);
}

// Function to check
// if the number is
// in Fibonacci or not
function checkFib(array, n)
{
    let count = 0;
    for (let i = 0; i < n; i++)
    {
        if (isPerfectSquare(5 * array[i] *
                                array[i] + 4) ||
            isPerfectSquare(5 * array[i] *
                                array[i] - 4))
        {
            console.log(array[i] + " ");
            count++;
        }
    }
    if (count == 0)
        console.log("None present + <br>");
}

// Driver Code
let array = [15, 1, ,3];
let n = array.length;

checkFib(array, n);

that is function to check nearest fibonaci how to get the output

Question : with Array [ 15, 1, 3 ] Expected Output is 2 because nearest fibonacci of 19 is 21 = 2

Thank u for help. 🙂

How do I make a button that will download a file

I’m attempting to make a button that will download an image file upon pressing, but what I’ve made will only take me to the file itself.

Html:

<button onclick="file()">Click me, i'll download an image</button>

Javascript:

function file() {
    const anchor = document.createElement("a");
    anchor.href = "dingus.png";
    anchor.download = "dingus.png";
    document.body.appendChild(anchor);
    anchor.click();
    
}

How save/get multiple checkboxes array values as a JSON in laravel-8

my problem is simply saving and editing array data

Like this, for example:

[“name1″,”name2″,”name3″,”name4”]

I want, for example, if it is in the “column_name” field: [“name1″,”name2”]

Checkboxes 1 and 2 is checked.

I use JSON to edit and save

Edit JS:

$(“input[name=’column_name’]”).val(res.column_name);

Save JS:

formData.append(“column_name”, $(“input[name=’column_name”).val()));

i hope it is clear.

Function being executed twice when it shouldn’t be

Im making a cookie clicker like game to practice Javascript. The point of the function addFarm(farmAdd) is to add a certain amount of farms when called. Using console.log, i have found that the setinterval executes twice every 1000ms instead of once every 1000ms leading to the banana count getting +30 added every second instead of +15. I imagine it is because the addFarm function is called twice in the code but the first time it is in an if statement that shouldnt be getting executed since the addFarm1 var is set to true and not false.

I am new to javascript (about a week) and cant figure out why it does this. Any help would be appreciated

function addFarm(farmAdd) { // this is the function
    farmCount = farmCount + farmAdd;
    farmAdd = 0;
    farmIncrement = farmCount * 5;

    farmCountText.textContent = farmCount + ' (+' + farmIncrement + ')';    

    setInterval(function() { // this part is executed twice every 1000ms
        bananaCount = bananaCount + farmIncrement;
        bananaCountText.textContent = bananaCount;
        console.log(farmIncrement);
    }, 1000);
}

function bananaClick() {
    bananaCount += 1;

    if (bananaCount > 10000) {
        bananaClicked.textContent = 'Golden Banana Bunch (+15)';
        banana.src = 'images/banana6.png';
        countByTwo(3);

        if (!addFarm1) {
            addFarm(1);
            addFarm1 = true;
        }
    }

    if (bananaCount > 15000) {
        bananaClicked.textContent = 'Mario Banana (+23)';
        banana.src = 'images/banana7.png';
        countByTwo(4);

        if (!addFarm2) {
            addFarm(2);
            addFarm2 = true;
        }
    }

    bananaCountText.textContent = bananaCount;
}

there is more code but i havent added it so i can make the post shorter but if you need more context then ask please 🙂

Marker Popover with React Ace

I am looking to create popovers on top of markers using React Ace. I found an example based on Ace Editor here
https://codepen.io/oatssss/pen/oYxJQV to create marker popovers but have not been able to make the events work correctly with the React wrapper (React Ace)

The example shared above includes creating markers addDynamicMarkers, which is already done by React Ace through the markers prop. However the mousenter on the specific markers HTML is posing a challenge.

https://codesandbox.io/s/immutable-waterfall-d9x5u9 (react ace with markers)

Is there an example on these lines or hints from someone who has worked on a similar outcome is highly appreciated.

How to push objects to an array in Vue 3 while i < 5

I am attempting to set up a button function in Vue 3 that handles pushing objects to an array in a for loop, while i < 5:

const addFeatureObjs = () => {
  for (let i = 0; i < 5; i++) {
    // featureObjArray.value.push({ id: null, feature: null })
    featureObjArray.value[i] = { id: null, feature: null }
  }
}

So far, I have a for loop set up to create 5 instances of the object while i < 5. However, I wish to set up this function so that each button click call to addFeatureObjs creates a new object one click at a time until 5 are created, instead of calling addFeatureObjs to create the 5 objects all at once. How can I go about setting up this function, for loop, and array to enable creating each object one at a time, until 5 are created?

With setTimeOut, why it console 4, 5 times ? javascript

If I run this code then it console 4 at 5 time, can anyone explain why it is happening ?

let number = 1;

for (var i=0; i<5; i++){
  number=i;
  setTimeout(()=>{
    console.log(number)
  },1000)
}

Also if I modify this to as below then output is 5 times 5 ?

for (var i=0; i<5; i++){
  setTimeout(()=>{
    console.log(i)
   },1000)
 }

And why it prints 0 to 5 when we use let like

    for (let i=0; i<5; i++){
  setTimeout(()=>{
    console.log(i)
   },1000)
 }

How do I make a DIV set to style.display = “none” but only mobile version?

I have a div so I want to have display=”none”, but it’s only show in responsive mode, so I have this media-query, but i try to change the property “block” to “none” when the user click in close

function hiddenModalAlertTwo () {
  var _modalTwo = document.getElementById("ModalAlertThree");
  var closeAlertTwo =  document.getElementsByClassName("icon-close");
            
  closeAlertTwo.onclick = function (){
    _modalTwo.style.display = "none";
  }       
}
//version web
.alert-desglose{
  display: none;
}

@media screen and (max-width: 500px)
.alert-desglose {
    display: block;
    margin-bottom: 25px;
    -webkit-order: 2;
    -ms-flex-order: 2;
    order: 2;
}
<div class="alert alert-desglose" id="ModalAlertThree">     
  <div class="content-alert-text">
    <div class="circle icon-alert">
      <img src="/Info.svg" alt="Icono info"/>
    </div> 
    <div class="copy-alert">
        <span class="data">HOLA</span>
    </div> 
    <div class="circle icon-close" onclick="hiddenModalAlertTwo()">
        <img src="Icon.png" alt="Icono cerrar"/>
    </div>  
  </div>
</div>

but the function don’t close the div

is there any way to generate invite links of the channels where my discord.js bot is in?

but I have a serious problem that I had a Discord channel with my friend and my Discord.js bot like bellow. But I left the channel and my friend is dead so Im unable to join the sever anymore.

const { Client, Intents } = require('discord.js')
const { prefix, token } = require("./config.json");
const ytdl = require("ytdl-core");

const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]})
  
client.on('ready', () => {
    console.log(client.user.tag + "I came home!")
})


client.on('message', message => {
    // some code for message commands
   
})


client.login(token);

So I want to ask that is there anyway to make my Discord.js bot to generate an invite link of the sever it is in? Because I dont have any knowledge about Discord.js and it’s really rushed so please help me with the code.

Thank you everyone for reading.

Websocket in webpage not being run when page is called with python requests

I have a webpage that is running some web sockets.

When I access the webpage with the browser it all works fine.

When I access the webpage with requests, the page doesn’t initiate the socket.

How is this possible?

Sockets:

<script>

    $(document).ready(function () {
            const messages_container = document.getElementById('chat_box');
            let room_id = "{{ room.id }}";

            var loc = window.location;
            var wsStart = 'ws://';

            if (loc.protocol == 'https:') {
                var wsStart = 'wss://';
            }

            let chatSocket = new WebSocket(
                wsStart
                + window.location.host
                + '/ws/matchmaker/'
                + room_id
                + '/'
            );

            $('#game_results').click(function () {
                chatSocket.send(JSON.stringify({
                    'message': 'results-incoming'
                }));
            });

            chatSocket.onopen = function (e) {
                // nothing
            };

            chatSocket.onmessage = function (e) {
                let message = JSON.parse(e.data)['message'];

                if (message['message-type'] == 'get-room-players') {
                    let message_body = JSON.parse(message['message-body']);
                    let players = "";
                    for (let i = 0; i < message_body.length; i++) {
                        players += `<div class="col-md-6 card">
                        <div class="card-body">
                            <h5 lass="card-title">player id ${message_body[i].fields['player_id']}</h5>
                            <h5 lass="card-title">player skill ${message_body[i].fields['skill']}</h5>
                            <h5 lass="card-title">player behaviour ${message_body[i].fields['behaviour']}</h5>
                            <h5 lass="card-title">player skill preference ${message_body[i].fields['skill_preference']}</h5>
                            <h5 lass="card-title">player behaviour preference ${message_body[i].fields['behaviour_preference']}</h5>
                            <h5 lass="card-title">player granularity_preference ${message_body[i].fields['granularity_preference']}</h5>
                        </div>
                    </div>`

                    }
                    $('#players_container').html(players);
                } else if (message['message-type'] == 'update-players') {
                    chatSocket.send(JSON.stringify({
                        'message': 'get-room-players'
                    }));
                } else if (message['message-type'] == 'update-room-match-status') {
                    $('#match_status').text(message['message-body']);
                } else if (message['message-type'] == 'results-incoming') {
                    window.location = "http://localhost:8002/game/?room_id=" + room_id;

                } else if (message['message-type'] == 'update-current-num-players') {
                    $('#current_num_players').text(message['message-body']);
                    // room is now full and can proceed to play
                    if (message['message-body'] == {{ room.game.max_num_players }}) {
                        $('#game_results').show();

                    }
                }

            };

            chatSocket.onclose = function (e) {
                console.error('Chat socket closed unexpectedly');
            };
        }
    );


</script>

The webpage which has the sockets is a response to this post request:

response = client.post(url, headers=headers, params=params, data=data, cookies=cookies)

If I print(response.text) the html code for the web socket webpage is shown, but as I said, the socket does not run.

CSS not showing up when HTML loaded

I am having an issue linking my CSS to HTML on my computer. My html file has the correct link and name for the CSS file but when I open by HTML file in chrome there is no styling. If I open up dev tools after that and go to source, only my js and html file show in the folder even though there is json, css, html, and js file in the project folder. The CSS file name is index.css, the js file name is index.js, and the html file name is index.html. If you know what could be wrong please let me know. I ran both files here and they work here but not when I try and run my html file on chrome.

CODE:

body {
    margin: 0;
    padding: 10px;
    font-family: Arial, Helvetica, sans-serif;
    min-width: 400px;
}

input {
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
    border: 1px solid #5f9341;
    margin-bottom: 4px;
}

button {
    background: #5f9341;
    color: white;
    padding: 10px 20px;
    border: 1px solid #5f9341;
    font-weight: bold;
}

#delete-btn {
    background: white;
    color: #5f9341;
}

ul {
    margin-top: 20px;
    list-style: none;
    padding-left: 0;
}

li {
    margin-top: 5px;
}

a {
    color: #5f9341;
}
<!DOCTYPE html>

<html lang="en">

<head>
  <link src="index.css" ref="stylesheet" type: "text/css">
</head>`enter code here`

<body>
  <input type="text" id="input-el">
  <button id="input-btn">SAVE INPUT</button>
  <button id="tab-btn">SAVE TAB</button>
  <button id="delete-btn">DELETE</button>
  <ul id="ul-el">
  </ul>
  <script src="index.js"></script>
</body>

</html>

AJAX and This Picking Up Window instead of

function EasyHTTP () {
    this.http = new XMLHttpRequest();
}



//Make an HTTP GET request
EasyHTTP.prototype.get = (url) => {
    let self = this;
    console.log(self);
    self.http.open('GET',url,true)

    self.http.onload( function() {
        //this keyword in different function
        if(self.http.status ===200){
            console.log('yes');
        }
    }) 


    self.http.send()
}

I’ve tried the above code, and getting rid of the self variable and
using arrow functions but everytime I console.log(this/self) from within the function it logs the Window and I keep getting this error:

easyhttp.js:11 Uncaught TypeError: Cannot read properties of undefined
(reading ‘open’)
at EasyHTTP.get (easyhttp.js:11:15)

I’m using the Live Server plug-in

Invert a sequence in JavaScript

I want to invert this sequence:
Invert a function like in mathematics(is this exist in programming)
What I mean: if f(x)=y —>g(y)=x so g is the inverse function of f.
My attempt was(but still not working):

function seq(num) {
  
  if(num < 2) {return 1; }
  if(num === 2) {return 2; } 
  
  if(num % 2 === 1) {
    const t = (num - 1) / 2;
    return seq(t - 1) + seq(t) + 1;
  }
  
  const t = num / 2;
  return seq(t) + seq(t + 1) + t;
  
}
document.write(_.invert(seq(4)));