Why does button move with float property?

im trying to make a VN, and i tried to make a float because i need the text to go in between the two images, but i think its causing the button to move slightly to the right side when it appears.
I keep seeing recommendations for other methods of putting things on the right, like display:flex; but I cant seem to use it in this instance.

document.addEventListener("DOMContentLoaded", () => {
  let index = 1;
  const button = document.querySelector('button');
  const sections = document.querySelectorAll('section');
  button.addEventListener('click', function() {
    if (sections[index]) {
      if (hasImg(index) && hasImg(index - 1)) {
        sections[index - 1].classList.remove("d-block");
      }
      sections[index].classList.add("d-block");
      typeWriter(sections[index]);
    }
    if (!sections[++index]) {
      button.disabled = true;
    }
  });

  function hasImg(index) {
    return sections[index].querySelector('img');
  }

  typeWriter(sections[0]);
});

function typeWriter(el) {
  const content = el.innerHTML;
  el.innerHTML = '';
  let i = 0;
  const typeInterval = setInterval(() => {
    if (content[i] === '<' && content[i + 1] === 'i' && content[i + 2] === 'm' && content[i + 3] === 'g') {
      let endIdx = content.indexOf('>', i) + 1;
      el.innerHTML += content.substring(i, endIdx);
      i = endIdx;
    } else {
      el.innerHTML += content[i];
      i++;
    }
    if (i >= content.length) {
      clearInterval(typeInterval);
    }
  }, 95);
}
section {
  display: none;
  text-align: center;
}

.d-block {
  display: block;
}

button {
  margin: 0 auto;
  display: block;
}

.portrait {
  animation: fadeIn 5s;
}

@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

.happy {
  float: left;
}

.sad {
  float: right;
}
<section class="text d-block">First</section>
<section class="text">Second</section>
<section class="text">
  <img class="portrait happy" src="https://cdn.iconscout.com/icon/premium/png-256-thumb/arrow-small-right-4241483-3517873.png">
  <img class="portrait sad" src="https://cdn.iconscout.com/icon/free/png-256/free-small-diamond-geometric-blue-38006.png">
</section>
<section>Las</section>
<section>Ursa</section>
<button>next</button>

Using moment to calculate time difference

I am using below logic to calculate the time difference.

However, this is giving wrong result value when days > 1.
Please help simplifying the code.

I will be using the time difference logic in angular framework.

const startDate = new Date(form.value.startDate);
const endDate = new Date();
const dateDiff = this.calculateDateDifference(startDate, endDate);

calculateDateDifference(startDate, endDate) {
    const difference = endDate.getTime() - startDate.getTime();

    const seconds = Math.floor((difference / 1000) % 60);
    const minutes = Math.floor((difference / (1000 * 60)) % 60);
    const hours = Math.floor((difference / (1000 * 60 * 60)) % 24);
    const days = Math.floor(difference / (1000 * 60 * 60 * 24));

    console.log(days + ' days ' + hours + ' hours ' + minutes + ' minutes ' + seconds + ' seconds');
    if (days > 1) {
        return `${days} Days, ${hours} Hours, ${minutes} Mins`;
    } else {
        return `${hours} Hours, ${minutes} Mins`;
    }
}

How can I achieve the same output using “moment”?

Checking While Condition and Inner setInterval Condition

I am trying to update a variable until it doesn’t contain any more {{var}} variables. I’m using while loop and a setInterval inside of that.

