async await calling function node.js

I have this function, that queries my database, and then calls getNumOfSessionForTrainerClientList function:

var select = "select * from USERS WHERE ASSIGNED_TRAINER = ?"
mysqlconn.connect(function(err) {
    if (err) {
        console.error('Database connection failed: ' + err.stack);
        return;
    }

    mysqlconn.query(select, [req.session.username], async function(err, rows) {
        if (err) {
            console.log(err);
        } else {
            
            let numOfSessionsLeft = {
                numberOfSessionsLeftIs: 0
            }
            for (var i = 0; i < rows.length; i++) {
                getNumOfSessionForTrainerClientList(req, res, rows[i], numOfSessionsLeft)
                rows[i]["NUM_OF_SESSIONS_PER_MONTH"] = (parseInt(rows[i]["NUM_OF_SESSIONS_PER_MONTH"]) - numOfSessionsLeft.numberOfSessionsLeftIs)
                console.log(numOfSessionsLeft)
            }
          

        }
        mysqlconn.end();

    })
})

and then inside the function getNumOfSessionForTrainerClientList, I have this:

async function getNumOfSessionForTrainerClientList(req, res, rows, numOfSessionsLeft) {

var getNumOfSessionForTrainerClientList = "select * from SCHEDULE WHERE CLIENT_USERNAME = ? AND ASSIGNED_TRAINER = ?"
mysqlconn.connect(async function(err) {
    if (err) {
        console.error('Database connection failed: ' + err.stack);
        return;
    }
        mysqlconn.query(getNumOfSessionForTrainerClientList, [rows["USERNAME"], req.session.username], async function(err, sessionData) {
            if (err) {
                console.log(err);
            } else {
                numOfSessionsLeft.numberOfSessionsLeftIs = 1;
                console.log(numOfSessionsLeft.numberOfSessionsLeftIs)

            }

        })

})

}

however, what is happening is that this line : rows[i]["NUM_OF_SESSIONS_PER_MONTH"] = (parseInt(rows[i]["NUM_OF_SESSIONS_PER_MONTH"]) - numOfSessionsLeft.numberOfSessionsLeftIs) is actually assigning 0 to rows[i]["NUM_OF_SESSIONS_PER_MONTH"] because that variable assignment is happening before the function call for getNumOfSessionForTrainerClientList finishes. So it is happening out of sync. I am not sure how to fix this, i have run into issues with async await before, but nothing like this. would appreciate the help.

Failed to resolve module specifier “three” as of 137

Coming back to some old project, I discover nothing was loading. Checking the console log I see the following:

Uncaught TypeError: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../".

In my script I got the following:

<script type="module">
import * as THREE from "https://cdn.skypack.dev/three/build/three.module.js"
import { OBJLoader } from "https://cdn.skypack.dev/three/examples/jsm/loaders/OBJLoader.js"
import { FirstPersonControls } from "https://cdn.skypack.dev/three/examples/jsm/controls/FirstPersonControls.js"

I try to step back some versions and not until I reach 0.136.0 does this error go away. Has the way one imports three.js changed, or is this a bug?

Also, would there be some way of catching this at runtime? Like I get the latest version number from Skypack and try an import. If failed, automatically step back a decimal and try again.

Is there a way to access and read from a CSV file that is stored on iCloud drive, using JavaScript?

I have an application on my iPhone that collects and appends data into a CSV files, and has two options for the storage of said files:

A) Local storage on the phone
B) Cloud-based storage on iCloud

I’d like to write a client-side script in JavaScript that processes the data points in these CSV’s (and puts them onto a chart with Charts.js), but I can’t find a way to access the file.

Is there some kind of API that can provide these options?
Any help is much appreciated 🙂

Thank you all in advance,
Peter

Is there a way calculate the position of an element before css transform matrix is applied?

I need to figure the ending bounding rect of an element before the matrix transformation is applied. I have no idea really where to start and can’t find any good articles addressing this.

So given you have the original position of the element with getBoundingClientRect() is there a reliable way to find the ending position if you have the matrix that is supposed to be applied.

I have built a scroll controller and I am trying to map the elements progress through the screen but I need the starting and ending position of the element. So I would need the position of the element after the css transformation is applied to figure out when the element has left the screen. Right now i am just applying the matrix and then running getBoundingClientRect() again. But this seems a bit hacky.

So give you have the original and ending matrix. And then you run the getBoundingClientRect() on the element to find its position. Is there a mathematical way to calculate the new bounding rect?

So for this example we will just use a 6 value matrix. But it would be nice to apply it to a full 16 value matrix as well:

const boundingRect = element.getBoundingClientRect();
const initialMatrix = [1, 0, 0, 1, 0, 0];
const endingMatrix =  [1, 0, 0, 1, 200, 400];

// Now calculate the new bounding rect of element after ending matrix is applied.

Any help would be appreciated. Or pointers in the right direction.

How to disable or readonly select input angular

If the cardSelect variable is true, just let read select it

