How to uncheck a specific row in Kendo Grid select column in ASP.NET MVC using JavaScript and jQuery?

I have a Kendo Grid in my ASP.NET MVC 5 project. One of the columns is a select column and I am trying to deselect a checkbox if it satisfies a sepecific condition. I have managed to deselect the checkbox. The issue is it is only changing the UI but not removing the deselected from this.select(). Just uncheck the specific row that made the condition = true and keep the ones that are false selected.

In summary, if the condition = true, I want to uncheck the box, remove it from this.select(), remove it from this.selectedKeyNames() and remove it from this._selectIds(). NOT Delete the row from the table in the UI.

The code below is not the actual code I am using but something similar to it. The code below is probably not going to work.

function onChange(e) {
   var selectedRows = this.select();
   for(var i = 0; i < selectedRows.length; i++){
       selectedRows[i].find("input[type='checkbox']").prop('checked', false);
       if( date1 > date2) {
          alert("You can't select this");
    }
  }
}

Cascading Dropdown, but in any selection order

I am trying to do cascading dropdown boxes for 4 fields, but instead of selecting in a set order (i.e. Country, State, City, Zip), I would like to be able to select in any possible order (i.e. pick City first, and all other dropdown’s options update). Can someone please point me in the right direction on finding potential resources/options for this? Also is there a term for this, since I’m assuming it would no longer be cascading with this change?

In the example below I have 2 states with the city Portland. Currently, I can select the Country (USA), then either the state of Maine or Oregon to and Portland will be one of the options for City. I would like it so at page load, all potential options for each select box are loaded, so I could choose to pick city – Portland first and Country, State, and Zip options will update to reflect the filtered options.

4 Dropdowns – country, state, city, zip

<select id="country" onchange="updateState()">
  <option value="">Select Country</option>
  <option value="USA">USA</option>
  <option value="India">India</option>
</select>

<label for="state">State:</label>
<select id="state" onchange="updateCity()">
  <option value="">Select State</option>
</select>

<label for="city">City:</label>
<select id="city" onchange="updateZip()">
  <option value="">Select City</option>
</select>

<label for="zip">Zip:</label>
<select id="zip">
  <option value="">Select Zip</option>
</select> 

var countryStateInfo. In this example you can see there are 2 cities of Portland – 1 in Maine, 1 in Oregon.

var countryStateInfo = {
    "USA": {
        "California": {
            "Los Angeles": ["90001", "90002", "90003", "90004"],
            "San Diego": ["92093", "92101"]
        },
    "Maine": {
            "Portland": ["04101"],
            "Augusta": ["04330"]
        },
    "Oregon": {
            "Portland": ["97035","97203"],
            "Eugene": ["97404"]
        }
    },
    "India": {
        "Assam": {
            "Dispur": ["781005"],
            "Guwahati" : ["781030", "781030"]
        },
        "Gujarat": {
            "Vadodara" : ["390011", "390020"],
            "Surat" : ["395006", "395002"]
        }
    }
}

Current javescript which is handling cascading filtering (only in 1 direction)

  const countrySelect = document.getElementById("country");
  const stateSelect = document.getElementById("state");
  const citySelect = document.getElementById("city");
  const zipSelect = document.getElementById("zip");

  // Update the state
  function updateState() {
    stateSelect.innerHTML = "<option value=''>Select State</option>";
    citySelect.innerHTML = "<option value=''>Select City</option>";
    zipSelect.innerHTML = "<option value=''>Select Zip</option>";

    const selectedCountry = countrySelect.value;
    if (selectedCountry !== "") {
      const states = countryStateInfo[selectedCountry];
      for (const state in states) {
        const option = document.createElement("option");
        option.value = state;
        option.textContent = state;
        stateSelect.appendChild(option);
      }
    }
  }

  // Update the city
  function updateCity() {
    citySelect.innerHTML = "<option value=''>Select City</option>";
    zipSelect.innerHTML = "<option value=''>Select Zip</option>";

    const selectedCountry = countrySelect.value;
    const selectedState = stateSelect.value;
    if (selectedCountry !== "" && selectedState !== "") {
      const cities = countryStateInfo[selectedCountry][selectedState];
      for (const city in cities) {
        const option = document.createElement("option");
        option.value = city;
        option.textContent = city;
        citySelect.appendChild(option);
      }
    }
  }

  // Update the zip
  function updateZip() {
    zipSelect.innerHTML = "<option value=''>Select Zip</option>";

    const selectedCountry = countrySelect.value;
    const selectedState = stateSelect.value;
    const selectedCity = citySelect.value;
    if (
      selectedCountry !== "" &&
      selectedState !== "" &&
      selectedCity !== ""
    ) {
      const zips = countryStateInfo[selectedCountry][selectedState][selectedCity];
      for (const zip of zips) {
        const option = document.createElement("option");
        option.value = zip;
        option.textContent = zip;
        zipSelect.appendChild(option);
      }
    }
  }

Permission Issue and Incorrect Data Placement in Google Sheets Code

I’m writing my first code in Google Scripts. I’m encountering an issue with my code where it doesn’t have the necessary permissions to access Google Sheets. I’m getting the error message “Exception: You do not have permission to call SpreadsheetApp.openById” when trying to execute the code. The code is intended to modify and retrieve data from a Google Sheets spreadsheet.

In addition to the permission issue, there is a specific behavior in the code that needs to be addressed. The code is designed to transfer information to a specific row within the Google Sheets spreadsheet, but it is currently transferring the data to a location outside the spreadsheet. For example, if there is an empty space available in the spreadsheet at row 9, the code mistakenly transfers the information to a different location outside the table where there is no formatting or structure. I attached my code below

