node.js get https no responding 504

I am trying to make an https request in my backend node.js web app. I have the following code:

const express = require('express');
const https = require('https');

const app = express();

app.get("/", function(req, res) {

  const url = "https://www.tkmaxx.com/uk/en/women/edits/big-brand-drop/c/01240000/autoLoad?page=1"
  https.get(url, function(response) {

    console.log(response.statusCode);

  });
  res.send("running test")
});

app.listen(3000, function() {
  console.log("Server started on port 3000");
});

I am getting the following error:

node:events:504
      throw er; // Unhandled 'error' event
      ^

Error: socket hang up
    at connResetException (node:internal/errors:691:14)
    at TLSSocket.socketOnEnd (node:_http_client:466:23)
    at TLSSocket.emit (node:events:538:35)
    at endReadableNT (node:internal/streams/readable:1345:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) 
Emitted 'error' event on ClientRequest instance at:
    at TLSSocket.socketOnEnd (node:_http_client:466:9)
    at TLSSocket.emit (node:events:538:35)
    at endReadableNT (node:internal/streams/readable:1345:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {   code: 'ECONNRESET' }

Anyone know what’s going on? Is the issues related to request headers or user agent? How can I set that?

Social network. Simple pet project [closed]

Trying to create a simple social network to shape my skills a little bit.
So I encountered a problem that I can not solve myself.
So I want to add a user to the friend list. So a user can send a request to another user.
So the client app on React can send an API request to the server. And then the server needs to get reached another client app to show the icon that the new friend request received. How can I achieve that?

Why is my cors headers not matching even when they are the same?

I am using passport js with REACT and during fetching the logged in user-data the cors header of fetch isnt matching even though they are the same.

this is where i am sending fetch to
http://localhost:3001/profilebuilder

And address I am fetching from
http://localhost:5000/auth/login/success

app.use(
  cors({
    origin: 'http://localhost:3001/profilebuilder',
    methods: "GET,POST,PUT,DELETE",
    credentials: true,
  })
);
app.listen("5000", () => {
  console.log("Server is running!");
});

this is the client code

 fetch("http://localhost:5000/auth/login/success", {
          method: "GET",
          credentials: "include",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            "Access-Control-Allow-Credentials": true,
          },
        })
          .then((response) => {
            if (response.status === 200) return response.json();
            throw new Error("authentication has been failed!");
          })
          .then((resObject) => {
            setProfile(resObject.user);
          })
          .catch((err) => {
            console.log(err);
          });

I am getting this error

Access to fetch at 'http://localhost:5000/auth/login/success' 
from origin 'http://localhost:3001' has been blocked by CORS 
policy: Response to preflight request doesn't pass access control
 check: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:3001/profilebuilder' 
that is not equal to the supplied origin. Have the server 
send the header with a
valid value, or, if an opaque response serves your needs,
 set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Repeat a loop a number of times

// What’s the minimum number of times you have to flip a coin before you can have three consecutive flips that result in the same outcome (either all three are heads or all three are tails)? What’s the maximum number of flips that might be needed? How many flips are needed on average? In this exercise we will explore these questions by creating a program that simulates several series of coin flips.

// Create a program that uses a random number generator to simulate flipping a coin several times. The simulated coin should be fair, meaning that the probability of heads is equal to the probability of tails. Your program should flip simulated coins until either 3 consecutive heads of 3 consecutive tails occur. Display an H each time the outcome is heads, and a T each time the outcome is tails, with all of the outcomes for one simulation on the same line. Then display the number of flips that were needed to reach 3 consecutive occurrences of the same outcome. When your program is run it should perform the simulation 10 times and report the average number of flips needed. Sample output is shown below:

const headsOrTails = [];
const flipcounts = [];
let threeInARow = false;

