Fetch React native

I am trying to post a simple request the request is ok but when i post wrong data it give me status 404.

const forgetpassword = async (data) => {
    try {
      const response = await fetch(
        "http://localhost:5000/api/v1/auth/forgetpassword",
        {
          method: "POST",
          headers: {
            Accept: "apllication/json",
            "Content-Type": "application/json",
          },
          body: data,
        }
      );
      if (!response.ok) {
        setError(true);
        console.log("status is", response.status, "error is", error);
        return;
      } else {
        const json = response.json();
        console.log("token", json.token);
        setResetToken(json.token);
      }
    } catch (error) {
      console.log("eroore is", error.message);
      setpincode("true");
    }
  };

This function give me this output

OUTPUT OF FUNCTION

In this picture error is false is error variable
The Error variable I declared as
const [error, setError] = useState(false);
is never set to true I dont know why this happens.
I want to navigate to new screen but if error occurs I want to stay on screen .The error variable is never set to true.

Script to email a PDF file and fit to single pages

I am running the following code:

    var activeSheet =   SpreadsheetApp.getActiveSpreadsheet().getSheetByName('FlowModelling');
    var umail = activeSheet.getRange('H1').getValue();
  Logger.log(SpreadsheetApp.getActiveSheet().getRange('H1').getValue())

   
    var message = {
      to: umail,
      subject: "Flow Modelling & Pump Selection",
      body: "Hi,nnPlease find the Flow Modelling & Pump Selection     attached.nnThank you,nAdmin at Watpump",
      name: "Watpump",
      attachments: [SpreadsheetApp.getActiveSpreadsheet().getAs(MimeType.PDF,).setName("Fluid Dynamics & Pump Selection")]
  }
     MailApp.sendEmail(message);
}

