How to override VSCode Intellisense inference with JSDoc comment

VSCode’s Intellisense ignores my JSDoc comment and infers what the definition should be when using a function that returns a function (in this case, it’s RamdaJS.reduce)

/**
 * @param { Array<number> } arrayOfNumbers
 * @return { number } sum - the sum of the arrayOfNumbers
 */
const getSumOfArrayElements = reduce (add, 0)

VSCode output:

const getSumOfArrayElements: (list: readonly any[]) => number
@param arrayOfNumbers

@return — sum - the sum of the arrayOfNumbers

Intellisense is defining getSumOfArrayElements as the definition for the return value of reduce (add, 0) (reduce with 2 arguments supplied)

Is there a way to have JSDoc comments have top priority in VSCode?

Thanks!

Mapbox Directions – How do you use a clicked point as the ‘end’ and a geocoding result as the ‘start’ in a Mapbox Directions API HTTP request?

This is my first question here on stack overflow. I’m working on a function using the Mapbox Directions API. I used this Mapbox Directions API tutorial as a base, but since I want both my start and end point to change, I am running into problems. I want the user to be able to click a rendered point layer and then enter an address into the Mapbox Geocoder to retrieve a route between those two locations. The following code allows this to happen on the first click. The issue occurs in subsequent clicks. When I enter a location into the geocoder, separate requests are made for every single time the layer was clicked since the map had loaded. I know this must have something to do with the entirety of the code (ie. click layer, create function for HTTP request, get coordinates of geocoder result) being contained within the ‘click’ event, but I’m not sure how to reach my goal otherwise.

     map.on('click', function(e) {
      var bbox = [
        [e.point.x - 5, e.point.y - 5],
            [e.point.x + 5, e.point.y + 5]
            ];
      var features = map.queryRenderedFeatures(bbox, {
        layers: ['Schools']
            });
      
      //these coordinates will be used as the 'start' coordinates in the request
      let start = features[0].geometry.coordinates.slice(-2)
    

      // create a function to make a directions request
      async function getRoute(end) {
        
        
        const query = await fetch(
          `https://api.mapbox.com/directions/v5/mapbox/walking/${start};${end}?steps=true&geometries=geojson&access_token=${mapboxgl.accessToken}`,
          { method: 'GET' }
        );
        const json = await query.json();
        const data = json.routes[0];
        const route = data.geometry.coordinates;
        const geojson = {
          type: 'Feature',
          properties: {},
          geometry: {
            type: 'LineString',
            coordinates: route
          }
        };
      
        // if the route already exists on the map, we'll reset it using setData
        if (map.getSource('route')) {
          map.getSource('route').setData(geojson);
        }
        // otherwise, we'll make a new request
        else {
          map.addLayer({
            id: 'route',
            type: 'line',
            source: {
              type: 'geojson',
              data: geojson
            },
            layout: {
              'line-join': 'round',
              'line-cap': 'round'
            },
            paint: {
              'line-color': 'orange',
              'line-width': 5,
              'line-opacity': 1
            }
          },
          UnderRoadLabels
          );
        }                
      }
            
        //the coordinates of the geocoder result will be used as 'end' in the request.
        //call function getRoute(end)
        geocoder.on('result', function(e) {
          var end = e.result.center.slice();              
          getRoute(end);                
          map.setLayoutProperty('route', 'visibility', 'visible');
        });
    });
    };

My guess is that since everything is contained within a ‘click’ function, every click is being used to make an HTTP request. I want only the last click to be used to make one request.

I am a noob here and am completely stumped. I’ve tried a lot of different things. Any advice? How could I re-write this so that it isn’t entirely contained in one click function?

Any help is appreciated.

How can I use JavaScript to check the correct radio button?

I am trying to build a program to automate clicking on the correct multiple choice answer from a set of radio buttons but I am having trouble. The only difference in the HTML is “explanation correct” and “explanation incorrect” on the highlighted line’s class based on if the correct radio button is clicked. Why won’t my JavaScript code work?

HTML I am working with

Above is the HTML that I am working with and below is the JavaScript code I have written to try and select the correct radio button. Any idea why it’s not working?

Solution that I have come up with so far

I have an array full of objects. All objects have key author and publisher. I want to take out the publisher who publish most different authors