function onEdit(e) {
  var sourceSheet = e.source.getActiveSheet();
  var editedRange = e.range;
  var column = editedRange.getColumn();
  var row = editedRange.getRow();
  
  if (column > 1 && row > 1) {
    var technicianNameCell = sourceSheet.getRange(row, 13);
    var technicianName = technicianNameCell.getValue();
    var dataValues = [];
    
    var columnsToCopy = [1, 2, 3, 4, 5, 6, 7, 11, 12]; // A, B, C, D, E, F, G, J
    
    for (var i = 0; i < columnsToCopy.length; i++) {
      var value = sourceSheet.getRange(row, columnsToCopy[i]).getValue();
      dataValues.push(value);
    }
    
    var targetSpreadsheetIds = {
      "technicianName": {
        "spreadsheetId": "spreadsheetId",
        "sheetName": "sheetName"
      },
      "technicianName": {
        "spreadsheetId": "spreadsheetId",
        "sheetName": "sheetName"
      },
      "technicianName": {
        "spreadsheetId": "spreadsheetId",
        "sheetName": "sheetName"
      }
    };
    
    var targetSpreadsheet = targetSpreadsheetIds[technicianName];
    
    if (targetSpreadsheet) {
      var targetSheet = SpreadsheetApp.openById(targetSpreadsheet.spreadsheetId).getSheetByName(targetSpreadsheet.sheetName);
      var lastRow = targetSheet.getLastRow();
      var firstEmptyRow = lastRow + 1;
      
      var targetRange = targetSheet.getRange(firstEmptyRow, 1, 1, dataValues.length);
      targetRange.setValues([dataValues]);
    }
  }
}

I attempted to implement a code that modifies and retrieves data from a Google Sheets spreadsheet. I expected the code to have the necessary permissions to access the spreadsheet and perform the required operations. Specifically, I expected the code to fill the empty space within the spreadsheet, with the transferred information while preserving the formatting and structure of the table.

However, what actually resulted was that the code encountered a permission issue. The error message “Exception: You do not have permission to call SpreadsheetApp.openById” was displayed when executing the code. Additionally, the transferred information was placed in a location outside the table where there was no formatting or structure.

How to make a function trigger just once?

I have different forms and in each one of the forms i want to generate a span tag after a label.

I am trying to achieve this with jQuery with the following function:

function generate_span(obj){
    var spanPosition = obj;
    var spanText = "<span>In the 'Output text format', user can add replacing vars formated with $catN, N will be the number of the category. The $cat1 is the category with most votes, $cat2, comes second and so on. i.e.: Popular amongst Family with $cat1 and $cat2, or This is great for $cat1 and $cat2 n</span>";
    spanPosition.after(spanText);
    

}

This function i trigger it inside a function that iterates all my forms:

function iterate_output_fields(){
    let outputs = jQuery('.cheryr-ui-repeater-content-box').find('[data-repeater-control-name="output-text-format"] label');
    
    outputs.each(function(e){
        generate_span(jQuery(this));
    })
}

And i am calling this function and those above inside the document ready function

iterate_output_fields();

My function is being triggered and the span is created properly. The issue is the following, i have a function that displays or not some fields of the form depending on the value of a select field.

function handle_select_change(obj) {
    var selectField = jQuery(obj);
    var selectedValue = selectField.val();
    var textareaField = obj.parents('.cheryr-ui-repeater-content-box').find('textarea');
    var outputText = obj.parents('.cheryr-ui-repeater-content-box').find('[data-repeater-control-name="output-text-format"]');
    


    if (selectedValue !== "multiple-choice") {
        textareaField.css("display", "none");
        textareaField.siblings().css("display", "none");
        outputText.css("display", "none");

    } else {
        
        textareaField.css("display", "block");
        textareaField.siblings().css("display", "block");
        if(!textareaField.val()){
            textareaField.attr("placeholder", "everyone:Everyone nfamily-kids:Family with Kids nteens:Teenagers nthrill-seekers:Thrill Seekers ncouples:Couples");
        }
        outputText.css("display", "block");
    }   
    
}

For some reason as the value of my select is changed the span is created again. So if i have a select with value multiple-choice the span is created and this is ok. If then i change the value to another one, the field is hidden, and this is also ok. But if now i change the value again to multiple-choice my function is triggered again and a new span is generated. And now i have two span tags when i should only have one.

Nextjs 13 useSearchParams returns null when using the ‘as’ prop in

I am trying to add a page id to each page in Nextjs 13 using the App Router. So I have created a custom link and I am using the as value to mask the url.

let pid = 0 // this will dynamically increase for every page but I will spare you all of that code
<Link href={`/?pid=${pid}`} as="/">
  Home
</Link>

So then in previous versions with the Pages Router you could do the following and get the pid just fine. I just tested this and it works fine.

const router = useRouter()
console.log(router.query)

// result { pid: 1}
// url show in browser http://localhost:3000

As you can see in the above example I am able to get the pid query params and not display them in the address bar. Now using the useSearchParams() hook with the App Router it just returns null every time. Did they remove this functionality from Nextjs 13? I don’t see any documentation on this when looking at either the Router docs or the Link docs for either the Pages/App respectively. Router DocsLink Docs.

I am trying to keep track of page specific data and it seems like Nextjs is trying as hard as they can to make this difficult.

— a bit of a rant feel free to ignore —

You can’t use the window.history.state because they just override this wiping anything you save away. In previous versions they would save a page key in the window.history.state so you could at least use that but now they have taken that away. So I could just leave the pid in the url but that would make a whole new set of challenges and it obviously doesn’t look as good. I know this last paragraph was a bit of a rant but I have been frustrated Nextjs’s attitude when it comes to window history for a long time and I am about to just go into the source code and change it so they just copy over existing window history state instead of completely overriding it so I can add a page id to the window history.

Get a list of all available MathJS functions [duplicate]

How to get a list of all available MathJS functions?

I expect something like: Math.getFunctionList(); // or some code that can parse this list
so I can get something like:
[
‘abs’,
‘add’,
‘cbrt’,
‘ceil’,
‘cube’,
‘divide’,
‘dotDivide’,
‘dotMultiply’,
‘dotPow’,
// …..
]