Here’s my fiddle: https://jsfiddle.net/billparti/oxej2s91/

    var conmath = "1000 - {{sum}}";
    var re = /{{([^{}]+)}}/;
    var m;
    console.log('Conmath-Outside While: ' + conmath);
    while (m == re.exec(conmath)) {
      var mfld = m[1];
      console.log('MFld: ' + mfld);
      console.log('Conmath-Inside While: ' + conmath);
      var mult = "2";
      var mfldi = "field~~sum"
      var mfldtxt = '#field' + '\~\~' + mfld;
      console.log('MfldTxt ' + mfldtxt);
      waitmfld = $(mfldtxt).filter(function() {return $(this).attr('data-mult') == mult}); // set var global to use in other funcs
      console.log('Waitmfld: ', $(waitmfld));
      var wtime = 0;
      return; // temp - comment out to see infinite loop
      var waitForElement = setInterval(function(waitmfld, mfld) {
        console.log('Inside Wait');
        console.log('ClassCk: ' + $(waitmfld).hasClass('done'));
        if (wtime > 1500) { // stop wait after 2secs
          console.log('Ending Wait: ' , $(wait));
          clearInterval(waitForElement);
        }  
        if ($(waitmfld).hasClass('done')) {
          console.log('Wait Has Class');
          var mval = $(waitmfld).text();
          console.log('Mval-Wait: ' + mval); // should be 3
          conmath = "1000 - 3"; // set conmath to check if can get out of while loop
          clearInterval(waitForElement);
        }
        wtime += 500;
      }, 500);
    }

Note: I put a temp return before the setInterval so you can see if there are other errors and it also prevents an infinite loop from happening.

How to refer to a github repo wiki with octokit

Using Octokit I can retrieve commits for the base repository. Here’s the code for that. The values passed for owner and repo parameters are “PDConSec” and “vsc-print” and being the admin I have a suitable PAT defined in an environment variable on my workstation.

const octokit = new Octokit({ auth: process.env.PRINT_PAT });