function findBiggestPublisher(arr) {
  for (let i = 0; i < arr.length; i++) {
    const element = arr[i];
    
    if (publisherBooks.hasOwnProperty(element)) {
      
      publisherBooks[element] = publisherBooks[element] + 1;
    } else {
      publisherBooks[element] = 1;
    }
  }
  console.log(publisherBooks);
  console.log(pushedPublishers);
  let publisherNameLow = "";
  let publisherNameHigh = "";
  let publisherHigh;
  let publisherLow;
  
  for (const [key, value] of Object.entries(publisherBooks)) {
    
    if (!publisherHigh || value > publisherHigh) {
      publisherHigh = value;
      publisherNameHigh = key;
    } 
    if (!publisherLow || value < publisherLow) {
      publisherLow = value;
      publisherNameLow = key;
    }
    //proverka za broi izdateli s 1 kniga
    
    if (value == 1) {
      console.log(`${key} has only ${value} book`);
    }
  }

  console.log(`${publisherNameHigh} has ${publisherHigh} books`);
  console.log(`${publisherNameLow} has ${publisherLow} books`);
  
}
findBiggestPublisher(pushedPublishers);

// So far I takeout the publishers with the most books and the fewest and the one with only 1 too.
Now I need to take out the publisher with the most different authors published.
Any advice about with what logic to compare them ?

Tic Tac Toe – minimax algorithm

I wanna use the minimax algorithm in tic tac toe. But I dont know how I could change my code. Right now the computer is choosing a random x on the board and checking if its available. I have read about it and seen some people do it but they have very similar code. I have a different one. I dont understand how to call the minimax on each available spot and the bestScore and bestMove stuff. this is my code now: check the snippet

const cellElement = document.querySelectorAll('[data-cell]')
const winner = document.getElementById("winner")
const winningConditions = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
]

let nextTurn = true
let win = true

function createCells() {
    cellElement.forEach(cell => {
        cell.addEventListener("click", cellButton, { once: true })
    });

}
createCells()

function cellButton(e) {
    const cell = e.target
    playerTurn(cell)
    checkWin()
    computerTurn(cell)
    checkWin()
    //check for draw
}

function playerTurn(cell) {
    if (nextTurn == false) {
        if (cell.innerHTML !== "✖") {
            cell.innerHTML = "O"
            nextTurn = true
        } else {
            alert("Choose another cell")
        }
    }
}

function computerTurn(cell) {
    let i = Math.floor(Math.random() * cellElement.length);

    if (nextTurn) {
        if (cellElement[i].innerHTML !== "✖" && cellElement[i].innerHTML !== "O") {
            cellElement[i].innerHTML = "✖";
            checkWin()
            nextTurn = false
        }
        return computerTurn();

    }
}
computerTurn()

function checkWin() {
    if (win) {
        for (let winCondition of winningConditions) {
            if (winCondition.every(i => cellElement[i].innerHTML == "O")) {
                winner.innerHTML = "O WON!!!"
                win = false
            } else if (winCondition.every(i => cellElement[i].innerHTML == "✖")) {
                winner.innerHTML = "X WON!!!"
                win = false
            }
        }
    }
}
body{
    background-color: #55E9BC;
    display: flex;
    justify-content: center;
}

.board{
    position: relative;
    width: 300px;
    height: 300px;
    top: 70%;
    display: grid;
    grid-template-columns: repeat(3, auto);
}

.cell{
    background-color:#11D3BC;
    color: #FFFCCA;
    width: 100px;
    height: 100px;
    margin: 1px;
    font-size: 80px;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

#winner{
    position: absolute;
    top: 250px;
    font-weight: bold;
    color: #3ab871;
    font-size: 40px;
    font-family: Verdana, Geneva, Tahoma, sans-serif;
}
    <p id="winner"></p>

    <div class="board">
        <div class="cell" data-cell></div>
        <div class="cell" data-cell></div>
        <div class="cell" data-cell></div>
        <div class="cell" data-cell></div>
        <div class="cell" data-cell></div>
        <div class="cell" data-cell></div>
        <div class="cell" data-cell></div>
        <div class="cell" data-cell></div>
        <div class="cell" data-cell></div>
    </div>

How does these line manipulate a state variable with an array in React?

I’m sitting down to visualize the quick sort algorithm with React.js for university. After a bit of searching, I found this code for partitioning, which is also intended for React.