Everything works fine except the PDF pages don’t scale to fit. In my document they are scaled to fit and do so if I do a manual PDF save. I have seen script for formatting Pdf’s but do not know where to write the script (the + ‘scale=4’ seems appropriate??

Search function in jQuery/Ajax with OMDb API

I want to create a search function using jQuery/Ajax, which takes user input and matches it with results from OMDb API. The result then gets listed in a html-document BUT how do I empty the result/list when a user clears the input search field?

const baseURL = 'http://www.omdbapi.com/?';
const key = 'apikey=96da8d24';

$('#search-field').keyup(function () {

  var userInput = $.trim($(this).val());

  if (userInput.length > 2) {
    $.ajax({
      type: 'GET',
      url: baseURL + key + '&s=' + userInput,
      dataType: 'json'
    }).done(function (data) {
      //console.log(data, 'Type: ' + typeof data.Search)
      
      $('#movie-list').empty();
      
      $.each(data.Search, function (key, value) {
        
        $("#movie-list").append(`
        <li>
          <img src="${value.Poster}">
            ${value.Title}
          <span>${value.Year}</span>
        </li>
        `);
      });
    });
  }
});

Google cloud functions: functions.https.onCall returning null but the value is shown correctly in the logs

I am calling a third-party API via Axios async-await, and returning the result to a flutter application via a google cloud function. I am forced to use functions.https.onCall because flutter can’t call onRequest functions as far as I know.

The result is shown correctly in console.log in the logs of the cloud function but when the flutter app calls the function, it’s always receiving null. Why?

getSmsBalance: functions.https.onCall(async (data, context) => {
    const business_id = data.business_id;
    const collectionRef = db.collection("buser_sms");
    const snapshot = await collectionRef.where("id", "==", business_id).get();
    if (snapshot.empty) {
        console.log("No matching documents - getSMSBalance .");
        let response = {
            status: false,
        };
        return JSON.stringify(response);
    }
    snapshot.forEach((doc) => {
        if (
            doc.data().enableReservationSms == true ||
            doc.data().enableAutoReminder == true ||
            doc.data().enableReminderSms == true
        ) {
            // get balance
            (async () => {
                const balance = await getBalance(
                    doc.data().senderId,
                    doc.data().username,
                    doc.data().password
                )
                    .then((result) => {
                        let response = {
                            status: true,
                            data: result,
                        };
                        console.log("balance is " + result);
                        return JSON.stringify(response);
                    })
                    .catch((err) => {
                        console.error(`Error - getSmsBalance - ${err}`);
                        let response = {
                            status: false,
                        };
                        return JSON.stringify(response);
                    });
            })();
        }
    });
}),

Peculiar Problem when Site with Storage left Unattended

I have developed a node.js site using vue.js and webpack. I am storing one value in “Local Storage”, two in “Session Storage” and a Cookie. Everything initially works properly when accessing the site and setting these values, however if I leave the site open in the browser for an extended amount of time (e.g. 12 hours), all the pages which uses these values are broken (although the cookie is still valid) and upon refreshing a page, the debugger in Firefox stops at the following line:

Array.from(riter, function () { throw 2; });

of the function below. If I clear the cache, values and cookie, the site works properly again.

try {
  var riter = [7][ITERATOR]();
  riter['return'] = function () { SAFE_CLOSING = true; };
  // eslint-disable-next-line no-throw-literal
  Array.from(riter, function () { throw 2; });
} catch (e) { /* empty */ }

What is the root cause of this issue?

Edit/Write JSON file in React Native/JavaScript

The title says it all, I want to edit a file in React Native.

This link shows how to read it easily, I just don’t know how to edit/write it.
https://www.codevscolor.com/react-native-parse-json

App.js (snippet)

import database from './db.json'

<Text style={{fontSize: 20, color: '#ffffff', fontWeight: 'bold'}}>
{database.name}
</Text>

db.json

{
    "name" : "Paul",
    "age" : 20,
    "subject" : [
        {
            "name": "SubA",
            "grade": "B"
        },
        {
            "name" : "SubB",
            "grade" : "C"
        }
    ]
}

How do I write a cloud function which creates a user in the Firestore database once a new user gets authenticated?

So far I have written the following code:

const functions = require("firebase-functions");
const admin = require("firebase-admin");

admin.initializeApp(functions.config().firebase);

exports.addAccount = functions.auth.user().onCreate((event) => {
  const user = event.data; // The firebase user
  const id = user.uid;

  return admin
    .database()
    .ref("/users/" + id)
    .set("ok");
});

The idea here is to execute a cloud function once a new user gets created. As this happens, I want to create a new node in the Firestore database. Under the ‘users’ collection I want to add a document with the uid, which contains a bit of information, in this case a String that says ‘ok’.

When deploying this function it produces an error. How exactly should I go about creating it?

Jquery for loop and strange behavior of variables

I’m sorry, but I can’t find better title for my question, but I’ll try to better describe my problem.
I have this code:

let pdfInvoice_sub_template = [
        {text: '{i}', alignment: 'center'},
        {text: 'invoices_sub-{i}-name', alignment: 'left'},
        {text: 'invoices_sub-{i}-unit', alignment: 'center'},
    ];
temp_pdfSubTemplate = [];

for (i = 1; i <= 2; i++) {
        temp_pdfSubTemplate[i] = pdfInvoice_sub_template;
        jQuery.each(temp_pdfSubTemplate[i], function (key, val) {
                 document.write(val.text = val.text.replace(/{i}/g, i) + '</br>');
        });
}

And hoping add two elements to the object, like this:

   [
    { text: '1', alignment: 'center' },
    { text: 'invoices_sub-1-name', alignment: 'left' },
    { text: 'invoices_sub-1-unit', alignment: 'center' }
   ],
   [
    { text: '2', alignment: 'center' },
    { text: 'invoices_sub-2-name', alignment: 'left' },
    { text: 'invoices_sub-2-unit', alignment: 'center' }
   ]

But after run this code, I have:

1
invoices_sub-1-name
invoices_sub-1-unit

1
invoices_sub-1-name
invoices_sub-1-unit

Why ‘i’ not iterating?
In debug devtools I see after first iterate that pdfInvoice_sub_template have a replaced {i} with 1, but I do replace {i} in temp_pdfSubTemplate. Why is happened this way and what i must to do?
Thanks!

Here is fiddler:
https://jsfiddle.net/xf4j1qpu/1/

localStorage.getItem does not update the rows deleted in javascript. What can i do to enable this

localStorage.getItem does not update the rows deleted in javascript. What can i do to enable this.

when I refresh the page. I see the last data entered but when i delete a row. the deleted row is not is not stored

    enter code here

// const formEl = document.querySelector("form");
// const tbodyEl = document.querySelector("tbody");
// const tableEl = document.querySelector("table");
// localStorage.clear()

function onAddWebsite(e) {
  e.preventDefault();
  const website = document.getElementById("website").value;
  const url = document.getElementById("url").value;
  let data = document.querySelector("tbody").innerHTML += `
      <tr>
          <td>${url}</td>
          <td>${website}</td>
          <td><button class="deleteBtn">Delete</button></td>
      </tr>
  `;
  localStorage.setItem('data', data)
}

function onDeleteRow(e) {
  if (!e.target.classList.contains("deleteBtn")) {
    return;
  }

  const btn = e.target;
  btn.closest("tr").remove();

}

document.addEventListener('DOMContentLoaded', function() {
  document.querySelector('tbody').innerHTML = localStorage.getItem('data');
  document.querySelector('button').onclick = onAddWebsite;
  document.querySelector('table').onclick = onDeleteRow;
});

AnyChart Template: How can I set the colour of a column only once?

I am using AnyChart and am trying to set the chart to have green and Red columns. Right now I have to set the colour on every column. Is there a way to set it for all?

What I am doing:

var data = anychart.data.set([
                ["04/24/2022", 2, 6, "#ab0000", "#009933"],
                ["04/25/2022", 3, 4, "#ab0000", "#009933"],
                ["04/26/2022", 4, 2, "#ab0000", "#009933"],
                ["04/27/2022", 5, 2, "#ab0000", "#009933"],
                ["04/28/2022", 5, 2, "#ab0000", "#009933"]
            ]);

Complete Code:

<!DOCTYPE html>
<html>

<head>
    <title>JavaScript Bar Chart</title>
    <script src="https://cdn.anychart.com/releases/8.0.0/js/anychart-base.min.js"> </script>
</head>

<body>

    <div id="anychart-embed-samples-bct-stacking-02" class="anychart-embed anychart-embed-samples-bct-stacking-02">
        <script
            src="https://cdn.anychart.com/releases/8.11.0/js/anychart-base.min.js?hcode=a0c21fc77e1449cc86299c5faa067dc4"></script>
        <script
            src="https://cdn.anychart.com/releases/8.11.0/js/anychart-exports.min.js?hcode=a0c21fc77e1449cc86299c5faa067dc4"></script>
        <script
            src="https://cdn.anychart.com/releases/8.11.0/js/anychart-ui.min.js?hcode=a0c21fc77e1449cc86299c5faa067dc4"></script>
        <div id="ac_style_samples-bct-stacking-02" style="display:none;">
            html, body, #container {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            }
        </div>
        <script>(function () {
                function ac_add_to_head(el) {
                    var head = document.getElementsByTagName('head')[0];
                    head.insertBefore(el, head.firstChild);
                }
                function ac_add_link(url) {
                    var el = document.createElement('link');
                    el.rel = 'stylesheet'; el.type = 'text/css'; el.media = 'all'; el.href = url;
                    ac_add_to_head(el);
                }
                function ac_add_style(css) {
                    var ac_style = document.createElement('style');
                    if (ac_style.styleSheet) ac_style.styleSheet.cssText = css;
                    else ac_style.appendChild(document.createTextNode(css));
                    ac_add_to_head(ac_style);
                }
                ac_add_link('https://cdn.anychart.com/releases/8.11.0/css/anychart-ui.min.css?hcode=a0c21fc77e1449cc86299c5faa067dc4');
                ac_add_style(document.getElementById("ac_style_samples-bct-stacking-02").innerHTML);
                ac_add_style(".anychart-embed-samples-bct-stacking-02{width:600px;height:450px;}");
            })();</script>
        <div id="container"
            style="width: 100%; height: 100%; position: absolute; top: 0; bottom: 0; left: 0; right: 0;border:1px solid">
        </div>
        <script>
            anychart.onDocumentReady(function () {

                // create a data set
                var data = anychart.data.set([
                    ["04/24/2022", 2, 6, "#ab0000", "#009933"],
                    ["04/25/2022", 3, 4, "#ab0000", "#009933"],
                    ["04/26/2022", 4, 2, "#ab0000", "#009933"],
                    ["04/27/2022", 5, 2, "#ab0000", "#009933"],
                    ["04/28/2022", 5, 2, "#ab0000", "#009933"]
                ]);

                // map the data
                var seriesData_1 = data.mapAs({ x: 0, value: 1, fill: 3 });
                var seriesData_2 = data.mapAs({ x: 0, value: 2, fill: 4 });

                // create a chart
                var chart = anychart.column();

                chart.xScroller(true);

                /* enable the percent stacking mode
                on the default primary value scale*/
                chart.yScale().stackMode("percent");

                // set the tick interval on the value scale
                chart.yScale().ticks().interval(20);

                // create column series
                chart.column(seriesData_1);
                chart.column(seriesData_2);

                // configure labels on the x-axis
                chart.xAxis().title("Date");

                // configure labels on the y-axis
                chart.yAxis().labels().format("{%value}%");
                chart.yAxis().title("Down Percentage");

                // configure tooltips
                chart.tooltip().format("{%yPercentOfCategory}{decimalsCount:2}%");

                // set the chart title
                chart.title("Wifi Up Percentage");

                // set the container id
                chart.container("container");

                // initiate drawing the chart
                chart.draw();
            });
        </script>
    </div>
</body>

</html>

I am looking for a way to not need to copy the colours over and over. Does anyone know how I could format the fill colour to be only in the column data?

Adding a button that can allow the user to create editable draggable boxes for the user and/or redirect to a form

My goal is to create a bunch of sectioned off containers that a card into said containers. Its similar to how some Kanban Boards work. However, for the moment I wish to be able to allow the user to create these cards and drag and edit them whenever they want.

HTML

<div class="container">
        <h3>Unscheduled Projects</h3>
        <p class="draggable" draggable="true" contenteditable="true">1</p>
    </div>

    <div class="container">
        <h3>Ready To Be Developed</h3>
        <p class="draggable" draggable="true" contenteditable="true">2</p>
    </div>

    <div class="container">
        <h3>In Development</h3>
        <p class="draggable" draggable="true" contenteditable="true">3</p>
    </div>

    <div class="container">
        <h3>Ready To Review</h3>
        <p class="draggable" draggable="true" contenteditable="true">4</p>
    </div>

    <div class="container">
        <h3>Completed</h3>
        <p class="draggable" draggable="true" contenteditable="true">5</p>
    </div>

.js

const draggables = document.querySelectorAll('.draggable')
const containers = document.querySelectorAll('.container')

draggables.forEach(draggable => {
    draggable.addEventListener('dragstart', () => {
        draggable.classList.add('dragging')
    })

    draggable.addEventListener('dragend', () => {
        draggable.classList.remove('dragging')
    })
})

containers.forEach(container => {
    container.addEventListener('dragover', e => {
        e.preventDefault()
        const draggable = document.querySelector('.dragging')
        container.appendChild(draggable)
    })
})

.css

.container {
    padding: 95px;
    background-color: darkgray;
    width: 10%;
    height: 825px;
    float: left;
    border-style: solid black;
}


.draggable {
    padding: 1rem;
    background-color: grey;
    border: 1px;
    border-style: solid;
    cursor: move;
}

.draggable.dragging {
    opacity: .100;
}

TypeError : next() is not a function, Next JS API

While making an API in Next JS, where I pass three parameter to my API function (req, res, next) here is the code :

const handler = async(req,res,next) =>{
// My code

//If Error then,
return next(new ErrorHandler("Error", 500)

}

I assure that ErrorHandler is working fine, but when I call this API it gives me the following Error:

TypeError: next is not a function,
   7 | const handler = async (req, res, next) => {
   8 |   //My code
>  9 |     return next(new ErrorHandler("Not Allowed", 405));
     |           ^
  10 | }  

In Express JS we pass next parameter to call next function or error handler but it seems like it doesn’t work with Next JS. I am new in this framework so I need your help in this.

Nodes JS: CRUD Getting an individual item with a POST request form a Firestore database is not working

I have a Firestore application running (Collection: ‘students’, containing 5 documents)
One document has the id: 1

I can write with a HTML form to that collection, so i can add an individual student.
I can also get all the students in one table (Bootstrap).

But i got lost when asking for the data of an individual student.

if i open a new terminal (VS code) and give the command

$curl "http://localhost:8080/student/1"

then the requested data are shown in my terminal
{“fatherName”:”Terpstra”,”lastName”:”Gerrits”,”firstName”:”Mark”}

However: when i use this form in a HTML page

<form id="apply-form" method="post" action="http://localhost:8080/student/:id">
      <label for="id">Student ID</label>
       <input type="text" id="id" name="id" placeholder="....">
       <button class="btn btn-primary btn-sm" type="submit">Get Data</button>
</form>

fill in the textfield: 1, and click the submit button

I get as result : Cannot POST /student/:id

If i use method="GET" in this form then the result in my browser is: http://localhost:8080/student/:id?id=1

If i type in the url: http://localhost:8080/student/1, then i get the requested data
{“fatherName”:”Terpstra”,”lastName”:”Gerrits”,”firstName”:”Mark”}

This way i could check if the data request to the database gives a result the correct data.

I do not know what is going wrong with the HTML-form, this is what i use in my application:

==== studentController.js

'use strict';
const firebase = require('../db');
const Student = require('../models/student');
const firestore = firebase.firestore();
.....
// 1 of the documents from the collection
const getStudent = async (req, res, next) => {
    try {
        const id = req.params.id;
        const student = await firestore.collection('students').doc(id);
        const data = await student.get();
        //if(!data.exists) {
            if(data == null) {

            res.status(404).send('Student with the given ID not found');
        }else {
            res.send(data.data());
        }
    } catch (error) {
        res.status(400).send(error.message);
    }
}

module.exports = {
    addStudent,
    getAllStudents,
    getStudent,
    updateStudent,
    deleteStudent
}

========== student.routes.js

const express = require('express');
const {addStudent, 
       getAllStudents, 
       getStudent,
       updateStudent,
       deleteStudent
      } = require('../controllers/studentController');
// in studentController.js staan de functies uitgeschreven

const router = express.Router();

// 1 document aan de collectie toevoegen
router.post('/student', addStudent);

// alle documenten uit de collectie opvragen
router.get('/students', getAllStudents);

// 1 document uit de collectie opvragen
router.get('/student/:id', getStudent);

// 1 document uit de collectie aanpassen
router.put('/student/:id', updateStudent);

// 1 document uit de collectie verwijderen
router.delete('/student/:id', deleteStudent);

module.exports = {
    routes: router
}

============ index.js

'use strict';
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const config = require('./config');
var studentRoutes = require('./routes/student-routes');
var citieRoutes = require('./routes/citie-routes');

const app = express();

app.use(express.static(__dirname + '/public'));
app.use(express.json());

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));

// app.use('/api', studentRoutes.routes);
app.use('/', studentRoutes.routes);
app.use('/', citieRoutes.routes);

app.listen(config.port, () => console.log('App is listening on url http://localhost:' + config.port));

Retrieve paths already on HTML canvas

I am working on a little tool to measure architectural drawings from PDF files. The PDF is rendered by Mozilla pdf.js on to a canvas. Once rendered, I would like to get coordinates all the paths/lines/rects on the canvas. This is to make the tool snap to the endpoints of lines when the mouse cursor is nearby. There don’t seem to be an API for retrieving that. As it is not my code that actually renders onto the canvas, I dont path information beforehand.

What I have so far tried is, modify the pdf.js to emit the endpoints’ x,y based on moveTo and lineTo, save them in an array. Using this array I can snap correctly in simple drawings. For complex drawings, there seems to be lot of transformations applied and this simple procedure doesnt work.

Any ideas on how to go about it?