async function getPreviousCommitSha(owner, repo) {
    try {
        // Get the list of commits from the default branch (usually 'main' or 'master')
        const { data } = await octokit.rest.repos.listCommits({
            owner,
            repo,
            per_page: 2, // Fetch the latest two commits
        });

GitHub repos have associated with them a wiki repo. You can clone it to edit the files locally. I did, and here’s the redacted content of the corresponding .git/config

[remote "origin"]
    url = https://[email protected]/PDConSec/vsc-print.wiki.git
    fetch = +refs/heads/*:refs/remotes/origin/*

I want to retrieve the last two commits for this wiki repo. I tried the repo name vsc-print.wiki but I keep getting the message Not Found - https://docs.github.com/rest/commits/commits#list-commits which you get for any invalid repo name.

What repo name should one use to refer to the wiki associated with a given repo?

Timing Issue – How to Prevent Initial Loading of Non-essential Images and Videos in a Chrome Extension?

I’m working on a Chrome extension aimed at preventing the initial load of non-essential images and videos to conserve bandwidth and resources. The extension is intended to swap src attributes with data-src for lazy loading, but despite implementation, all media are fetched as per network monitoring, although they appear hidden on the webpage.

The script is executed at document_start, yet it seems the intervention occurs too late or does not effectively block the media from being fetched, only hiding them after the fact. I’m seeking advice on strategies or APIs that could enhance the extension’s ability to prevent these initial loads more efficiently.

Could there be a more effective approach or specific Chrome APIs that I’m missing that could help achieve this goal better? Any insights or suggestions on how to address this issue would be greatly appreciated.

jsPDF Library not exporting Cyrillic letters

I am trying to export data into PDF from a React project using JS. (I tried other libraries as well) so I am using jsPDF to create the pdf and it works fine until I try to export something in Cyrillic.

async function exportDataToPDF() {
    const doc = new jsPDF();

    // Load the font file as a binary string
    const fontUrl = "../../../assets/fonts/Roboto-Regular.ttf";
    const fontData = await fetch(fontUrl).then(res => res.arrayBuffer());
    const fontArray = new Uint8Array(fontData);
    const fontString = String.fromCharCode.apply(null, Array.from(fontArray));

    // Add the font to the virtual file system
    doc.addFileToVFS("Roboto-Regular.ttf", fontString);

    // Add the font to the document
    doc.addFont("Roboto-Regular.ttf", "Roboto", "normal");

    // Set the font
    doc.setFont("Roboto");

    // Set font size and add text
    doc.setFontSize(16);
    doc.text('In english', 10, 10);
    doc.text('На български', 10, 20);

    // Save the PDF
    doc.save('Планирано производство.pdf');
}

I tried importing the font this way, but it won’t find it. It finds other files in the assets folder.

import RobotoRegular from "../../../assets/fonts/Roboto-Regular.ttf"; 

Then I tried to add the path in the function as shown in the code and it did read it, the font changed to Cyrillic, but it still won’t read Cyrillic letters.

const fontUrl = "../../../assets/fonts/Roboto-Regular.ttf";

How to access Index array in H5 file using jsfive library?

I need to grab the index array from an h5 file but can’t seem to locate it.
I use this python code to print and see

import pandas as pd

ber_per_flow = pd.read_hdf('c:\runbrowser\data\032266_1\RunID032266_1.MonitorData.h5', 'count_of_reads_lengths')
print(ber_per_flow)

which returns

           All reads  Trimmed by adapter  Trimmed by quality  Trimmed by Adapter or Quality
12           2                 1.0                 1.0                            2.0
13           5                 4.0                 1.0                            5.0
14           5                 3.0                 2.0                            5.0
15           5                 3.0                 2.0                            5.0
16           9                 5.0                 4.0                            9.0
..         ...                 ...                 ...                            ...
459          1                 0.0                 0.0                            0.0
465          1                 0.0                 0.0                            0.0
466          1                 0.0                 0.0                            0.0
469          1                 0.0                 0.0                            0.0
476          1                 0.0                 0.0                            0.0

the first column starting at 12 and down is the index array.

This is my JS code

const readH5FileRLDataAsync = async (filepath, key) => {
    return new Promise((resolve, reject) => {
        fs_raw.readFile(filepath, (err, data) => {
            if (err) return reject(err);
            else {
                try {
                    let f = new hdf5.File(data.buffer);
                    let keys1 = f.get(`${key}/block1_items`);
                    let group1 = f.get(`${key}/block1_values`);
                    let keys = f.get(`${key}/block0_items`);
                    let group = f.get(`${key}/block0_values`);
                    if (group !== undefined && group1 !== undefined) {
                        let result = splitIntoChunks(group, keys);
                        let result1 = splitIntoChunks(group1, keys1);
                        let merged = { ...result, ...result1 };
                        return resolve(merged);
                    }
                    else return resolve(null);
                }
                catch (e) {
                    console.log(e);
                    return reject(e);
                }
            }
        });
    });
}

keys1 contains ‘All reads’, group contains the array for keys1, keys contains ‘Trimmed by adapter, Trimmed by quality, Trimmed by Adapter or Quality’ and group1 contains the arrays for corresponding keys. Neither contain the index array shown in python.

I’m new to this library, does anyone know how to locate <path_to_indexes_dataset> ?

React native recording voice

How can I record a voice using react native and, when recording, have access to data at certain time intervals, say a second, and somehow work with this data, let’s say send it to the server, etc.

I try do this with lib react native recorder and other libs, but this did not produce results

Javascript don’t appear on website after to deploy with vite on Github

my directories

Hello everybody, I tried several times to deploy with Vite Vanilla my project on github and my website never appear Javascript. All link websites are working but JS nothing
PACKAGE.JSON FILE:
enter image description here

VITE.CONFIG.JS FILE:
enter image description here

I’m trying to up multipages but js not working, and I hope that I deploy without bugs.

Can’t get the attribute _id out of a mongoose object using NextJs

I’m using mongodb and I try to get the id of a reservation by calling the attribute reservation._id inside my page after fetching the data. When I try to print reservation._id, I only get “undefined”.

Here is my GET function and my mongoose schema for context :

import mongoose, {Schema, model, models} from "mongoose";

const ReservationSchema = new Schema({
    name : {
       type:  String,
       required : true
    },
    status : {
       type:  Boolean,
       required : true
    },
    salle : {
       type:  Boolean,
       required : true
    },
    image : {
       type:  String,
       default: "/salle_mix.png"
    },
})

const Reservation = models.Reservation || model('Reservation', ReservationSchema);

export default Reservation;
import { connectToDB } from "@utils/database";
import Reservation from "@models/reservation";

export const GET = async(request)=>{
    try {
        await connectToDB();

        const reservations = await Reservation.find({});
        return new Response(JSON.stringify(reservations), {status: 200})
    } catch(error){
        console.error("Error fetching reservations:", error);
        return new Response("Failed to fetch all reservations", {status: 500})
    }

}

I’ve already tried converting the id using .toString() but it dont seems to work.

How can I round numbers with three or more digits after the decimal point accurately?

I am in the process of developing a cart system, and encountered some challenges with rounding certain amounts during calculations. Below are the details of my cart.

itemPrice = 0.99;
itemQuantity = 10;
totalPrice = 9.90; /* 0.99 * 10 */

here I apply 25% of discount coupon on the totalPrice amount

discountedPrice = 2.475 /* (9.90 * 25) / 100 */
totalPriceAfterDiscount = 7.425 /* 9.90 - 2.475 */

Please provide instructions on how to round the discountedPrice and totalPriceAfterDiscount amounts to two decimal places, ensuring that their sum equals the totalPrice.

Upon rounding both figures, the values are as follows: discountedPrice = 2.48 and totalPriceAfterDiscount = 7.43. The sum of 2.48 and 7.43 equals 9.91.

enter image description here

HTML Canvas How to stop color mixing on edges?

So I’m trying to make a demo application, that shows how RCE learning works. User is supposed to draw colored shapes and then the neural network learns where boundaries of each color are located. The problem is that the places where 2 colors overlap mix different colors. Which results in creation of new output neurons even tho the user only used 2 colors which id say is confusing (On this image you can see how around the borders between colors many small neurons of different color are created.), so I’m trying to stop the color mixing.

I use 2 canvases the bottom one is for displaying what the user drew and the top one displays the area covered by neurons.
This is the code for the drawing (the coordinates from top canvas are divided by 5, because my code is slow (javascript is slow) and with this many points it would take ages to compute, so the underlying canvas is 25 times smaller)

draw(e: MouseEvent) {
    if (!this.isDrawing) return;
    if (this.boardCtx === null) throw new Error("Canvas not found!!");

    const rect = this.board.getBoundingClientRect();
    const x = (e.clientX - rect.left) / 5;
    const y = (e.clientY - rect.top) / 5;
    const color = (document.getElementById("colorPicker") as HTMLInputElement)
      .value;
    const size = (document.getElementById("size") as HTMLInputElement).value;

    this.boardCtx.strokeStyle = color;
    this.boardCtx.lineWidth = +size;
    this.boardCtx.lineCap = "round";

    this.boardCtx.lineTo(x, y);
    this.boardCtx.stroke();
    this.boardCtx.beginPath();
    this.boardCtx.moveTo(x, y);
  }

Is there a way to stop the color mixing? Or should i just use tresholding techniques on the picture after drawing it?

Cannot solve Uncaught TypeError: Cannot read properties of null

I’m hesitant to post this here as it seems like it should be an easy error to solve, but every option that I’ve tried doesn’t result in the error resolving.

I’m working on a application in Google Sheets where people are able to log what training they’ve completed so they can retrospectively look back at what they’ve done over a period and find any holes in their knowledge. When a user clicks on the edit button next to an entry, they should be taken to an edit page (which successfully happens) and have all the details loaded against the entry load so they are able to edit them.

The problem I’m having is when an entry is clicked on to edit, the ID number of the entry is pulled through to the edit page of the application, but none of the other information is pulled through and the console gives me the error

Uncaught TypeError: Cannot read properties of null (reading ‘trainingTopic’)

This seems to be happening in the afterEditViewLoads function in the main.html file.

From my understanding this could be occurring because the script is running before the element in the HTML has loaded fully, but my scripts are located at the bottom of my HTML file, after everything loads (as far as I can see).

The code from my main.html file is as follows:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <style>
      .nav-link {
        cursor:pointer;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <ul class="nav nav-tabs">
        <li class="nav-item">
          <div class="nav-link active" id="homeLink">Home</div>
        </li>
        <li class="nav-item">
          <div class="nav-link" id="searchLink">Search</div>
        </li>
        <li class="nav-item">
          <div class="nav-link" id="addEntryLink">Add Entry</div>
        </li>
      </ul>
      <div id="app"></div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-0pUGZvbkm6XF6gxjEnlmuGrJXVbNuzT9qBBavbLwCsOGabYfZo0T0to5eqruptLy" crossorigin="anonymous"></script>
    <script>
      var data;
      function loadView(options) {
        var id = typeof options.id === "undefined" ? "app" : options.id;
        var cb = typeof options.callback === "undefined" ? function() {} : options.callback;
        google.script.run.withSuccessHandler(function(html) {
          document.getElementById(id).innerHTML = html;
          typeof options.params === "undefined" ? cb() : cb(options.params);
        })[options.func]();
      }

      function setDataForSearch() {
        google.script.run.withSuccessHandler(function(dataReturned) {
          data = dataReturned.slice();
        }).getDataForSearch();
      }

      function search() {
        var searchInput = document.getElementById("searchInput").value.toString().toLowerCase().trim();
        var searchWords = searchInput.split(/s+/);
        var searchColumns = [1,2];
        var resultsArray = searchInput === "" ? [] : data.filter(function(r) {
          return searchWords.every(function(word) {
            return searchColumns.some(function(colIndex) {
              return r[colIndex].toString().toLowerCase().indexOf(word) !== -1
            });
          });
        });
        var searchResultsBox = document.getElementById("searchResults");
        var templateBox = document.getElementById("rowTemplate");
        var template = templateBox.content;
        searchResultsBox.innerHTML = "";
        resultsArray.forEach(function(r) {
          var tr = template.cloneNode(true);
          var entryIDColumn = tr.querySelector(".entryID");
          var trainingTopicColumn = tr.querySelector(".trainingTopic");
          var trainingProviderColumn = tr.querySelector(".trainingProvider");
          var deleteButton = tr.querySelector(".deleteButton");
          var editButton = tr.querySelector(".editButton");

          entryIDColumn.textContent = r[0];
          deleteButton.dataset.entryID = r[0];
          editButton.dataset.entryID = r[0];
          trainingTopicColumn.textContent = r[1];
          trainingProviderColumn.textContent = r[2];
          searchResultsBox.appendChild(tr);
        });
      }

      function displayConfirmationDelete(e) {
        if(e.target.dataset.buttonState === "delete") {
          e.target.previousElementSibling.classList.remove("d-none");
          e.target.textContent = "Cancel";
          e.target.dataset.buttonState = "cancel";
        } else {
          e.target.previousElementSibling.classList.add("d-none");
          e.target.textContent = "Delete";
          e.target.dataset.buttonState = "delete";
        }
      }

      function deleteEntry(e) {
        var entryID = e.target.dataset.entryID;
        google.script.run.withSuccessHandler(function() {
          e.target.closest(".resultBox").remove();
          var ids = data.map(function(r) {return r[0].toString().toLowerCase()});
          var index = ids.indexOf(entryID.toString().toLowerCase());
          data.splice(index,1);
        }).deleteById(entryID);
      }

      function afterEditViewLoads(params) {
        console.log("Checking for trainingTopic element...")
        var trainingTopicElement = document.getElementById("trainingTopic");
        console.log(trainingTopicElement);
        document.getElementById("entryID").value = params.entryID;
        google.script.run.withSuccessHandler(function(entryInfo) {
          document.getElementById("trainingTopic").value = entryInfo.trainingTopic;
          document.getElementById("trainingProvider").value = entryInfo.trainingProvider;
          document.getElementById("dateUndertaken").value = entryInfo.dateUndertaken;
          document.getElementById("trainingType").value = entryInfo.trainingType;
          document.getElementById("jobNumber").value = entryInfo.jobNumber;
          document.getElementById("trainingPurpose").value = entryInfo.trainingPurpose;
          document.getElementById("trainingOutcome").value = entryInfo.trainingOutcome;
        }).getEntryById(params.entryID);
      }

      function loadSearchView(){
        loadView({func:"loadSearchView", callback:setDataForSearch});
      }

      function loadAddEntryView(){
        loadView({func:"loadAddEntryView"});
      }

      function loadEditEntryView(){
        loadView({func:"loadEditEntryView"});
      }

      document.getElementById("searchLink").addEventListener("click",loadSearchView);
      document.getElementById("addEntryLink").addEventListener("click",loadAddEntryView);
      document.getElementById("homeLink").addEventListener("click",loadEditEntryView);

      function inputEventHandler(e) {
        if(e.target.matches("#searchInput")) {
          search();
        }
      }

      function clickEventHandler(e) {
        if(e.target.matches(".deleteButton")) {
          deleteEntry(e);
        }
        if(e.target.matches(".beforeDeleteButton")) {
          displayConfirmationDelete(e);
        }
        if(e.target.matches(".editButton")) {
          loadView({func:"loadEditEntryView",callback:afterEditViewLoads,params:{entryID:e.target.dataset.entryID}});
        }
      }

      document.getElementById("app").addEventListener("input",inputEventHandler);
      document.getElementById("app").addEventListener("click",clickEventHandler);

    </script>
  </body>
</html>

The code for the edit.html page where the details should be loaded is as follows:

<h1>Edit Entry</h1>

<div class="editEntryForm">
  <div class="mb-3">
    <label for="entryID" class="form-label"><strong>Entry ID</strong></label>
    <input type="text" class="form-control" id="entryID" readonly>
  </div>
  <div class="mb-3">
    <label for="trainingTopic" class="form-label"><strong><span style="color: red;">* </span>Training Topic</strong></label>
    <div id="trainignTopcHelp" class="form-text">This is just a headline, not a full description of the training.</div>
    <input type="text" class="form-control" id="trainingTopic" required>
  </div>
  <div class="mb-3">
    <label for="trainingProvider" class="form-label"><strong><span style="color: red;">* </span>Training Provider</strong></label>
    <input type="text" class="form-control" id="trainingProvider" required>
  </div>
  <div class="mb-3">
    <label for="dateUndertaken" class="form-label"><strong><span style="color: red;">* </span>Date Undertaken</strong></label>
    <input type="date" class="form-control" id="dateUndertaken" required>
  </div>
  <div class="mb-3">
    <label for="trainingType" class="form-label"><strong><span style="color: red;">* </span>Training Type</strong></label>
    <select class="form-select" id="trainingType" required>
      <option selected></option>
      <option value="Product representative">Product representative</option>
      <option value="Informal training/staff discussions">Informal training/staff discussions</option>
      <option value="Seminar/webinar">Seminar/webinar</option>
      <option value="Formal training course">Formal training course</option>
      <option value="Technical reading">Technical reading</option>
      <option value="ComplyNZ tech meeting">ComplyNZ tech meeting</option>
    </select>
  </div>
  <div class="mb-3">
    <label for="jobNumber" class="form-label"><strong><span style="color: red;">* </span>ComplyNZ Job Number</strong></label>
    <div id="jobNumberHelp" class="form-text">Was the training related to assessing a specific job or jobs?  If so, record the job number(s).  If not, enter N/A.</div>
    <input type="text" class="form-control" id="jobNumber" required>
  </div>
  <div class="mb-3">
    <label for="trainingPurpose" class="form-label"><strong><span style="color: red;">* </span>Training Purpose</strong></label>
    <div id="trainingPurposeHelp" class="form-text">Outline what the purpose of the training was.</div>
    <textarea class="form-control" id="trainingPurpose" rows="3" required></textarea>
  </div>
  <div class="mb-3">
    <label for="trainingOutcome" class="form-label"><strong><span style="color: red;">* </span>Training Outcome</strong></label>
    <div id="trainingPurposeHelp" class="form-text">In your own words, describe the outcome of the training, and how you will put it into effect.</div>
    <textarea class="form-control" rows="3" id="trainingOutcome" required></textarea>
  </div>
  <button class="btn btn-primary">Save Entry</button>
  <button class="btn btn-primary">Cancel Changes</button>
</div>

And finally, the code for my server side functions is as follows:

function getDataForSearch() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ws = ss.getSheetByName("Training Log");
  return ws.getRange(2,1,ws.getLastRow()-1,3).getValues();
}

function deleteById(id) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ws = ss.getSheetByName("Training Log");
  const entryIds = ws.getRange(2,1,ws.getLastRow()-1,1).getValues().map(r => r[0].toString().toLowerCase());
  const posIndex = entryIds.indexOf(id.toString().toLowerCase());
  const rowNumber = posIndex === -1 ? 0 : posIndex + 2;
  ws.deleteRow(rowNumber);
}

function getEntryById(id) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const ws = ss.getSheetByName("Training Log");
  const entryIds = ws.getRange(2,1,ws.getLastRow()-1,1).getValues().map(r => r[0].toString().toLowerCase());
  const posIndex = entryIds.indexOf(id.toString().toLowerCase());
  const rowNumber = posIndex === -1 ? 0 : posIndex + 2;
  const entryInfo = ws.getRange(rowNumber,1,1,8).getValues()[0];
  return {entryID:entryInfo[0], 
          trainingTopic:entryInfo[1], 
          trainingProvider:entryInfo[2], 
          dateUndertaken:entryInfo[3], 
          trainingType:entryInfo[4], 
          jobNumber:entryInfo[5], 
          trainingPurpose:entryInfo[6], 
          trainingOutcome:entryInfo[7]
          }
}

