Formulário de e-mail e Google API

Eu estou com um problema e não consigo solucionar, criei um código em JS para enviar e-mails via Google API, e tbm criei um formulário HTML para receber o e-mail do usuário. Eu preciso conectar esse e-mail recebido do formulário ao parâmetro To: do código da API do Gmail.

Alguém sabe como eu posso linkar esses dois códigos?

Eu tentei criar uma VAR para receber o e-mail e declarei ele em to: mas não funcionou, também tentei fazer uma função mas não funcionou, acredito que seja problema de lógica minha. Alguém já fez isso antes?

Get a number from a string using charCodeAt

const text = "Hello team, I checked my wallet balance, there is 0,0000341 USDT, I can not buy anything";

Need to get a number using only one loop for and charCodeAt()

const parseBalance = (str) => {
  const zero = "0".charCodeAt(0);
  const nine = "9".charCodeAt(0);
  const coma = ",".charCodeAt(0);
  let num = 0,
    factor = 1;

  for (let i = str.length - 1; i >= 0; i--) {
    const char = str.charCodeAt(i);
    if (char >= zero && char <= nine) {
      num += (char - 48) * factor;
      factor *= 10;
    }
  }
  return num;
};

Need result: 0.0000341
My result is 341
Tell me how to correct the formula for writing zeros

Anchor Link scroll not working correctly when Javascript component included in page

I have a page that is mostly HTML/CSS with one Javascript component in the middle.

I am having an issue with using anchor links to jump to specific parts on the page.
For now I made a section titles Test to test the scrolling behavior.

So when I type in the URL: …/contact#Test it should jump to the Test section.

When I disable Javascript on the page it works as intended.

Also when I go into the CSS and change the Javascript Component’s display to none or set a manual height it works as well. But I don’t want to set a manual height because the component is dynamic.

But with the component enabled as it is, the page scrolls down to the bottom every time.

screenshot of the page

Why is my HTML file keeps saying file not accessed when trying to open a form link?

I have been working on a project that only consists of HTML, CSS and JavaScript and the problem aroused when I tried to test my project out, I created a button link for Contact Me (which I created another html file from the normal index file to show the form link) but when I click on it shows file not accessed. Why? And how can I fix it?

  1. I checked the anchor tag
  2. I checked the name of the file

ajax prefilter checking is not doing its work

I have the code which i am running to check that my session is check before any ajax call is made, i have added a successCheck in the code to check if its not going recursive, but it shows in network panel, it works but not in the console.

any idea what i am doing wrong here

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
  console.log(options);
  // Check if the request is an AJAX call
  if (options.type.toLowerCase() !== "post" && options.type.toLowerCase() !== "get") {
      return;
  }

  // Check if the sessionCheck option is present
  if (options.sessionCheck === false) {
    console.log('hello');
    return;
  }

  // Run the session expiration check before each AJAX call
  checkSessionBeforeAjax(jqXHR);
});

function checkSessionBeforeAjax(jqXHR) {
  // Make an AJAX call to check if the session has expired
  $.ajax({
      url: "checkSession.cfm",
      type: "POST",
      sessionCheck: false,
      success: function(response) {
        var _resp = $.parseJSON(response);
        console.log(_resp);
        var status = _resp[1];
        alert(status);
          if (status === "expired") {
              // Display a popup message to the user with a high z-index
              customSwal('success',_resp[1],
                () => { 
                  window.location.href = 'logout.cfm';
                }
            );
          }
      }
  });
}

there are many ajax calls in my code, which runs one after one, so this check is for those and it runs before each ajax request, i was also wondering if this could just check the first call i am making and show a sweetAlert and halt all others if the alert is shown and user navigates to logout screen. on click ok OK button.

React Native FileSystem.GetInfoAsync doesn’t return when a file was modified

What I want to achieve with the below code is get info for individual files so that I can sort the files according to the modified time.