either objects with information about these functions, or anything so that I can use it as a list.

How do I make this page format to landscape?

Java to Html is printing in landscape but is formatted in portrait.Im using jsPDF and html2canvas.For some reason the page is printing in landscape but it still formating the page as portrait.This is my code.

const button = document.getElementById(‘jsPdf’);

function generatePDF() {
    
    // Choose the element that your content will be rendered to.
    const element = document.getElementById('generatePdf');
    window.jsPDF = window.jspdf.jsPDF;

    var doc = new jsPDF({
        orientation: 'landscape',
        unit:'in',
        format: [612,792]
    });

    // Source HTMLElement or a string containing HTML.

    doc.html(element, {
        callback: function (doc) {
            // Save the PDF
            doc.save('sample-document.pdf');
        },
        autoPaging: 'text',
        x: 5,
        y: 5,
        width: 250, //target width in the PDF document
        windowWidth: 1200 //window width in CSS pixels

Is there any reason why it wouldnt be switching to landscape in the print screen?enter image description here. In the picture the page is landscape but the text on it is still formatted in portrait mode as you can see by the smushed text. Its also grabbing the invisible charecters.

I tried to make a page print landscape. it turned the page into landscape in the print screen but did not format the actual page to landscape.

H10 error deploying react native project to Heroku using node

I have problems deploying my simple frontend project to heroku (I deploy my backend with java spring in another app with not problems). I tried to get help from the heroku-support, but they could not find the problem. Im using react native for the project. Ive read alot of threads and tried many hours before posting this.

in my package.json file I have:

{
“name”: “AwesomeProject2”,
“version”: “0.0.1”,
“private”: true,
“main”: “index.js”,
“type”: “module”,
“scripts”: {
“android”: “react-native run-android”,
“ios”: “react-native run-ios”,
“lint”: “eslint .”,
“start”: “node index.js”,
“test”: “jest”
},
etc

in my Procfile I have:
web: node ./index.js

The error I get is:

2023-05-23T15:32:00.000000+00:00 app[api]: Build succeeded  
2023-05-23T15:32:03.085414+00:00 heroku[web.1]: Starting process with command `node ./index.js`  
2023-05-23T15:32:04.338023+00:00 app[web.1]: node:internal/errors:490  
2023-05-23T15:32:04.338070+00:00 app[web.1]: ErrorCaptureStackTrace(err);  
2023-05-23T15:32:10.297744+00:00 app[web.1]: at ModuleWrap.<anonymous>       (node:internal/modules/esm/module_job:77:40)  
2023-05-23T15:32:10.297745+00:00 app[web.1]: at link (node:internal/modules/esm/module_job:76:36) {  
2023-05-23T15:32:10.297745+00:00 app[web.1]: code: 'ERR_MODULE_NOT_FOUND'  
2023-05-23T15:32:10.297746+00:00 app[web.1]: }  
2023-05-23T15:32:10.297746+00:00 app[web.1]:  
2023-05-23T15:32:10.297746+00:00 app[web.1]: Node.js v18.16.0  
2023-05-23T15:32:10.422614+00:00 heroku[web.1]: Process exited with status 1  
2023-05-23T15:32:10.454163+00:00 heroku[web.1]: State changed from starting to crashed  
2023-05-23T15:32:12.908871+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET     path="/" host=pleasework123-frontend.herokuapp.com request_id=811ba6a8-e29b-4971-b774-d150dc2a4273 fw

Ive tried changing Procfile and package.json settings. Ive tried using react vite. Ive tried reinstallning node.

Why am I getting ‘user.matchPassword is not a function’ error when calling my API with bcryptjs in Node.js and Express?

const userAuth = asyncHandler( async (req,res)=>{
    const  { email , password } = req.body;

    const user = User.findOne({email});

    if(user && (await user.matchPassword(password))){
        generateToken(res,user._id)
        res.status(201).json({
            _id:user._id,
            name:user.name,
            email:user.email
        })
       }else{
        res.status(401);
        throw new Error('Incorrect Password or Email');
        }
});
{
    "message": "user.matchPassword is not a function",
    "stack": "TypeError: user.matchPassword is not a functionn    at file:///C:/Users/siroh/OneDrive/Desktop/MERN-Auth/server/Controllers/userControllers.js:45:28n    at asyncUtilWrap (C:\Users\siroh\OneDrive\Desktop\MERN-Auth\node_modules\express-async-handler\index.js:3:20)n    at Layer.handle [as handle_request] (C:\Users\siroh\OneDrive\Desktop\MERN-Auth\node_modules\express\lib\router\layer.js:95:5)n    at next (C:\Users\siroh\OneDrive\Desktop\MERN-Auth\node_modules\express\lib\router\route.js:144:13)n    at Route.dispatch (C:\Users\siroh\OneDrive\Desktop\MERN-Auth\node_modules\express\lib\router\route.js:114:3)n    at Layer.handle [as handle_request] (C:\Users\siroh\OneDrive\Desktop\MERN-Auth\node_modules\express\lib\router\layer.js:95:5)n    at C:\Users\siroh\OneDrive\Desktop\MERN-Auth\node_modules\express\lib\router\index.js:284:15n    at Function.process_params (C:\Users\siroh\OneDrive\Desktop\MERN-Auth\node_modules\express\lib\router\index.js:346:12)n    at next (C:\Users\siroh\OneDrive\Desktop\MERN-Auth\node_modules\express\lib\router\index.js:280:10)n    at Function.handle (C:\Users\siroh\OneDrive\Desktop\MERN-Auth\node_modules\express\lib\router\index.js:175:3)"
}

Displaying a div based on select element value with JavaScript and CSS

I was trying to display a div and hide other div when the select element hold the corresponding value.

I created a select element with 4 options, the default with empty value plus three others, lower, upper, higher. I placed three hidden div elements below containing the content for each of the 3 options: lower, upper and higher. I wanted to show and hide each div based on the values of the select element. Here is my code:

         <div class="">
            <div class="">
              <label class="">Department
                <select id="departments" name="departments">
                  <option value="" selected>Select Department...</option>
                  <option value="lower">Lower</option>
                  <option value="upper">Upper</option>
                  <option value="higher">Higher</option>
                </select>
              </label>
            </div>
          </div>

          <div class="lower-dep">
            <div class="input-check">
              <input type="checkbox" id="color1" name="color1" value="Red">
              <label for="color1"> Red</label>
            </div>
          </div>

          <div class="upper-dep">
            <div class="input-check">
              <input type="checkbox" id="color1" name="color1" value="Red">
              <label for="color1"> Red</label>
            </div>
          </div>

          <div class="higher-dep">
            <div class="input-check">
              <input type="checkbox" id="color1" name="color1" value="Red">
              <label for="color1"> Red</label>
            </div>
          </div>

       From my css file:
       .lower-dep, .upper-dep, .higher-dep {
        display: none;
        }

          
  <script>
    const departments = document.querySelector("#departments");
    const lowerdep = document.querySelector(".lower-dep");
    const upperdep = document.querySelector(".upper-dep");
    const higherdep = document.querySelector(".higher-dep");

    if (departments.value = "") {
      lowerdep.style.display = "none";
      upperdep.style.display = "none";
      higherdep.style.display = "none";

    } else if (departments.value = "lower") {
      lowerdep.style.display = "block";

    } else if (departments.value = "upper") {
      upperdep.style.display = "block";

    } else {
      higherdep.style.display = "block";
    }

  </script>

login created token, but still get an error react

I have a react native application. And an login service call.

And if I trigger the login service call the token has been created. But I still get an login failed error. So this is the service call:

export const loginRequest = async (email, password) => {
    try {
        const response = await fetch("http://192.168.1.65:8000/api/user/token/", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                email: email,
                password: password,
            }),
        });

        const data = await response.json();
        console.log(data);

        if (response.ok) {
            await AsyncStorage.setItem("Token", data.access);

            return true;
        } else {
            throw new Error(data.detail);
        }
    } catch (error) {
        throw new Error("Login failed");
    }
};

And in the console I see that the token has created:

 Object {
  "token": "a608aa4c5c584f288c6afce37ef963985ec64f1c",
}


Question: how to proper login?

WebSocket connection to ‘wss://127.0.0.1:8080/’ failed

Problem Context

I have an express server serving my webpage with HTTPS via the following code:

const express = require("express");
const app = express();
const fs = require("fs");
const https = require("https");

const sslKey = fs.readFileSync(__dirname + "/certs/key.pem");
const sslCert = fs.readFileSync(__dirname + "/certs/cert.pem");

app.get("/", (req, res) => {
  res.sendFile(__dirname + "/pages/index.html");
});

https
  .createServer(
    {
      key: sslKey,
      cert: sslCert,
    },
    app
  )
  .listen(3000);

The webpage is connecting to a Python websocket server running on my computer on port 8080 via the following code:

const server = "127.0.0.1";
const ws = new WebSocket(`wss://${server}:8080`);

And my Python websocket server is running based on the following code:

import asyncio
import websockets
import random
import string
import subprocess
import os
import logging
import ssl
import speech_recognition as sr
r = sr.Recognizer()

logging.basicConfig()

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)