Apologies for the blocks of code, but I can’t seem to work out why I’m getting the error and how to fix it, so any help would be appreciated. I’ll include a link to the spreadsheet/code in question in case anyone wants to look at it in situ with the rest of the code.

https://docs.google.com/spreadsheets/d/1bIX0zFoT8LASX4uo4cboQ4ePjEOlKPhCC7wkpJg0Vrc/edit?usp=sharing

Thanks in advance!

ValidationError: User validation failed: password: Path `password` is required

    this.$__.validationError = new ValidationError(this);
                               ^

ValidationError: User validation failed: password: Path `password` is required.
    at Document.invalidate (C:UsersvicdhSlayerLegendUpdatesservernode_modulesmongooselibdocument.js:3200:32)
    at C:UsersvicdhSlayerLegendUpdatesservernode_modulesmongooselibdocument.js:2993:17
    at C:UsersvicdhSlayerLegendUpdatesservernode_modulesmongooselibschematype.js:1368:9
    at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
  errors: {
    password: ValidatorError: Path `password` is required.
        at validate (C:UsersvicdhSlayerLegendUpdatesservernode_modulesmongooselibschematype.js:1365:13)
        at SchemaType.doValidate (C:UsersvicdhSlayerLegendUpdatesservernode_modulesmongooselibschematype.js:1349:7)
        at C:UsersvicdhSlayerLegendUpdatesservernode_modulesmongooselibdocument.js:2985:18
        at process.processTicksAndRejections (node:internal/process/task_queues:77:11) {
      properties: {
        validator: [Function (anonymous)],
        message: 'Path `password` is required.',
        type: 'required',
        path: 'password',
        fullPath: undefined,
        value: undefined
      },
      kind: 'required',
      path: 'password',
      value: undefined,
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    }
  },
  _message: 'User validation failed'
}