<select name="card-exp-month" #validateMonth formControlName="digiMes" class="form- 
 control" name="validade" id="validade"   >
<option value="">Mês</option>
<option value="01">01 Jan</option>
<option value="02">02 Fev</option>
<option value="03">03 Mar</option>
<option value="04">04 Abr</option>
<option value="05">05 Mai</option>
<option value="06">06 Jun</option>
<option value="07">07 Jul</option>
<option value="08">08 Ago</option>
<option value="09">09 Set</option>
<option value="10">10 Out</option>
<option value="11">11 Nov</option>
<option value="12">12 Dez</option>
</select>

When is input text its works

<label for="nomeimpresso">Nome <b>impresso</b> no cartão<span class="text-danger"> * 
</span></label>
<input #nomeImpresso formControlName="digiNome"  name="holder-name" id="nomeimpresso" 
class="form-control col-lg-6" type="text"  [readonly]="cardSelect" >

Bootstrap nav tab how to change active tab to underline?

Bootstrap nav tab how to change active tab to underline?
This is my code.

// Bootstrap Handles The Javascript
// Add css to underline the active tab
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
<div class="container">
  <nav>
    <div class="nav nav-tabs" id="nav-tab" role="tablist">
      <button class="nav-link active" id="nav-home-tab" data-bs-toggle="tab" data-bs-target="#nav-home" type="button" role="tab" aria-controls="nav-home" aria-selected="true">Home</button>
      <button class="nav-link" id="nav-profile-tab" data-bs-toggle="tab" data-bs-target="#nav-profile" type="button" role="tab" aria-controls="nav-profile" aria-selected="false">Profile</button>
      <button class="nav-link" id="nav-contact-tab" data-bs-toggle="tab" data-bs-target="#nav-contact" type="button" role="tab" aria-controls="nav-contact" aria-selected="false">Contact</button>
    </div>
  </nav>
  <div class="tab-content" id="nav-tabContent">
    <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">Home</div>
    <div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab">Profile</div>
    <div class="tab-pane fade" id="nav-contact" role="tabpanel" aria-labelledby="nav-contact-tab">Contact</div>
  </div>
</div>

Thanks in advance!

Recursive Function Uncaught RangeError: Maximum call stack size exceeded

This function which will execute when you enter on input field then it will calculate how much money do you have to return with x type to customer.

But getting stack size error sometime for 6 digit and everytime for 7 digit.

Reproduce: put 1234567 in input box and check the console.

Function:

function isRemainingMoney(value) {
    let remainingValue = value;

    // when remaning value becomes zero then return the returnlist
    if (remainingValue == 0) {
      return returnList;
    }

    for (let pRed of predictorList) {
      /* remainingValue is greater than predictor value then push it 
      eg:  41.33 > 20
           21.33 > 20
           1.33 > 1
           0.33 > 0.25
           0.08 > 0.05
           0.03 > 0.01 * 3 times
      */
      if (remainingValue >= pRed) {
        const isPredExist = returnList.find(
          (pItem) => +pItem.money == +pRed
        );
        if (!!isPredExist) {
          isPredExist.count += 1;
          isPredExist.total = isPredExist.total + +pRed;
        } else {
          returnList.push({
            type: pRed,
            money: pRed,
            count: 1,
            total: pRed,
          });
        }
        remainingValue = +remainingValue.toFixed(2) - pRed;
        break;
      }
    }
    // recursive call the same method untill remainivalue becomes zero.
    return isRemainingMoney(+remainingValue.toFixed(2));
  }

document.querySelector('input').addEventListener('change', (event) => {
   if(!!event.target.value) {
        returnList.length = 0;
        returnList = isRemainingMoney(+event.target.value - total);
        console.log(returnList, 'returnList');
   }
   
})

Playground: https://jsbin.com/kuwomalare/edit?html,js,console,output

d3. join with nested elements

I am trying to use d3.join and trying to get this DOM structure.
The data is dynamic and data size will change. I want to append all rectangles with in a separate group (“g”). When you click on the circle more than once to draw the rectangles, several empty “g” elements are created. Please help me learn what I am doing wrong. Thanks

Here is the code pen link

https://codepen.io/zubair57/pen/mdqWLRV?editors=0011

<svg width="800" height="3800">
  <g>
    <circle cx="600" cy="100" r="20"></circle>
  </g>
  <g>
    <rect width="600" height="20" x="0" y="0" class="bil"></rect>
  </g>
  <g>
    <rect width="200" height="20" x="0" y="25" class="bil"></rect>
  </g>
  <g>
    <rect width="300" height="20" x="0" y="50" class="bil"></rect>
  </g>
  <g>
    <rect width="400" height="20" x="0" y="75" class="bil"></rect>
  </g>
  <g>
    <rect width="900" height="20" x="0" y="100" class="bil"></rect>
  </g>
  <g>
    <rect width="200" height="20" x="0" y="125" class="bil"></rect>
  </g>
</svg>