ssl_cert = "certs/cert.pem"
ssl_key = "certs/key.pem"

ssl_context.load_cert_chain(ssl_cert, keyfile=ssl_key)

async def server(websocket, path):
    await call_some_custom_irrelevant_function_with_the_socket(websocket, path)


start_server = websockets.serve(
    server, "127.0.0.1", 8080, ssl=ssl_context, origins="*")


asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

There are separate TLS/SSL certificates being used by both, the express server, and the Python websocket server. I generated them and granted them trust on my local computer using mkcert, a way to generate and automatically grant certificates trusted authority on your local device. Certificates for both are placed inside the certs directory of each’s project folder and appropriately referenced in the code.

I run the Python websocket server with python app.py in its directory successfully, and start my express app using nodemon app.js in its directory as well, being able to access https://localhost:3000 in a secure manner.

Problem

When I open my webpage and pull the trigger to connect to the websocket server (Irrelevant code as it’s just an event handler on a button that calls the websocket connection code I gave above and some other irrelevant socket event stuff), it waits for like 1 second and then gives out the following error:

WebSocket connection to 'wss://127.0.0.1:8080/' failed: 

I researched a bit regarding this and it seems that there may be some sort of problem with how I am integrating my TLS/SSL certificates, however, I am clueless as to exactly what. If someone could help me out in fixing this, or even point me in the right direction, I’d be grateful.

Jest & Supertest not working with Express middleware routers

I’m using Node v18.8.0 and Express v4.18.2.
Say I had this app where I wanted to get a list of all phone codes from each country. This is my model:

// models/misc/phoneCodeModel.js
const mongoose = require('mongoose');
const phoneCodeSchema = new mongoose.Schema({
    countryCodes: {
        type: [String],
        required: [true, `To add a phone code you must specify the 'countryCodes' array`]
    },
    countryName: {
        type: String,
        required: [true, `To add a phone code you must specify the 'countryName'`]
    }
});

const PhoneCode = mongoose.model(`PhoneCode`, phoneCodeSchema);
module.exports = PhoneCode;

This is the controller:

// controllers/misc/phoneCodeController.js
const PhoneCode = require(`./../../models/misc/phoneCodeModel`);

exports.getPhoneCodes = async (req, res, next) => {
    const phoneCodes = await PhoneCode.find();

    res.status(200).json({
        status: 'success',
        data: {
            phoneCodes
        }
    });
};