model: user.js

const mongoose = require('mongoose');
const { Schema } = mongoose;
const bcrypt = require('bcrypt');

const userSchema = new Schema({
  username: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true,
    minlength: 5
  },
});


// set up pre-save middleware to create password
userSchema.pre('save', async function(next) {
  try {
    // Check if the password field is modified and not empty
    if (this.isModified('password') && this.password) {
      const saltRounds = 10;
      this.password = await bcrypt.hash(this.password, saltRounds);
    }
    next();
  } catch (error) {
    console.log(error); // Pass error to the next middleware
  }
});

// Method to compare the incoming password with the hashed password
userSchema.methods.isCorrectPassword = async function(password) {
  return await bcrypt.compare(password, this.password);
};



const Users = mongoose.model('User', userSchema);

module.exports = Users;

schemas: resolvers.js

const User = require('../models/user');
const bcrypt = require('bcryptjs');
const resolvers = {
  Query: {
    user: async () => { 
      try {
        const user = await User.findOne();
        if(user){
          return console.log('User found: ', user);
        }
        const successful = console.log('User found: ', user);
        res.status(200).json(successful);
        return user;
      } catch (error) {
        console.log(error);
        throw new Error('Error fetching user data');
      }
    }
  },
  Mutation: {
    signup: async (_, { username, password }) => {
      try {
        const hashedPassword = await bcrypt.hash(password, 10);
        const user = await User.create({ username, password: hashedPassword })
        const savedUser = await User.save(); 
        const successful =console.log('User created: ', user);
        res.status(200).json(savedUser + successful);
        return user;
      } catch (error) {
        throw new Error('Error creating user');
      }
    },
    login: async (_, { username, password }) => {
      try {
        const user = await User.findOne({ username});
        if (!user) {
          throw new Error('User not found');
        }
        const passwordMatch = await bcrypt.compareSync(password, User.password);
        if (passwordMatch === false) {
          throw new Error("incorrect password " + console.log(passwordMatch) + console.log(user.password) + console.log(Error));
        } else if (passwordMatch === true){
          console.log(passwordMatch);
        }
           console.log('Login successful');
        return user;
      } catch (error) {
        throw new Error(console.error('Error logging in: ', error));
      }
    }
  }
}
module.exports = resolvers;