const permissions =
            await StorageAccessFramework.requestDirectoryPermissionsAsync();

        if (permissions.granted) {
            try {
                let uri = permissions.directoryUri;
                let files = await StorageAccessFramework.readDirectoryAsync(
                    uri
                );
                const fileObjects = [];

                for (const file of files) {
                    const fileStat = await getInfoAsync(
                        file
                    );
                                    
                    fileObjects.push({
                        uri: fileStat.uri,
                        time: fileStat.modificationTime,
                    });
                }
                        fileObjects.sort((a, b) => b.time - a.time);

                setStatusFiles(fileObjects);
            } catch (error) {
                console.log(error);
            }
        }

I tried logging the results of the function within the loop but I only get the following info.
{“exists”: true, “isDirectory”: false, “size”: 109448, “uri”: “content://com…”}

Two cameras for one attendee in AWS Chime SDK

I’m evaluating whether the Javascript Chime SDK fits the requirements I have.

I would like to know whether the SDK will allow me to share two cameras connected to the same physical machine in a Chime meeting, but I can’t find any information.

I would still be okay with creating one attendee per camera if need be, as long as I can do it from the same browser tab.

For a bit of context, picture a booth containing a remotely controlled medical device, and a computer with two USB cameras connected to it so that a remote doctor can see the patient from two angles: I want the doctor to be able to see the video coming from both cameras, and to do that I need Chime SDK to allow me to have two video inputs in the same browser tab.

Timestamp Discrepancy Between C++ REST Client and JavaScript REST Server on Same Machine

I have a C++ REST client and a REST server running in Chrome as a JavaScript code. Both the client and server are running on the same Windows machine. However, I’m encountering a strange issue where the request received time on the server is earlier than the request sent time from the client.

Here’s a snippet of my server-side JavaScript code:

const recievedTime = performance.now();
        const timestamp = new Date(
            performance.timeOrigin + recievedTime
        ).toISOString();

And here’s a snippet of my client-side C++ code:

        // Get the current time point.
        auto now = std::chrono::system_clock::now();

        // Convert to time_t for formatting.
        std::time_t currentTimeT = std::chrono::system_clock::to_time_t(now);

        // Get the local time components (single argument to std::localtime).
        std::tm localTime = *std::localtime(&currentTimeT); // Dereference the returned pointer.

        // Create an ostringstream for formatting.
        std::ostringstream formattedTime;

        // Use put_time for efficient formatting.
        formattedTime << std::put_time(&localTime, "%Y-%m-%d");
        formattedTime << 'T';
        formattedTime << std::put_time(&localTime, "%H:%M:%S");

        // Get fractional seconds with nanosecond precision.
        auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch());
        int64_t fractionalSeconds = duration.count() % 1000000000;

        // Format milliseconds with 3-digit precision.
        formattedTime << '.' << std::setfill('0') << std::setw(3) << (fractionalSeconds / 1000000);

        // Append 'Z' for UTC time zone.
        formattedTime << 'Z';
        std::string timeStamp = formattedTime.str();


I’m expecting the server to receive the request with a timestamp that matches or is later than the timestamp generated on the client. However, I’m observing that the server’s received time is earlier.
Client sent time : 2024-03-12T09:38:03.404Z
Server receive time : 2024-03-12T09:38:03.398Z

Could someone help me understand why this discrepancy might be happening? Is there an issue with how I’m generating or handling timestamps in either the C++ client or JavaScript server code?

Post request keeps inserting null values into MySQL

Using fetch API to send a post request from two forms when the button add household is clicked the /addcustomer route works but the /add household route just adds null values into the database except for the predefined values of date_created and userid. I checked on the client side and the data is being sent properly but it is using the text/html content type even though I specified to use multiform data. Here is the code:

const fileInput = document.getElementById('fileInput');

// Select the label element
const fileInputLabel = document.querySelector('.fileInputLabel');

// Listen for changes in the file input
fileInput.addEventListener('change', function() {
    // Get the selected file
    const file = fileInput.files[0];

    // Check if a file is selected
    if (file) {
        // Update the label text with the file name
        fileInputLabel.textContent = "Uploaded Picture!";
    } else {
        // If no file is selected, revert to the default label text
        fileInputLabel.textContent = 'Uploaded image!';
    }
});