exports.getPhoneCode = async (req, res, next) => {
    const phoneCode = await PhoneCode.findById(req.params.id);

    res.status(200).json({
        status: 'success',
        data: {
            phoneCode
        }
    });
};

This is the router:

// routes/misc/phoneCodeRoutes.js
const express = require('express');

const phoneCodeController = require(`./../../controllers/misc/phoneCodeController`);

const router = express.Router();
router.route('/')
    .get(phoneCodeController.getPhoneCodes);
router.route('/:id')
    .get(phoneCodeController.getPhoneCode);
module.exports = router;

This is the app.js file:

const express =  require('express');
const app = express();
app.use(express.json()); // Parse request/response into JSON objects

const phoneCodeRouter = require(`./routes/misc/phoneCodeRoutes`);

app.use('/api/v1/phoneCodes', phoneCodeRouter);
app.get('/test', (req, res) => {
    res.send("test")
});

app.all('*', (req, res, next) => {
    res.status(404).json({
        status: 'fail',
        message: `Can't find ${req.originalUrl} on this server!`
    });
});

module.exports = app;

There’s a server.js file that starts the app on port 8080…
Now the real question, if I try to make a test using Jest and Supertest:

// tests/test.js
const request = require('supertest');
const app = require('./../app');

describe('Phone codes', () => {
    
    describe('GET /phoneCodes', () => {
        test('Should response with a 200 status code', () => {
            return request(app).get('/api/v1/phoneCodes').expect(200);
        });
    });
    
});

I get the following error:

 FAIL  test/test.js (10.776 s)
  Phone codes
    GET /phoneCodes
      × Should response with a 200 status code (5016 ms)

  ● Phone codes › GET /phoneCodes › Should response with a 200 status code

    thrown: "Exceeded timeout of 5000 ms for a test.
    Add a timeout value to this test to increase the timeout, if this is a long-running test. See https://jestjs.io/docs/api#testname-fn-timeout."

       5 |
       6 |      describe('GET /phoneCodes', () => {
    >  7 |              test('Should response with a 200 status code', () => {
         |              ^
       8 |                      return request(app).get('/api/v1/phoneCodes').expect(200);
       9 |              });
      10 |      });

      at test (test/test.js:7:3)
      at describe (test/test.js:6:2)
      at Object.describe (test/test.js:4:1)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        11.652 s
Ran all test suites.

Meanwhile from Postman I get the list correctly, and if I try to make the test on the ‘/test’ endpoint it works correctly:

const request = require('supertest');
const app = require('./../app');