async function partition(arr, start, end) {
        // Taking the last element as the pivot
        const pivotValue = arr[end];
        let pivotIndex = start;

        await changeColorForPivot(end)


        for (let i = start; i < end; i++) {
            if (arr[i] < pivotValue) {
                // Swapping elements
                [arr[i], arr[pivotIndex]] = [arr[pivotIndex], arr[i]];
                // Moving to next element
                pivotIndex++;
            }
        }

        // Putting the pivot value in the middle
        [arr[pivotIndex], arr[end]] = [arr[end], arr[pivotIndex]]

        await changeColorForPivot(pivotIndex)

        return pivotIndex;
    }

My array that I want to sort is in a state variable so that I can react to a change for display it visually.

const [arrForVisualisation, setArrForVisualisation] = useState([])

My question now is what exactly these two lines do in the Partition function

// Swapping elements
[arr[i], arr[pivotIndex]] = [arr[pivotIndex], arr[i]];

// Putting the pivot value in the middle
[arr[pivotIndex], arr[end]] = [arr[end], arr[pivotIndex]]

To me it seems like these two lines of code manipulate the state variable, as if they also update/change it at the same time.
To my knowledge, I always thought that you can update/change a state variable only with the corresponding setState() function.

For my further proceeding it would help me very much to understand these two lines of code, since I must still adapt the function somewhat, in order to be able to visualize the happening changes accordingly.

A Wage Calculator Algorithm [closed]

How to create a work algorithm for the following problem? Attached is the problem and my solution below.

Steve works a minimum of 0 hours and a maximum of 12 hours only on Mondays, Wednesdays and Fridays.
Steve works for a fixed rate of $10 per hour for the first 10 hours of the wek, $15 per hour for the second 10 hours of
the week, $20 per hour for the third 10 hours of the week and $25 per hour for the last 6 hours of the week.
Steve receives a bonus of $50 whenever he works for more than 10 hours on exactly 1 day only. Steve receives a
bonus of $75 whenever he works for more than 10 hours on exactly 2 days only. Steve receives a bonus of $100
whenever he works for more than 10 hours on all 3 days.
Write a pseudo code algorithm entitled STEVE_WAGE_CALCULATOR that reads in three integers between 0 and 12
inclusive that represent the hours worked on Monday, Wednesday and Friday of a given week and prints Steve’s total
salary for that week after all adjustments

program STEVE_WAGE_CALCULATOR
 begin 

mhoursWorked <- 0
whoursWorked <- 0
fhoursWorked <- 0
weeklyHours
bonus1 <- 50
bonus2 <- 75
bonus3 <- 100
mBonus <- 0
mNormal <-0
wBonus <-0
wNormal <-0
fBonus <-0
fNormal <-0
total <-0

PRINT "Enter number of hours worked on Monday: "
READ_INT mhoursWorked

PRINT "Enter number of hours worked on Wednesday: "
READ_INT whoursWorked

PRINT "Enter number of hours worked on Friday: "
READ_INT fhoursWorked


If mhoursWorked = 10 
then mhoursWorked * 10 + bonus1
READ_INT mBonus

else mhoursWorked * 10
READ_INT mNormal

if whoursWorked = 10
then whoursWorked * 15 + bonus2 
READ_INT wBonus

else whoursWorked * 15
READ_INT wNormal

if fhoursWorked = 10
then fhoursWorked * 20 + bonus3 
READ_INT fBonus 

else fhoursWorked * 20
READ_INT fNormal

if mBonus && wBonus && fBonus = true
then mBonus + wBonus + fBonus = total

else if mBonus && wBonus && fNormal = true
then mBonus + wBonus + fNormal = total

else if mBonus && wNormal && fNormal = true
then mBonus + wNormal + fNormal = total 

else if mNormal && wNormal && fNormal = true
then mNormal + wNormal + fNormal = total

else if mNormal && wNormal && fBonus = true
then mNormal + wNormal + fBonus = total

else mNormal && wBonus && fNormal = true
then mNormal + wBonus + fNormal = total


PRINT "Total Weekly Wage: " + total
 end

jso.numfields not returning anything within Excel VBA while connecting to PDF file

So I am trying to write a VBA Macro in Excel that will loop through all 400+ .pdf files I have in a folder, extract pertinent data from them, and store that data in an Excel spreadsheet. However I am not sure that my .pdf files are even being opened. My file path is good, but when I try to detect any fields in the .pdf file using .numfields, it returns 0. I’ve checked Adobe Acrobat in my References tool, are there any ‘things’ I need to set up for JS Objects to work in Excel VBA ?