document.getElementById('addHousehold').addEventListener('click', function() {
    let rightForms = document.querySelectorAll('.right-form');
    


    // Iterate over each right-form
    rightForms.forEach((form, index) => {
        let formData = new FormData();

        // Get data from inputs in the current form
        let inputs = form.querySelectorAll('input, select');
        inputs.forEach(input => {
            if (input.type === 'file') {
                // If the input is a file input, append the file to the FormData object
                formData.append(input.name, input.files[0]);
            } else {
                formData.append(input.name, input.value);
            }
        });

        // Log the FormData object
        console.log(formData);

        // Send the form data to the Express.js API
        fetch('/addCustomer', {
            method: 'POST',
            body: formData,
            headers: {
                
                //'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.text();
        })
        .then(formData => {
            console.log('Data sent successfully:', formData);
            // Optionally, update the UI to reflect the successful submission
        })
        .catch(error => {
            console.error('Error sending data:', error);
            // Optionally, update the UI to indicate the error
        });
    });
});
document.addEventListener('DOMContentLoaded', () => {
    const addHouseholdButton = document.getElementById('addHousehold');
    addHouseholdButton.addEventListener('click', () => {
        
        const address = document.getElementById('address').value;
        const apt = document.getElementById('apt').value;
        const workphone = document.getElementById('workphone').value;
        const city = document.getElementById('city').value;
        const zipcode = document.getElementById('zipcode').value;

        const formData_contact = new FormData();
        formData_contact.append('address', address);
        formData_contact.append('apt', apt);
        formData_contact.append('workphone', workphone);
        formData_contact.append('city', city);
        formData_contact.append('zipcode', zipcode);
        
       

        fetch('/addhousehold', {
            method: 'POST',
            body: formData_contact,
            headers: {
                
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.text();
        })
        .then(formData_contact => {
            console.log('Data sent successfully:', formData_contact);
           
            // Optionally, update the UI to reflect the successful submission
        })
        .catch(error => {
            console.error('Error sending data:', error);
            // Optionally, update the UI to indicate the error
        });
    });
});
const express = require('express');
const session = require('express-session');
const mysql = require('mysql');
const app = express();
const port = 5000;
const multer = require('multer');
const upload = multer({ dest: '/public/images/' });





//Allows the user to use public folder to access views 
app.use(express.static('public'));

// MySQL connection configuration
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'letmein1',
  database: 'mydatabase'
});

//View engine 
app.set('view engine', 'ejs');

//Middle ware for sessions
app.use(session({
  secret: 'mysecret', // Change this to a long random string
  resave: false,
  saveUninitialized: true
}));

// Connect to the database
connection.connect((err) => {
  if (err) {
      console.error('Error connecting to MySQL database: ' + err.stack);
      return;
  }
  console.log('Connected to MySQL database as ID ' + connection.threadId);
});

app.use(express.json());
// Middleware to parse the body of incoming requests
app.use(express.urlencoded({ extended: true }));

// Route to handle GET requests to the login page
app.get('/', (req, res) => {
  res.render('login', { user: req.session.user });
});

//Post request for login page
app.post('/login', (req, res) => {
  const { username, password } = req.body;
  connection.query('SELECT * FROM users WHERE TRIM(username) = ? AND TRIM(password) = ?', [username.trim(), password.trim()], (error, results, fields) => {
      if (error) {
          res.send('Error retrieving user from database');
          return;
      }
      if (results.length > 0) {
        req.session.user =  results[0];
        res.redirect('/dashboard');

      } else {
        const message = 'Invalid Credentials';
        res.render('badLogin', { user: req.session.user });
      }
  });
});

//Dashboard 
app.get('/dashboard', (req, res) => {
  // Check if the user is logged in
  if (req.session.user) {
    // If user is logged in, render the dashboard page
    res.render('dashBoard', { user: req.session.user });
  } else {
    // If user is not logged in, redirect to the login page
    res.redirect('/');
  }
});