describe('Phone codes', () => {
    
    describe('GET /phoneCodes', () => {
        test('Should response with a 200 status code', () => {
            return request(app).get('/test').expect(200);
        });
    });
    
});
 PASS  test/test.js
  Phone codes
    GET /phoneCodes
      √ Should response with a 200 status code (46 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.003 s, estimated 11 s
Ran all test suites.

Am I missing something? Why is it not working with my Express routes? I’m using Jest v29.5.0 and Supertest v6.3.3

I looked up the Supertest docs on NPM and used it’s default methods and chained them like in their examples (with and without the ‘done’ parameter), but no luck. I tried making async functions myself and evaluating the response later, same result. I don’t know what else to do. I tried increasing the timeout value as the error says but it doesn’t work either.

Date and time will need to display on click in the input field

I have the rest of the JavaScript code on how to upload it to view this error and get a solution for it. Can anyone tell me how to upload arrowed 70000 character lines of bootstrap-datetimepicker JavaScript code?

(function(factory){
 if (typeof define === 'function' && define.amd)
      define(['jquery'], factory);
    else if (typeof exports === 'object')
      factory(require('jquery'));
    else
      factory(jQuery);

}

(function($, undefined){
var DPGlobal = {
    modes:            [
      {
        clsName: 'minutes',
        navFnc:  'Hours',
        navStep: 1
      },
      {
        clsName: 'hours',
        navFnc:  'Date',
        navStep: 1
      },
      {
        clsName: 'days',
        navFnc:  'Month',
        navStep: 1
      },
      {
        clsName: 'months',
        navFnc:  'FullYear',
        navStep: 1
      },
      {
        clsName: 'years',
        navFnc:  'FullYear',
        navStep: 10
      }
    ],
    isLeapYear:       function (year) {
      return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0))
    },
    getDaysInMonth:   function (year, month) {
      return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
    },
    getDefaultFormat: function (type, field) {
      if (type === 'standard') {
        if (field === 'input')
          return 'yyyy-mm-dd hh:ii';
        else
          return 'yyyy-mm-dd hh:ii:ss';
      } else if (type === 'php') {
        if (field === 'input')
          return 'Y-m-d H:i';
        else
          return 'Y-m-d H:i:s';
      } else {
        throw new Error('Invalid format type.');
      }
    },
    validParts: function (type) {
      if (type === 'standard') {
        return /t|hh?|HH?|p|P|z|Z|ii?|ss?|dd?|DD?|mm?|MM?|yy(?:yy)?/g;
      } else if (type === 'php') {
        return /[dDjlNwzFmMnStyYaABgGhHis]/g;
      } else {
        throw new Error('Invalid format type.');
      }
    },
    nonpunctuation: /[^ -/:-@[-`{-~tnrTZ]+/g,
    parseFormat: function (format, type) {
     
      var separators = format.replace(this.validParts(type), '').split(''),
        parts = format.match(this.validParts(type));
      if (!separators || !separators.length || !parts || parts.length === 0) {
        throw new Error('Invalid date format.');
      }
      return {separators: separators, parts: parts};
    },
    parseDate: function (date, format, language, type, timezone) {
      if (date instanceof Date) {
        var dateUTC = new Date(date.valueOf() - date.getTimezoneOffset() * 60000);
        dateUTC.setMilliseconds(0);
        return dateUTC;
      }
      if (/^d{4}-d{1,2}-d{1,2}$/.test(date)) {
        format = this.parseFormat('yyyy-mm-dd', type);
      }
      if (/^d{4}-d{1,2}-d{1,2}[T ]d{1,2}:d{1,2}$/.test(date)) {
        format = this.parseFormat('yyyy-mm-dd hh:ii', type);
      }
      if (/^d{4}-d{1,2}-d{1,2}[T ]d{1,2}:d{1,2}:d{1,2}[Z]{0,1}$/.test(date)) {
        format = this.parseFormat('yyyy-mm-dd hh:ii:ss', type);
      }
      if (/^[-+]d+[dmwy]([s,]+[-+]d+[dmwy])*$/.test(date)) {
        var part_re = /([-+]d+)([dmwy])/,
          parts = date.match(/([-+]d+)([dmwy])/g),
          part, dir;
        date = new Date();
        for (var i = 0; i < parts.length; i++) {
          part = part_re.exec(parts[i]);
          dir = parseInt(part[1]);
          switch (part[2]) {
            case 'd':
              date.setUTCDate(date.getUTCDate() + dir);
              break;
            case 'm':
              date = Datetimepicker.prototype.moveMonth.call(Datetimepicker.prototype, date, dir);
              break;
            case 'w':
              date.setUTCDate(date.getUTCDate() + dir * 7);
              break;
            case 'y':
              date = Datetimepicker.prototype.moveYear.call(Datetimepicker.prototype, date, dir);
              break;
          }
        }
        return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), 0);
      }
      var parts = date && date.toString().match(this.nonpunctuation) || [],
        date = new Date(0, 0, 0, 0, 0, 0, 0),
        parsed = {},
        setters_order = ['hh', 'h', 'ii', 'i', 'ss', 's', 'yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'D', 'DD', 'd', 'dd', 'H', 'HH', 'p', 'P', 'z', 'Z'],
        setters_map = {
          hh:   function (d, v) {
            return d.setUTCHours(v);
          },
          h:    function (d, v) {
            return d.setUTCHours(v);
          },
          HH:   function (d, v) {
            return d.setUTCHours(v === 12 ? 0 : v);
          },
          H:    function (d, v) {
            return d.setUTCHours(v === 12 ? 0 : v);
          },
          ii:   function (d, v) {
            return d.setUTCMinutes(v);
          },
          i:    function (d, v) {
            return d.setUTCMinutes(v);
          },
          ss:   function (d, v) {
            return d.setUTCSeconds(v);
          },
          s:    function (d, v) {
            return d.setUTCSeconds(v);
          },
          yyyy: function (d, v) {
            return d.setUTCFullYear(v);
          },
          yy:   function (d, v) {
            return d.setUTCFullYear(2000 + v);
          },
          m:    function (d, v) {
            v -= 1;
            while (v < 0) v += 12;
            v %= 12;
            d.setUTCMonth(v);
            while (d.getUTCMonth() !== v)
              if (isNaN(d.getUTCMonth()))
                return d;
              else
                d.setUTCDate(d.getUTCDate() - 1);
            return d;
          },
          d:    function (d, v) {
            return d.setUTCDate(v);
          },
          p:    function (d, v) {
            return d.setUTCHours(v === 1 ? d.getUTCHours() + 12 : d.getUTCHours());
          },
          z:    function () {
            return timezone
          }
        },
        val, filtered, part;
      setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m'];
      setters_map['dd'] = setters_map['d'];
      setters_map['P'] = setters_map['p'];
      setters_map['Z'] = setters_map['z'];
      date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
      if (parts.length === format.parts.length) {
        for (var i = 0, cnt = format.parts.length; i < cnt; i++) {
          val = parseInt(parts[i], 10);
          part = format.parts[i];
          if (isNaN(val)) {
            switch (part) {
              case 'MM':
                filtered = $(dates[language].months).filter(function () {
                  var m = this.slice(0, parts[i].length),
                    p = parts[i].slice(0, m.length);
                  return m === p;
                });
                val = $.inArray(filtered[0], dates[language].months) + 1;
                break;
              case 'M':
                filtered = $(dates[language].monthsShort).filter(function () {
                  var m = this.slice(0, parts[i].length),
                    p = parts[i].slice(0, m.length);
                  return m.toLowerCase() === p.toLowerCase();
                });
                val = $.inArray(filtered[0], dates[language].monthsShort) + 1;
                break;
              case 'p':
              case 'P':
                val = $.inArray(parts[i].toLowerCase(), dates[language].meridiem);
                break;
              case 'z':
              case 'Z':
                timezone;
                break;

            }
          }
          parsed[part] = val;
        }
        for (var i = 0, s; i < setters_order.length; i++) {
          s = setters_order[i];
          if (s in parsed && !isNaN(parsed[s]))
            setters_map[s](date, parsed[s])
        }
      }
      return date;
    },
    formatDate:       function (date, format, language, type, timezone) {
      if (date === null) {
        return '';
      }
      var val;
      if (type === 'standard') {
        val = {
          t:    date.getTime(),
         
          yy:   date.getUTCFullYear().toString().substring(2),
          yyyy: date.getUTCFullYear(),
        
          m:    date.getUTCMonth() + 1,
          M:    dates[language].monthsShort[date.getUTCMonth()],
          MM:   dates[language].months[date.getUTCMonth()],
          
          d:    date.getUTCDate(),
          D:    dates[language].daysShort[date.getUTCDay()],
          DD:   dates[language].days[date.getUTCDay()],
          p:    (dates[language].meridiem.length === 2 ? dates[language].meridiem[date.getUTCHours() < 12 ? 0 : 1] : ''),
        
          h:    date.getUTCHours(),
         
          i:    date.getUTCMinutes(),
          
          s:    date.getUTCSeconds(),
         
          z:    timezone
        };

        if (dates[language].meridiem.length === 2) {
          val.H = (val.h % 12 === 0 ? 12 : val.h % 12);
        }
        else {
          val.H = val.h;
        }
        val.HH = (val.H < 10 ? '0' : '') + val.H;
        val.P = val.p.toUpperCase();
        val.Z = val.z;
        val.hh = (val.h < 10 ? '0' : '') + val.h;
        val.ii = (val.i < 10 ? '0' : '') + val.i;
        val.ss = (val.s < 10 ? '0' : '') + val.s;
        val.dd = (val.d < 10 ? '0' : '') + val.d;
        val.mm = (val.m < 10 ? '0' : '') + val.m;
      } else if (type === 'php') {
      
        val = {
     
          y: date.getUTCFullYear().toString().substring(2),
          Y: date.getUTCFullYear(),
       
          F: dates[language].months[date.getUTCMonth()],
          M: dates[language].monthsShort[date.getUTCMonth()],
          n: date.getUTCMonth() + 1,
          t: DPGlobal.getDaysInMonth(date.getUTCFullYear(), date.getUTCMonth()),
          
          j: date.getUTCDate(),
          l: dates[language].days[date.getUTCDay()],
          D: dates[language].daysShort[date.getUTCDay()],
          w: date.getUTCDay(), 
          N: (date.getUTCDay() === 0 ? 7 : date.getUTCDay()),       
          S: (date.getUTCDate() % 10 <= dates[language].suffix.length ? dates[language].suffix[date.getUTCDate() % 10 - 1] : ''),
         
          a: (dates[language].meridiem.length === 2 ? dates[language].meridiem[date.getUTCHours() < 12 ? 0 : 1] : ''),
          g: (date.getUTCHours() % 12 === 0 ? 12 : date.getUTCHours() % 12),
          G: date.getUTCHours(),
          
          i: date.getUTCMinutes(),
        
          s: date.getUTCSeconds()
        };
        val.m = (val.n < 10 ? '0' : '') + val.n;
        val.d = (val.j < 10 ? '0' : '') + val.j;
        val.A = val.a.toString().toUpperCase();
        val.h = (val.g < 10 ? '0' : '') + val.g;
        val.H = (val.G < 10 ? '0' : '') + val.G;
        val.i = (val.i < 10 ? '0' : '') + val.i;
        val.s = (val.s < 10 ? '0' : '') + val.s;
      } else {
        throw new Error('Invalid format type.');
      }
      var date = [],
        seps = $.extend([], format.separators);
      for (var i = 0, cnt = format.parts.length; i < cnt; i++) {
        if (seps.length) {
          date.push(seps.shift());
        }
        date.push(val[format.parts[i]]);
      }
      if (seps.length) {
        date.push(seps.shift());
      }
      return date.join('');
    },
    convertViewMode:  function (viewMode) {
      switch (viewMode) {
        case 4:
        case 'decade':
          viewMode = 4;
          break;
        case 3:
        case 'year':
          viewMode = 3;
          break;
        case 2:
        case 'month':
          viewMode = 2;
          break;
        case 1:
        case 'day':
          viewMode = 1;
          break;
        case 0:
        case 'hour':
          viewMode = 0;
          break;
      }

      return viewMode;
    },
    headTemplate: '<thead>' +
                '<tr>' +
                '<th class="prev"><i class="{iconType} {leftArrow}"/></th>' +
                '<th colspan="5" class="switch"></th>' +
                '<th class="next"><i class="{iconType} {rightArrow}"/></th>' +
                '</tr>' +
      '</thead>',
    headTemplateV3: '<thead>' +
                '<tr>' +
                '<th class="prev"><span class="{iconType} {leftArrow}"></span> </th>' +
                '<th colspan="5" class="switch"></th>' +
                '<th class="next"><span class="{iconType} {rightArrow}"></span> </th>' +
                '</tr>' +
      '</thead>',
    contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
    footTemplate: '<tfoot>' + 
                    '<tr><th colspan="7" class="today"></th></tr>' +
                    '<tr><th colspan="7" class="clear"></th></tr>' +
                  '</tfoot>'
  };
  DPGlobal.template = '<div class="datetimepicker">' +
    '<div class="datetimepicker-minutes">' +
    '<table class=" table-condensed">' +
    DPGlobal.headTemplate +
    DPGlobal.contTemplate +
    DPGlobal.footTemplate +
    '</table>' +
    '</div>' +
    '<div class="datetimepicker-hours">' +
    '<table class=" table-condensed">' +
    DPGlobal.headTemplate +
    DPGlobal.contTemplate +
    DPGlobal.footTemplate +
    '</table>' +
    '</div>' +
    '<div class="datetimepicker-days">' +
    '<table class=" table-condensed">' +
    DPGlobal.headTemplate +
    '<tbody></tbody>' +
    DPGlobal.footTemplate +
    '</table>' +
    '</div>' +
    '<div class="datetimepicker-months">' +
    '<table class="table-condensed">' +
    DPGlobal.headTemplate +
    DPGlobal.contTemplate +
    DPGlobal.footTemplate +
    '</table>' +
    '</div>' +
    '<div class="datetimepicker-years">' +
    '<table class="table-condensed">' +
    DPGlobal.headTemplate +
    DPGlobal.contTemplate +
    DPGlobal.footTemplate +
    '</table>' +
    '</div>' +
    '</div>';
  DPGlobal.templateV3 = '<div class="datetimepicker">' +
    '<div class="datetimepicker-minutes">' +
    '<table class=" table-condensed">' +
    DPGlobal.headTemplateV3 +
    DPGlobal.contTemplate +
    DPGlobal.footTemplate +
    '</table>' +
    '</div>' +
    '<div class="datetimepicker-hours">' +
    '<table class=" table-condensed">' +
    DPGlobal.headTemplateV3 +
    DPGlobal.contTemplate +
    DPGlobal.footTemplate +
    '</table>' +
    '</div>' +
    '<div class="datetimepicker-days">' +
    '<table class=" table-condensed">' +
    DPGlobal.headTemplateV3 +
    '<tbody></tbody>' +
    DPGlobal.footTemplate +
    '</table>' +
    '</div>' +
    '<div class="datetimepicker-months">' +
    '<table class="table-condensed">' +
    DPGlobal.headTemplateV3 +
    DPGlobal.contTemplate +
    DPGlobal.footTemplate +
    '</table>' +
    '</div>' +
    '<div class="datetimepicker-years">' +
    '<table class="table-condensed">' +
    DPGlobal.headTemplateV3 +
    DPGlobal.contTemplate +
    DPGlobal.footTemplate +
    '</table>' +
    '</div>' +
    '</div>';
  $.fn.datetimepicker.DPGlobal = DPGlobal;



  $.fn.datetimepicker.noConflict = function () {
    $.fn.datetimepicker = old;
    return this;
  };



  $(document).on(
    'focus.datetimepicker.data-api click.datetimepicker.data-api',
    '[data-provide="datetimepicker"]',
    function (e) {
      var $this = $(this);
      if ($this.data('datetimepicker')) return;
      e.preventDefault();
      
      $this.datetimepicker('show');
    }
  );
  $(function () {
    $('[data-provide="datetimepicker-inline"]').datetimepicker();
  });
}));

$('.form_datetime').datetimepicker({        
        language:  'fr',
        weekStart: 1,
        todayBtn:  0,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        showMeridian: 1,
        
    });
.datetimepicker table tr td.active:active,
.datetimepicker table tr td.active:hover:active,
.datetimepicker table tr td.active.disabled:active,
.datetimepicker table tr td.active.disabled:hover:active,
.datetimepicker table tr td.active.active,
.datetimepicker table tr td.active:hover.active,
.datetimepicker table tr td.active.disabled.active,
.datetimepicker table tr td.active.disabled:hover.active {
    background-color: #039;
}

.datetimepicker table tr td span {
    display: block;
    width: 23%;
    height: 54px;
    line-height: 54px;
    float: left;
    margin: 1%;
    cursor: pointer;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
}

.datetimepicker .datetimepicker-hours span {
    height: 26px;
    line-height: 26px;
}

.datetimepicker .datetimepicker-hours table tr td span.hour_am,
.datetimepicker .datetimepicker-hours table tr td span.hour_pm {
    width: 14.6%;
}

.datetimepicker .datetimepicker-hours fieldset legend,
.datetimepicker .datetimepicker-minutes fieldset legend {
    margin-bottom: inherit;
    line-height: 30px;
}

.datetimepicker .datetimepicker-minutes span {
    height: 26px;
    line-height: 26px;
}

.datetimepicker table tr td span:hover {
    background: #eee;
}

.datetimepicker table tr td span.disabled,
.datetimepicker table tr td span.disabled:hover {
    background: 0;
    color: #999;
    cursor: default;
}

.datetimepicker table tr td span.active,
.datetimepicker table tr td span.active:hover,
.datetimepicker table tr td span.active.disabled,
.datetimepicker table tr td span.active.disabled:hover {
    background-color: #006dcc;
    background-image: -moz-linear-gradient(top, #08c, #04c);
    background-image: -ms-linear-gradient(top, #08c, #04c);
    background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#08c), to(#04c));
    background-image: -webkit-linear-gradient(top, #08c, #04c);
    background-image: -o-linear-gradient(top, #08c, #04c);
    background-image: linear-gradient(to bottom, #08c, #04c);
    background-repeat: repeat-x;
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0088cc', endColorstr='#0044cc', GradientType=0);
    border-color: #04c #04c #002a80;
    border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
    filter: progid:DXImageTransform.Microsoft.gradient(enabled=false);
    color: #fff;
    text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css" rel="stylesheet"/>
<input class="form-control form_datetime" data-date-format="dd-MM-yyyy hh:mm" data-link-field="dtp_input1" type="text" required autocomplete="off" data-link-format="dd-mmm-yyyy hh:mm" >

On the time selection, only one time will always be selected instead of the relative time. For example, if I select today’s date and go to the time, i.e., 11 hours and 30 minutes, that needs to get selected, and the same will need to appear on the input field, but that is not going to happen. What it is getting to display on the inenter code hereput field is 23-May-2023 23:05 instead of 23-May-2023 23:30. It will work in the am and pm sections relatively the same.

Promises resolving in different order than added

I am creating a PDF with jsPDF. In the code I have some loops, where I create promises to add images to the document.
Now I want to add a new page in between the other promises if certain conditions are met. But the page is always added before every other promise. Here is my code:

var docPromises = [];

for (var i = 0; i < usedMonths.length; i++){

  if(checkColumnPage(startPos)){
    var addPagePromise = new Promise((resolve, reject) => {
      doc.addPage();
      resolve();
    });
    docPromises.push(addPagePromise);
  }



  var imgSourceMonth = eval("img_months_" + currentMonth);

  (function(imgSrc, position) {
    var clonedStartPos = position.slice();

    var addImagePromiseMonth = calculateImageWidth(imgSrc, 20)
      .then(function(width) {
        doc.addImage(imgSrc, 'PNG', clonedStartPos[0], clonedStartPos[1], width, 20);
      })
      .catch(function(error) {
        console.error(error);
      });

    docPromises.push(addImagePromiseMonth);
  })(imgSourceMonth, startPos);

}

checkColumnPage(startPos) returns true if a new page has to be added and false if not.

I resolve the promises like this:
Promise.all(docPromises)

The second part in the loop works perfectly. The order of the image is correct.

I logged every promise action to the console and it appeared that the page was always added first, followed by every other promise.
I can’t figure out the problem… In my mind it should work like this:

Iteration 1 (checkColumnPage = false): add image promise
Iteration 2 (checkColumnPage = false): add image promise
Iteration 3 (checkColumnPage = true): add page promise, add image promise
Iteration 4 (checkColumnPage = false): add image promise

But the page always comes first. Can anyone help me with this problem? Thanks in advance.