Here is my code so far:

Private Sub CoH_Water_Invoice()

     'Declare the File Path
     Dim path As String: path = "K:AdministrationUtilitiesFY22"
     Dim file As String: file = Dir(path & "*.pdf")

     'Set up Variables/Acrobat Objects
     Dim AcroApp As Acrobat.CAcroApp
     Dim theForm As Acrobat.CAcroPDDoc
     Dim jso As Object

     Set AcroApp = CreateObject("AcroExch.App")
     Set theForm = CreateObject("AcroExch.PDDoc")
     theForm.Open(path & file)
     Set jso = theForm.GetJSObject

     'Check for fields
     If jso.numfields > 0 Then
          Debug.Print("Fields detected")
     Else
          Debug.Print("No Fields detected")
     End If

     theForm.Close
     AcroApp.Exit
     Set AcroApp = Nothing
     Set theForm = Nothing
End Sub

In the “Immediates” window, I always get “No Fields detected”, so it is not picking up any fields in the JS Object. Any ideas?

Functions and synchronous requests

Imagine my JS script is the following :

function big_code() {
        do_a_lot_of_stuff
        $.ajax({
            type: "post",
            url : host + "/function1",
            headers: {"content-type": "application/json"},
            datatype: "json",
            contentType: "application/json; charset=utf-8",
            data: my_variables1 ,
            success:function(){
                      $.ajax({
                      type: "post",
                      url : host + "/function2",
                      headers: {"content-type": "application/json"},
                      datatype: "json",
                      contentType: "application/json; charset=utf-8",
                      data: my_variables2,
                      success:function(data){  VARIABLES = SOMETHING })
    }
  })

 return VARIABLES }


function other_bigfunction() {
        VARIABLES = big_code() 
        do_something_else...



I succeeded to get the variable VARIABLES from big_code function by using async=false in ajax requests.
Of course it is unconvenient because all others functions stop working….

Have you an idea to obtain this variable in big_code() ONLY after ajax requests?

Thank you in advance

Counting the Occurance or frequency of array elements Using Logical Operators only with the help of javascript and storing it in a object

let us consider the array

const scored= ['Lewandowski', 'Gnarby', 'Lewandowski', 'Hummels'];

Then we have to create a emtpty object

const scorers={};

Now looping through the array we can do

for (const player of scored) {
  (scorers[player] += 1) || (scorers[player] === 1 || (scorers[player] = 1));
}

(scorers[player] += 1):-> First we try to add pretending that the “player” is there in object.if the player is there one will be added else if “player” is not there it will return Nan and continue with next expression (scorers[player] === 1 || (scorers[player] = 1)).Then we check for following steps.

scorers[player] === 1:-> Next if the player is there,we check if value is 1 and if it has a value 1,the operation does not continue further.if player has a value 1,means that he has already been assigned a start value.

scorers[player] = 1:-> The player does not have a value of 1,we assign him a value of 1 to start with.

Below is what final code looks like

 const scored = ['Lewandowski', 'Gnarby', 'Lewandowski', 'Hummels'];
const scorers = {};
for (const player of scored) {
   (scorers[player] += 1) || (scorers[player] === 1||(scorers[player]=1));
    }
console.log(scorers);

how to bypassing Cptcha numbers

I’m trying to build a script that will bypass the security code on my particular site, I must build the code as if I have no access to the code.
The problem with the image of this security is that the built-in link changes every time you refresh it, so I can not take the image link and send to an API that knows how to print images, because the API will get a different image than what is displayed on the screen.
If anyone can help me find a way to build a script that will bypass this code I would really, really really appreciate it
I’m stuck on this for a few days.
I attach the code of the image:

<img src="https://pokemon-arena.co.il/includes/captcha.php" alt="captcha" title="captcha">

Call A Function Inside Of Other File

I’m Trying To Create A Npm Module That When You Call It, It’s Supposed To Execute The main()
Function In The index.js (file that calls the module) File.

But When I Try To Run It It Says :

Error: 
 ReferenceError: main is not defined

Here Is The Files

(module) index.js:

try {
    main()
} catch (error) { 
    console.log(`Error: n ${error}`) 
} 

(test file) test.js

var js = require("./index")

function main() {
    console.log("Better JS Working")

    return 0
}