app.get('/logout', (req, res) => {
  req.session.user = null;
  res.redirect('/');
}); 

app.get('/login', (req, res) => {
  res.render('login', { user: req.session.user });
});

const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));

app.post('/addCustomer', upload.single('profilePicture'), (req, res) => {
  if (!req.session.user || !req.session.user.id) {
    res.status(403).send('User not authenticated');
    return;
  }
  const { name, dateOfBirth, relation, Year, Make, Model, VIN, CellPhone, address, apt, workphone, city, zipcode } = req.body;

  connection.query('INSERT INTO customers (name, profile_picture, dateOfBirth, relation, year, make, model, vin, cellphone) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', [name, req.file.filename, dateOfBirth, relation, Year, Make, Model, VIN, CellPhone], (error, results, fields) => {
    if (error) {
      console.error('Error storing customer data:', error);
      res.status(500).send('Error storing customer data');
      return;
    }

    console.log(req.body );

 
    
    });
  });

  app.post('/addhousehold', (req, res) => {
    // Check if the user is authenticated or any other necessary checks
    if (!req.session.user) {
        // Handle unauthenticated user
        res.status(403).send('User not authenticated');
        return;
    }

    const { address, apt, workphone, city, zipcode } = req.body;

    connection.query('INSERT INTO household (address, apt, work_phone, city, zipcode, date_created, userid) VALUES (?, ?, ?, ?, ?, NOW(), ?)', [address, apt, workphone, city, zipcode, req.session.user.id], (householdError, householdResults, householdFields) => {
        if (householdError) {
            console.error('Error storing household data:', householdError);
            res.status(500).send('Error storing household data');
            return;
        }
        console.log(req.body);

        console.log('Household data stored successfully');
        res.status(200).send('Customer and household data stored successfully');
    });
});



/*app.post('/addCustomer', upload.single('profilePicture'), (req, res) => {
  const { name, dateOfBirth, relation, Year, Make, Model, VIN, CellPhone } = req.body;

  connection.query('INSERT INTO customers (name, profile_picture, dateOfBirth, relation, year, make, model, vin, cellphone) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)', [name, req.file.filename, dateOfBirth, relation, Year, Make, Model, VIN, CellPhone], (error, results, fields) => {
    if (error) {
      console.error('Error storing customer data:', error);
      res.status(500).send('Error storing customer data');
      return;
    }
    console.log('Customer data stored successfully');
    res.status(200).send('Customer data stored successfully');
 

    const { address, apt, workPhone, city, zipcode, userId } = req.body;
  connection.query('INSERT INTO household (address, apt, work_phone, city, zipcode, date_created, user_id) VALUES (?, ?, ?, ?, ?, NOW(), ?)', [address, apt, workPhone, city, zipcode, userId], (householdError, householdResults, householdFields) => {
    if (householdError) {
      console.error('Error storing household data:', householdError);
      res.status(500).send('Error storing household data');
      return;
    }

    console.log('Household data stored successfully');
    res.status(200).send('Customer and household data stored successfully');
  });
});
}); */



app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

I checked to see if the values being entered match the constraints of the attributes in the database so that is not the case.

I also console.log()-ed the values gather in the fetch API that routes to /addhousehold and it prints the values correctly.

When I try to console.log the req.body on the server’s side the only contents I can see is name, date of birth , relation, year, make, model , vin and cellphone. The values relating to household is undefined and not listed so that tells me there is a problem with the way the server is receiving the data. I am thinking that the header is not sending the data in the correct format but every time I try to change the header type it still sends the post request as html/text.

Postman Script: Only the Last Request is Getting Executed in a Loop, Why?

why this is happening only request at the last is only getting executed.
pre- request script:

const testCases = ['1002', '3002', '100002', 'singh', '1002y'];

    // Set the productid variable for the current iteration
    pm.variables.set('productid', testCases[3]);
    pm.sendRequest({
        url: pm.variables.replaceIn("{{baseUrl}}/products/:priductId"),
        method: 'GET'
    });

    pm.variables.set('productid', testCases[0]);
    pm.sendRequest({
        url: pm.variables.replaceIn("{{baseUrl}}/products/:priductId"),
        method: 'GET'
    });

test:

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
    if(pm.response.code === 200)
    console.log("ok");
});

pm.test("Status code is 400", function () {
    pm.expect(pm.response.code).to.equal(400);
        if(pm.response.code === 400)
    console.log("Bad Response");
});
console:
 
GET https://valentinos-coffee.herokuapp.com/products/:priductId
400
271 ms
 
GET https://valentinos-coffee.herokuapp.com/products/:priductId
400
275 ms
 
GET https://valentinos-coffee.herokuapp.com/products/1002
200
269 ms
 
ok

In this code also same thing is happening

const testCases = ['1002', '3002', '100002', 'singh', '1002y'];

// Loop through test cases
for (let i = 0; i < testCases.length; i++) {
    // Set the productid variable for the current iteration
    pm.variables.set('productid', testCases[i]);

    // Make the API request
    const response = pm.sendRequest({
        url: pm.variables.replaceIn("{{baseUrl}}/products/:productId"),
        method: 'GET'
    });
}

as you can see from the console only at last the productid is being assigned,
tried promise also then only one request is going out,
tried adding artificial wait also to make it wait 3 seconds then also same thing is happening only the request at last is having the productid assigned.

i want to rectify it so that for each request there is an output from test then next request goes just like that

Uncaught SystaxError: Unexpected Token ‘<'

Hello I have this very old application made in Vue 2 and everything was working fine but just today, I am experiencing this error: Uncaught SystaxError: Unexpected Token '<'.

enter image description here

When I click the link, it returns an HTML file, the index file of my project:

enter image description here

So to check, I tried to build npm run build the project locally. Upon checking on the generated files, the file returns a proper script file.
enter image description here

I also tried to run the project on docker locally, and it was working fine. I tried the usually answer publicPath: '/' but it does not work on my issue.

Can somebody tell what is wrong with my project build?

Circular dependencies causing local unit test failures. But the tests succeed in jenkins. Why?

I have a react app. We use jest and the react testing library for unit testing. Sometimes, we receive the following error:

“TypeError: Cannot read property ‘X’ of undefined”

Typically points to a circular dependencies. But we only see this locally. Jenkins runs and passes the test just fine.

Why would that be? It’d be nice if test failures were the same on jenkins and locally…

Thanks!

JS OOP – class method calling another class from function

I was curious about JS Design Patterns and decided to try this website,
but on the Command Pattern section I got super confused. You can see the explanation in the link but for this post’s sake I have provided a code snippet below.

class OrderManager {
    constructor() {
        this.orders = [];
    }

    execute(command, ...args) {
        return command.execute2(this.orders, ...args);
    }
}
  
class Command {
    constructor(executee) {
        this.execute2 = executee;
    }
}

function PlaceOrderCommand(order, id) {
    return new Command(orders => {
        orders.push(id);
        console.log(`You have successfully ordered ${order} (${id})`);
    });
}

const manager = new OrderManager();

manager.execute(new PlaceOrderCommand("Pad Thai", "1234"));

I am super confused, I thought I was good at JS but apparently I am not..

The questions in line are:

  1. How can you call the manager.execute with only one argument, when in the definition there are two?!

  2. Why call the function with new keyword like new PlaceOrderCommand(“Pad Thai”, “1234”)

  3. How does execute2 call the arrow function when it is just assigned in the constructor?!

all these things are super confusing and seem like magic to me..

Fetching from SQL and displaying on frontend errors

I am working on a workout website for practice and fun. I can enter a workout and it saves to mysql but when i try and fetch and show the workouts in the db im getting errors. In Postman i can see users but using http://localhost:3000/api/workouts Just shows a blank page.