schemas: typeDefs.js

const typeDefs = `
  type User {
    username: String
    password: String
  }

  type Query {
    user: User
  }

  type Mutation {
    signup(
      username: String!,
      password: String!
    ): User

    login(
      username: String!,
      password: String!
    ): User
  }
`;

module.exports = typeDefs;

Where am I going wrong? I can’t seem to pinpoint the error. When i remove the required: true, I end up getting this Could not connect to MongoDB MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 So I do not know if they are related or not. But in my opinion i believe the MongoDB one seems to be related to with some error in the server.js or connection.js file. I’ve tried doing throw new Error and console logging errors.

Identifiers Errors

I have some problems with my code im trying to validade if the HTML file that my program reads have identifier in in case it have perfect the problem is that when my .java reads the file and create the .txt that it have to generate the program reads everything as a identifier

        String line;
        int lineNumber = 1;

        while ((line = reader.readLine()) != null) {
            // Write enumerated lines to the output file
            writer.write(String.format("%04d", lineNumber) + " " + line + "n"); 
           
            String[] tokens = line.split("\s+");

            for (String token : tokens) {
                // Use regular expression to validate the identifier
                if (!token.matches("[a-zA-Z_\p{L}][\p{L}0-9_]*")) {
                    // If the token is not a valid identifier, write to the output file
                    writer.write("Error at line " + lineNumber + ": Invalid token -> " + token + "n");
                } else {
                    // If the token is an identifier, check if it's a reserved word in JavaScript
                    boolean isReserved = false;
                    for (String reserved : ReservedWords) {
                        if (token.equals(reserved)) {
                            // If the token matches a reserved word, mark it as reserved
                            isReserved = true;
                            break;
                        }
                    }

Error on line 1: Invalid identifier -> <!DOCTYPE
Error on line 1: Invalid identifier -> html>
Error on line 1: Invalid identifier -> <html>
Error on line 1: Invalid identifier -> <head>

the .txt show me this, but I just need to show me error if the identifier is wrong,not every single line in the code.