How do I sort a javascript 2d array of names into groups?

I have a race consisting of (for example) 9 heats. There are (for example) 9 drivers split in to groups. In this example, each driver will drive in 4 heats each. However, I don’t know ,explicitly, how many groups there are and I don’t know how many drivers are in each group.

What I do know, is which heat each driver is in. So, for this example the heats may look like this:
enter image description here

So, how do I determine how many groups there are and how do I get the drivers in to their respective groups?

Also, how do I make this generic, so that it could be 8 drivers in 8 heats or 37 drivers in 29 heats?

In javascript, so far, I have populated a 2D array that gives results similar to the grid shown above.

Here is the code I have so far:

for (var i = 0; i < heatData.cnt; i++)           //number of heats                                              
{
    var driverArray = new Array();
    for (var k = 0; < json.r[1].d.length ; k++)  //number of drivers in this heat.
    {
        var name = json.r[1].d[k].nn;            //this is the name of the driver in this heat.
        driverArray[k] = name;                   //adds the name to the inner array
    }
    heatArray.push(driverArray);                 //adds the inner array to the end of the outer array.
    });

}

Thanks,

Connal

Laravel vue page is not loading and is pending in the network tab

I got question about Laravel and VueJS. I’ve built my Vue project with npm run watch and I started my Laravel application with php artisan serve to serve the app. When I went visit my website-page, the page would not load and is continuing in a infinite loop. In my network tab, I see an API request has been sent to /js/landing.js, but he seems to be pending for the whole time.

My application is at the moment running on WSL, but I do not know what problem caused this issue.

enter image description here

How can I save in Firestore when a value is from a conditional element? More explanation below

So I have this category of select.

  1. If the user chose, shirt sizes, it will show a text field to enter the number of the size and a selection as well to enter whether it is S,M,L, and so on.
  2. If the user chose CM, it will only reveal a size an InputProp at the end of a CM and also goes the same to ML

I can already save it in the firestore well if the user will just choose number 1.The problem here is that, if I’ll choose number two the sizes CM and ML would not be submitted since I am not sure how to do this as saving size1 will have a value of undefined.

Select a category

const [category, setCategory] = useState(); //select
const [size1, setSize1] = useState(); //select

  //select
  const handleChange = (event) => {
    setCategory(event.target.value);
  };


          <FormControl fullWidth>
                <Select
                  value={category}
                  onChange={handleChange}
                >
                  <MenuItem value="Shirt">shirt sizes</MenuItem>
                  <MenuItem value="CM">CM</MenuItem>
                  <MenuItem value="ML">ML</MenuItem>
                </Select>
              </FormControl>

Conditionally rendering according to what was selected above:

const [size, setSize] = useState();
 function handleSelectionUpdate(data) {
    setSize1(data);
  }

{category === "shirt" && (
                <>
                  <TextField
                    label="Size"
                    type="text"
                    value={size}
                    onChange={(e) => setSize(e.target.value)}
                    required
                  />
                  <Size1 onSelectionUpdate={handleSelectionUpdate} />
                </>
              )}

The way I created CM and ML are the same:

 {category === "CM" && (
                <>
                  <TextField
                    label="Size"
                    type="text"
                    value={size}
                    onChange={(e) => setSize(e.target.value)}
                    required
                    InputProps={{
                      endAdornment: (
                        <InputAdornment position="end">CM</InputAdornment>
                      ),
                    }}
                  />
                </>
              )}

Saving this in firestore:
I created it as size: size + "-" + size1 because I wanted to it to show something like this size: 40CM

const docRef = await addDoc(collection(db, "products"), {
      //productName here
      size: size + "-" + size1,
    });
    setOpen(true);
    console.log("Document written with ID: ", docRef.id);

Implement foldRight on Array.prototype in javascript

I want to implement a foldRight method with multiple reducer functions

Array.prototype.foldRight = function(f, acc){
    if(this.length == 0){
        return null;
    }
    else {
        const head = this[0];
        const tail = this.slice(1);
        return foldRight(f(acc, head), tail);
    }
};

But im still new to javascript, am I using the Array.prototype right to add an own method to the Array class? And why doesn’t it work when im testing it with exampleArray.foldRight((a,b)=>b+a) etc?

How do I return the data that came with fetch to the parent function? [duplicate]

KullaniciDogrula(mail, password){

        if(!checkEmail(mail)){
            console.log("başarısız mail");
            return false;
        }
        
        var url = "../panel/netting/islem.php";
        var veri = `mail=${mail}&password=${password}&kullaniciDogrulama=true`;
        var returnValue;

        fetch(url, {
            method: "POST",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: veri
        })
        .then((response) => {
            return response.text();
        })
        .then((response) => {
            if(response == 1){
                //true to parent function
            }else{
                //false to parent function
            }
        })
        .catch((response) => {
            returnValue = 0;
        });

   }   

I want KullaniciDogrula() to return 1 if the response is 1, and KullaniciDogrula() to return 0 if the response is 0. How can I do it?