http://localhost:3000/test-db This on the other hand works. I will attach my code, i cant see why
http://localhost:3000/api/workouts doesnt show workouts.

SELECT * FROM workouts in mysql does show the workouts.

It has to be something with my server.js, I want to be able to see the workouts on postman.

I cannot post images due to not having 10 rep.

const express = require('express');
const cors = require('cors');
const db = require('./src/config/db'); // Adjust the path as needed to your db config
require('dotenv').config();

const app = express();
app.use(express.json());
// app.use(cors());
app.use(cors({
  origin: ['http://localhost:3000', 'http://localhost:3001'], // allow requests from these origins
  methods: ['GET', 'POST'], // allow these HTTP methods
  allowedHeaders: ['Content-Type', 'Authorization'], // allow these headers
}));

// Test endpoint to check database connection
app.get('/test-db', (req, res) => {
    // Query the database to retrieve a list of tables
    db.query('SHOW TABLES', (err, results) => {
      if (err) {
        console.error(err);
        res.status(500).send('Database connection error');
      } else {
        // Return the list of tables as JSON response
        res.status(200).json(results);
      }
    });
});

// Login endpoint for user authentication
app.post('/api/login', (req, res) => {
  const { email, password } = req.body;
  
  // Query database for user by email and password
  const query = 'SELECT * FROM users WHERE email = ? AND password = ?';
  db.query(query, [email, password], (err, results) => {
    if (err) {
      return res.status(500).json({ message: "Database error", error: err });
    }
    if (results.length === 0) {
      return res.status(401).json({ message: "Invalid email or password" });
    }
    
    // Send success response if user is found
    res.json({ message: "Login successful" });
  });
});

// Signup endpoint for user registration
app.post('/api/signup', async (req, res) => {
  const { email, password } = req.body;

  try {
    // Check if user already exists in the database
    const existingUser = await db.query('SELECT * FROM users WHERE email = ?', [email]);
    if (existingUser.length > 0) {
      return res.status(400).json({ message: 'Email already exists' });
    }

    // Insert new user into the database
    await db.query('INSERT INTO users (email, password) VALUES (?, ?)', [email, password]);

    // Return success message if user is successfully registered
    res.status(201).json({ message: 'User registered successfully' });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ message: 'An error occurred. Please try again later.' });
  }
});

// Endpoint to save workout data to the database
app.post('/api/workouts', async (req, res) => {
  const { workout } = req.body;

  try {
    // Insert the workout data into the database without the workout_date field
    await db.query('INSERT INTO workouts (workout_name, user_id) VALUES (?, ?)', [workout.workout_name, workout.user_id]);

    // Return success message if workout is successfully saved
    res.status(201).json({ message: 'Workout saved successfully' });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ message: 'An error occurred. Please try again later.' });
  }
});


// Endpoint to fetch all workouts from the database
app.get('/api/workouts', async (req, res) => {
  try {
    
    const workouts = await db.query('SELECT * FROM workouts');

    console.log('Workouts:', workouts); 

    const workoutRows = workouts.rows;
  
    res.status(200).json(workoutRows);
  } catch (error) {
    console.error('Error fetching workouts:', error);
    res.status(500).json({ message: 'An error occurred. Please try again later.' });
  }
});




const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));



I have tried changing the server.js code but nothing seems to work.

BibiJs Reader not loading books with images

Hello Stack Overflow community,

I hope you’re all doing well. I’m currently working on a book reading website using Bibi Reader, and I’ve encountered a perplexing issue. Some of the books, particularly those with a significant number of images, are not loading in Bibi Reader.

I’ve tried various troubleshooting steps, including reducing the size of the books, to rule out any potential size-related issues. However, even smaller books with images are failing to load.

If any of you have experience with Bibi Reader or encountered a similar problem, I would greatly appreciate your insights and assistance in resolving this issue. Here is the EPUB book that exhibits the problem, hoping that it might provide more context for diagnosis. I’m also attaching the loading page along with network properties that I am getting.

enter image description here