while (threeInARow == false) {
  const coinFlip = Math.floor(Math.random() * 10 + 1);
  if (coinFlip <= 5) {
    headsOrTails.push('H');
  } else {
    headsOrTails.push('T');
  }
  for (let index = 0; index < headsOrTails.length; index++) {
    const element = headsOrTails[index];
    if (element == headsOrTails[index + 1]) {
      if (element == headsOrTails[index + 2]) {
        threeInARow = true;
        console.log('il numero di flip ottenuti è ' + headsOrTails.length);
      }
    }
  }
}
`

Is there any way to repeat the while loop a number of times? for example 10 times

React js Compiled with warnings

I am junior backend developer but I use the react library in my clone projects

After updating the react script, I started getting a lot of errors in my project. I solved some of them, how can I solve them or ignore them

node -v v14.17.0
enter image description here

Can’t parse excel date to string with xlsx in a util function javascript

I am trying to read an excel document which has a datetime column.Uploading it to the website,instead of date column i get those numbers which represent the time.I know that using xlsx utils sheet to json we can convert the date cell to the format we want,but i am using a big function to parse this document and the only thing i use from xlsx is xlsx.read . in this function i wrote celldate to true but my web app throws the error that i can not use date object as react child and i dont understand how to convert it as string or at least to read objects property. Could you help me please?

excelToJson utility function which i use:

const XLSX = require("xlsx");
const extend = require("node.extend");

const excelToJson = (function () {
  let _config = {};

  const getCellRow = (cell) => Number(cell.replace(/[A-z]/gi, ""));
  const getCellColumn = (cell) => cell.replace(/[0-9]/g, "").toUpperCase();
  const getRangeBegin = (cell) => cell.match(/^[^:]*/)[0];
  const getRangeEnd = (cell) => cell.match(/[^:]*$/)[0];
  function getSheetCellValue(sheetCell) {
    if (!sheetCell) {
      return undefined;
    }
    if (sheetCell.t === "z" && _config.sheetStubs) {
      return null;
    }
    return sheetCell.t === "n" || sheetCell.t === "d"
      ? sheetCell.v
      : (sheetCell.w && sheetCell.w.trim && sheetCell.w.trim()) || sheetCell.w;
  }

  const parseSheet = (sheetData, workbook) => {
    const sheetName =
      sheetData.constructor === String ? sheetData : sheetData.name;
    const sheet = workbook.Sheets[sheetName];
    const columnToKey = sheetData.columnToKey || _config.columnToKey;
    const range = sheetData.range || _config.range;
    const headerRows =
      (sheetData.header && sheetData.header.rows) ||
      (_config.header && _config.header.rows);
    const headerRowToKeys =
      (sheetData.header && sheetData.header.rowToKeys) ||
      (_config.header && _config.header.rowToKeys);

    let strictRangeColumns;
    let strictRangeRows;
    if (range) {
      strictRangeColumns = {
        from: getCellColumn(getRangeBegin(range)),
        to: getCellColumn(getRangeEnd(range)),
      };

      strictRangeRows = {
        from: getCellRow(getRangeBegin(range)),
        to: getCellRow(getRangeEnd(range)),
      };
    }

    let rows = [];
    for (let cell in sheet) {
      // !ref is not a data to be retrieved || this cell doesn't have a value
      if (
        cell === "!ref" ||
        (sheet[cell].v === undefined &&
          !(_config.sheetStubs && sheet[cell].t === "z"))
      ) {
        continue;
      }

      const row = getCellRow(cell);
      const column = getCellColumn(cell);

      // Is a Header row
      if (headerRows && row <= headerRows) {
        continue;
      }

      // This column is not _configured to be retrieved
      if (columnToKey && !(columnToKey[column] || columnToKey["*"])) {
        continue;
      }

      // This cell is out of the _configured range
      if (
        strictRangeColumns &&
        strictRangeRows &&
        (column < strictRangeColumns.from ||
          column > strictRangeColumns.to ||
          row < strictRangeRows.from ||
          row > strictRangeRows.to)
      ) {
        continue;
      }

      const rowData = (rows[row] = rows[row] || {});
      let columnData =
        columnToKey && (columnToKey[column] || columnToKey["*"])
          ? columnToKey[column] || columnToKey["*"]
          : headerRowToKeys
          ? `{{${column}${headerRowToKeys}}}`
          : column;

      let dataVariables = columnData.match(/{{([^}}]+)}}/g);
      if (dataVariables) {
        dataVariables.forEach((dataVariable) => {
          let dataVariableRef = dataVariable.replace(/[{}]*/gi, "");
          let variableValue;
          switch (dataVariableRef) {
            case "columnHeader":
              dataVariableRef = headerRows
                ? `${column}${headerRows}`
                : `${column + 1}`;
            // break;
            default:
              variableValue = getSheetCellValue(sheet[dataVariableRef]);
          }
          columnData = columnData.replace(dataVariable, variableValue);
        });
      }

      if (columnData === "") {
        continue;
      }

      rowData[columnData] = getSheetCellValue(sheet[cell]);

      if (sheetData.appendData) {
        extend(true, rowData, sheetData.appendData);
      }
    }

    // removing first row i.e. 0th rows because first cell itself starts from A1
    rows.shift();

    // Cleaning empty if required
    if (!_config.includeEmptyLines) {
      rows = rows.filter((v) => v !== null && v !== undefined);
    }

    return rows;
  };

  const convertExcelToJson = function (config = {}) {
    _config = config.constructor === String ? JSON.parse(config) : config;

    // ignoring empty lines by default
    _config.includeEmptyLines = _config.includeEmptyLines || false;

    // source has to be defined and should have a value
    if (!(_config.source)) {
      throw new Error(":: 'source' required for _config :: ");
    }

    let workbook = XLSX.read(_config.source, {
      type: "array",
    });

    let sheetsToGet =
      _config.sheets && _config.sheets.constructor === Array
        ? _config.sheets
        : Object.keys(workbook.Sheets).slice(
            0,
            (_config && _config.sheets && _config.sheets.numberOfSheetsToGet) ||
              undefined
          );

    let parsedData = {};
    sheetsToGet.forEach((sheet) => {
      sheet =
        sheet.constructor === String
          ? {
              name: sheet,
            }
          : sheet;

      parsedData[sheet.name] = parseSheet(sheet, workbook);
    });

    return parsedData;
  };

  return convertExcelToJson;
})();

export default excelToJson;  

And that is how i use it:

const convertExcelToObject = (file) => {
      const reader = new FileReader();
      reader.onload = function (event) {
        const data = new Uint8Array(event.target.result);
        let result = excelToJson({ source: data });
       onUploadExcelFile(result.Transactions);
      };
          reader.readAsArrayBuffer(file);
    };  

The excel document comes from asp.net web api as a base64string. Thanks in advance!

jsPDF-Autotable: How do I add a content after the header and also add a footer?

I have this sample table already with a header. However, I also wanted to put the div="content" after the header in the first page and add the div="footer" in every page. How can I do this?

I have a div content that I wanted to show this in the print as well.

enter image description here

enter image description here

codesandbox: https://codesandbox.io/s/print-to-pdf-8ij2ws?file=/demo.js

Codes:

 const handlePrint = () => {
    console.log("clicked");
    const doc = new jsPDF();
    var img = new Image();
    img.src = require("./assets/logo-social.png");

    img.onload = () => {
      var finalY = doc.lastAutoTable.finalY || 10;

      const columns = [
        "First Name",
        "Last Name",
        "Number",
        "Address",
        "Total Amount"
      ];
      const rows = [];
      data.map((item) =>
        rows.push([
          item.firstName,
          item.lastName,
          item.houseNo,
          item.Address,
          item.totalAmount
        ])
      );

      //used this one
      doc.autoTable(columns, rows, {
        startY: finalY + 30,
        // showHeader: "never",
        didDrawPage: function (data) {
          // Header

          doc.setFontSize(20);
          doc.setTextColor(40);
          doc.text("Title here", data.settings.margin.left + 21, 22);
          doc.text("subtittle here", data.settings.margin.left + 21, 28);
          doc.addImage(img, "png", 10, 15, 25, 15);
        }
      });
      doc.save("order.pdf");
    };

};

My react code doesn’t work after i import some files

        import React from "react";
import { Container, AppBar, Typography, Grow, Grid } from "@material-ui/core";

import Posts from "./components/Posts/Posts";
import Form from "./components/Form/Form";
import memories from "./images/memories.png";
const App = () => {
  return (
    <Container maxwidth="lg">
      <AppBar position="static" color="inherit">
        <Typography variant="h2" align="center">
          Memories
        </Typography>
        <img src={memories} alt="memories" height="60" />
      </AppBar>
      <Grow in>
        <Container>
          <Grid
            container
            justify="space-between"
            alignItems="stretch"
            spacing={3}
          >
            <Grid item xs={12} sm={7}>
              <Posts />
            </Grid>
            <Grid item xs={12} sm={4}>
              <Form />
            </Grid>
          </Grid>
        </Container>
      </Grow>
    </Container>
  );
};

export default App;

This is my code. It was working unitl i added the code in the Grow tag. If anyone know the solution please help me. I’m a beginner trying to learn react.

I am having issue with my image src in next.js

I am using Sanity image url in my project and I am getting this error in my console page that says
“next-dev.js?3515:25 Warning: Prop src did not match. Server: “https://cdn.sanity.io/images/jbcyg7kh/production/4f6d8f5ae1bed2647201bfcaed2f270897b92306-800×533.jpg” Client: “https://cdn.sanity.io/images/jbcyg7kh/undefined/4f6d8f5ae1bed2647201bfcaed2f270897b92306-800×533.jpg”

    import sanityClient from "@sanity/client";
import  imageUrlBuilder  from "@sanity/image-url";



export const client = sanityClient({
    projectId:"projectId",
    dataset:process.env.NEXT_SANITY_DATASET,
    useCdn: true,
    apiVersion:"2022-05-13"
});


const builder = imageUrlBuilder(client)

export const urlFor= (source) =>builder.image(source)

    enter code here



    import Link from "next/link";
import React from "react";
import { urlFor } from "../lib/client";

function Product({ product: { name, image, price, description, slug } }) {
  return (
    <div>
      <Link href={`/product/${slug.current}`}>
        <div>
          <img src={urlFor(image[0])} alt="" />
          <h4>{name}</h4>
          <p>₦{price}</p>
          <p>{description}</p>
        </div>
      </Link>
    </div>
  );
}

export default Product;

JavaScript How to create elements into each created element?

I’m trying to put a content div into each parent div, but this way it puts all the content divs to the first parent div, not each parent div. I’ve tried to do it in 2 for loops, tried forEach, but just can’t figure it out.

        for (let i = 0; i < 5; i++) {
           const parent = document.createElement("div");
           parent.classList.add("parent");
           parent.setAttribute("id","parent");
           document.getElementById("container").appendChild(parent);
           const content = document.createElement("div");
           content.classList.add("content");
           document.getElementById("parnet").appendChild(content);
        }

Ty for your answer

Player Auction project [closed]

Part 1 In an sports event there are many franchise teams are there. Each team has a maximum set up budget under which it can take various player. Each player has a bidding budget. Now sum of all player’s budget for a particular team shouldn’t exceed the Team’s maximum budget.

Example : Team Thunderbird has maximum budget 500$. If 5 players are under
Thunderbird team. Player 1 budget : 100$, Player 2 budget 75$, Player 3 Budget :
80$, Player4 budget : 110$, player5 budget : 90$. Sum of all 5 player budget =
100$+75$+80$+110$+90$=455$ . The moment System going to add one more
new player whose budget is 85$ , then system will show an exception message
saying” it will exceeds the max budget of Team”. Each player has id , name and
budgetPrice properties.

Create an Java with Angular based application for the above scenarios which will
meets the below functionalities :1. User should first create a login credentials : Sign up form consists of fields
like :
username : Text Box( 4 to 15 character)
Age : Only numeric
Gender : radio Button (male or female)
Hobbies : Check boxes ( must have to select 2 check boxes)
Password: Text box ( alpha+numeric+SpecialChar+minimum one
Uppercase with 5 to 10 character)
Submit Button : Submit
After successfully validated the upper fields system should submit the User data
in database.

  1. Once user creates the signup step , he/she can now login to the application
    by providing the Username and password. After successfully logged in User can
    land to the Home page of player Auction.

  2. Home Page : Design the Home page in such a way that it should consists of
    Create Team, Create Player, show Team, Show Player tab button should be
    there.(use Angular router feature)

  3. Once user select Create Team : which consists of filed like Team name and
    Team Max budget. User Needs to fill both fields and click on submit button. Once
    a team successfully created it will show you “ Successfully created with team
    name “ . If that team name already exists in database it will show exception
    message “ Player already exists” .

  4. Once User select Create Player tab button system will show a new screen of
    Create player. Page consists of a text box or an drop down box . where user will
    enter the team name which has already created in step 4. User need to enter
    player name in text box , player Bidding budget . Click on submit button.
    Validation step : System should validate if the player can assign to the team or
    not . validation step already described above . While assigning a player to a team
    if player budget exceeds to the total team budget system should showappropriate exception message “ player can’t be tagged to this team as it exceeds
    team’s budget”.

  5. Once user selects show team tab button it will land in Show team page.
    Here user needs to select a particular team name which is there in the database
    from a dropdown box or User needs to enter a team name in the textbox and hit
    in the submit button. Once user click on submit button system will display all the
    player information in a tabular form.

  6. Once user Selects Show Player tab button system will land in show player
    page. Here User needs to enter a particular Player id and click on Submit button,
    After clicking on submit button system will display all the information of that
    player like name, playerBudget and to which team that player assigned to . If a
    player is not assigned to any team system will show NA as team name filed.

  7. Write Junit test case for each API .
    Part2 :
    Use maven to build the above application .
    After build push your code to GIT HUB repository.
    Create an CI/CD flow to Jenkins tool so that when ever an build will trigger and
    push code to GITHUB system will automatically trigger a build to Jenkins server.

Skill To be Used :
Spring boot Micro services
Angular for front end
JavaScript for validation
Junit
Boot strap for page designing( No black and white page allowed)
Maven
GIT
Jenkins

Update or create row based on ID – Google Script

It’s been several days since I’m stuck on this problem. I’ve tried everything I saw but I think I miss some logic of the Google Script.

I have a php form which send data on post to a Google Spreadsheet. It uses a Google Script to handle the request and update a Google Spreasheet. The problem is that I added one ID per row (generated on my web app and sent through my php form) but I can’t find the way to compare the ID received on my Google Script in order to compare it to the ID of the last row of my spreadsheet. The goal is to replace the row if the ID already exists or add the new row at the end of my spreadsheet.

Here is the Google script I’ve found on the internet which works but does not handle row updates based on the ID
(The commented lines are the code I’ve tried to add but because of the fact that I cannot manage to log data when I’m sending my php form, I cannot visualize what I’m missing.)

var scriptProp = PropertiesService.getScriptProperties()

function intialSetup () {
  var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  scriptProp.setProperty('key', activeSpreadsheet.getId())
}

function doPost (e) {
  var lock = LockService.getScriptLock()
  lock.tryLock(10000)

  try {
    var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
    var sheet = doc.getSheetByName(sheetName)

    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
    var nextRow = sheet.getLastRow() + 1

    // var values = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
    // var lastRow = sheet.getLastRow();
    // var lastRowId = values[lastRow - 1][0];
    // var test = JSON.parse(e.postData.contents);
    // Logger.log(test);
    // if (test.id == lastRowId) {
    //   return;  
    // }

    var newRow = headers.map(function(header) {
      return header === 'timestamp' ? new Date() : e.parameter[header]
    })

    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])

    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow}))
      .setMimeType(ContentService.MimeType.JSON)
  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}```