How to automatically scrap a table specific columns full of rows with JS?

i’m trying to make a personal project which will gather text and numbers data from wikipedia which would later move all that to the database and then compare all these gathered values to make a visual representation.
But i’m having some difficulties with selecting what values i want to gather, specifically for html tables. I’d like to select all rows with data inside and only with specific columns.

for example I have a table like this:

Column1       column2    column3
rowdata1      rowdata1   rowdata1
rowdata2      rowdata2   rowdata2

And I want to make it look like this:

Column1       column3 
rowdata1      rowdata1   
rowdata2      rowdata2   

Without a second column and its rows for example. So, is there any simple and straightforward solution on how to do so? Because manually picking names and numbers with Xpath is going to take ages. Here is an example of my current code below

const puppeteer = require('puppeteer');

async function scrapewiki(url) {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto(url);

    const [el] = await page.$x('/html/body/div[3]/div[3]/div[5]/div[1]/table/tbody/tr[2]/td[1]/a');
    const txt = await el.getProperty('textContent');
    const country = await txt.jsonValue();

    const [el2] = await page.$x('/html/body/div[3]/div[3]/div[5]/div[1]/table/tbody/tr[2]/td[3]');
    const txt2 = await el2.getProperty('textContent');
    const population = await txt2.jsonValue();

I use JS and NPM and i’m total newbie here.Thank you

How do I render react components through express routes?

I want to use react components as pages, and I want them to be rendered through express routes.

So basically I am trying to do SSR with just express and react.

package.json:

{
    "name": "project",
    "version": "1.0.0",
    "main": "index.js",
    "description": "",
    "scripts": {
        "dev": "nodemon index.js"
    },
    "keywords": [],
    "author": "",
    "license": "MIT",
    "type": "module",
    "dependencies": {
        "express": "^4.18.1",
        "nodemon": "^2.0.19",
        "react": "^18.2.0",
        "react-dom": "^18.2.0"
    }
}

index.js:

import express from "express";
import React from "react";
import ReactDOMServer from "react-dom/server";
import Home from "./Home";

const app = express();
const port = 3000;

app.get("/", (req, res) => {
    res.send(ReactDOMServer.renderToString(<Home />));
});

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`);
});

Home.js:

export default function Home() {
    return (
        <div>
            <h1>home</h1>
            <p>hello world</p>
        </div>
    );
}

When I run npm run dev, I get this error:

res.send(ReactDOMServer.renderToString(<Home />));
SyntaxError: Unexpected token '<'

I figured it was from the JSX stuff, so I tried installing some babel packages, and updating my dev script:

{
    "name": "project",
    "version": "1.0.0",
    "main": "index.js",
    "description": "",
    "scripts": {
        "dev": "nodemon index.js --exec babel-node --presets env,react"
    },
    "keywords": [],
    "author": "",
    "license": "MIT",
    "type": "module",
    "dependencies": {
        "@babel/node": "^7.18.6",
        "@babel/preset-env": "^7.18.6",
        "@babel/preset-react": "^7.18.6",
        "express": "^4.18.1",
        "nodemon": "^2.0.19",
        "react": "^18.2.0",
        "react-dom": "^18.2.0"
    }
}

But the error still occurs when I do npm run dev.

How do I simply get express to render a react component when a certain route is visited? I prefer doing it this way since I will have API routes as well, so I don’t want to fragment the routing into a mixture of express and react router, etc.

how to handle millions of data with Javascript

I’m building a student placement app using Javascript. for my backend server I’m using MySQL. so let me state my app first.

I want to build an app that records students (millions of students) and their scores. after that i need my app to analyze all data provided and rank them all. and then using those ranks it places them to a campus of their choosing based on their ranks.

so my question is what method or library can i use to handle this many datas?

how to return a value from ajax anonymous function

i know to return a value from a java script anonymous function we can use callback function like this:

function foo(myCallback){
    return myCallback();
}
function bar(){
    var result = foo(function(){
    var result = "hello"; 
    return result;
});
return result;
}
var showResult = bar();
alert(showResult);

but i have a function that use ajax object to read a value from data base and i need to return this value:

function foo(myCallback){
    return myCallback();
}
function findTheBankName(id){
    var request = new XMLHttpRequest;
    request.open("GET","../model/jsonReports.php?bankAccountID="+id);
    request.onreadystatechange= foo(function(){
        if (this.readyState==4 && this.status==200){
            let serviceData=JSON.parse(this.responseText);
            result=serviceData.bankName;
            return result       
    });
    request.send();
    return result;
}
var showResult = bar();
alert(showResult);

but anonymous don’t work in this case. can u help me? how to return a value from ajax anonymous function to main function and return it from main function???!!!

I receive null values when passing me data by POST from JS to PHP using Jquery Ajax

I’m trying to get values from a form to insert them in my database. When I send the data with Ajax (click on “submit” button), I get these warnings:

AH01071: Got error 'PHP message: PHP Warning:  Trying to access array offset on value of type null in /home/glab360/.ftp-users/app/home.php on line 15

PHP message: PHP Warning:  Trying to access array offset on value of type null in /home/glab360/.ftp-users/app/home.php on line 27', referer: https://app.glab360.com/cuestionario/nuevo

This is my AJAX:

$.ajax({
    type: 'POST',
    url: 'validate.php',
    data: {
        q1_NombreDeLaIdentidad: q1_NombreDeLaIdentidad,
        q1_DireccionCompletaDeLaEntidad: q1_DireccionCompletaDeLaEntidad,
        q1_Nif: q1_Nif,
        q1_Telefono: q1_Telefono,
        q1_DireccionDeCorreoElectronico: q1_DireccionDeCorreoElectronico,
        q1_Actividad: q1_Actividad,
        q1_ActividadCategorias: q1_ActividadCategorias,
        q2_QueDatosPersonalesTratasEnTuEntidad: q2_QueDatosPersonalesTratasEnTuEntidad,
        q3_HayEmpresasOProfesionalesExternosQueTratenDatosPersonalesResponsabilidadDeSuEntidad: q3_HayEmpresasOProfesionalesExternosQueTratenDatosPersonalesResponsabilidadDeSuEntidad,
        q4_CuentaSuEntidadConPaginaWeb: q4_CuentaSuEntidadConPaginaWeb,
        q5_AccedeADatosPersonales: q5_AccedeADatosPersonales,
        q6_RegistroDeTrabajadores: q6_RegistroDeTrabajadores,
        q7_FinalidadDispositivosDeGeolocalizacion: q7_FinalidadDispositivosDeGeolocalizacion
    },
    cache: false,
    success: function (response) {
        console.log(response);
    }
});

I have checking on Internet and I’m getting those warnings because I’m not checking if the data I get, exist or not.

So I added the isset() to my variables at the time of retrieving the value per post:

$q1_NombreDeLaIdentidad = isset($_POST['q1_NombreDeLaIdentidad']);
$q1_DireccionCompletaDeLaEntidad = isset($_POST['q1_DireccionCompletaDeLaEntidad']);
$q1_Nif = isset($_POST['q1_Nif']);
$q1_Telefono = isset($_POST['q1_Telefono']);
$q1_DireccionDeCorreoElectronico = isset($_POST['q1_DireccionDeCorreoElectronico']);
$q1_Actividad = isset($_POST['q1_Actividad']);
$q1_ActividadCategorias = isset($_POST['q1_ActividadCategorias']);
$q2_QueDatosPersonalesTratasEnTuEntidad = isset($_POST['q2_QueDatosPersonalesTratasEnTuEntidad']);
$q3_HayEmpresasOProfesionalesExternosQueTratenDatosPersonalesResponsabilidadDeSuEntidad = isset($_POST['q3_HayEmpresasOProfesionalesExternosQueTratenDatosPersonalesResponsabilidadDeSuEntidad']);
$q4_CuentaSuEntidadConPaginaWeb = isset($_POST['q4_CuentaSuEntidadConPaginaWeb']);
$q5_AccedeADatosPersonales = isset($_POST['q5_AccedeADatosPersonales']);
$q6_RegistroDeTrabajadores = isset($_POST['q6_RegistroDeTrabajadores']);
$q7_FinalidadDispositivosDeGeolocalizacion = isset($_POST['q7_FinalidadDispositivosDeGeolocalizacion']);

When I print this info, using echo(), I can see the result in my console.log (as a succesful request), and I don’t see any null. All the dataI get, is correct. No nulls and no weird things.

But when I try to insert this data in the database, if I don’t force my DB to accept nulls, I get these errors:

Got error 'PHP message: PHP Fatal error:  Uncaught mysqli_sql_exception: Column 'q1_DireccionCompletaDeLaEntidad' cannot be null in /home/glab360/.ftp-users/app/cuestionario/validate.php:28nStack trace:n#0 /home/glab360/.ftp-users/app/cuestionario/validate.php(28): mysqli_stmt->execute()n#1 {main}n  thrown in /home/glab360/.ftp-users/app/cuestionario/validate.php on line 28', referer: https://app.glab360.com/cuestionario/nuevo

This is my insert query:

$sql = "INSERT INTO companyForm (q1_NombreDeLaIdentidad, q1_DireccionCompletaDeLaEntidad, q1_Nif, q1_Telefono, q1_DireccionDeCorreoElectronico, q1_Actividad, q1_ActividadCategorias, q2_QueDatosPersonalesTratasEnTuEntidad, q3_HayEmpresasOProfesionalesExternosQueTratenDatosPersonalesResp, q4_CuentaSuEntidadConPaginaWeb, q5_AccedeADatosPersonales, q6_RegistroDeTrabajadores, q7_FinalidadDispositivosDeGeolocalizacion, completed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssssssssssssi", $q1_NombreDeLaIdentidad, $q1_DireccionCompletaDeLaEntidadd, $q1_Nif, $q1_Telefono, $q1_DireccionDeCorreoElectronico, $q1_Actividad, $q1_ActividadCategorias, $q2_QueDatosPersonalesTratasEnTuEntidad, $q3_HayEmpresasOProfesionalesExternosQueTratenDatosPersonalesResponsabilidadDeSuEntidad, $q4_CuentaSuEntidadConPaginaWeb, $q5_AccedeADatosPersonales, $q6_RegistroDeTrabajadores, $q7_FinalidadDispositivosDeGeolocalizacion, $completed);
if ($stmt->execute()) {
    header('Location: ../gracias');
}
else {
    header('Location: ../error');
}

I don’t know what is happening. Seems like my data is null because doesn’t exist or something like that, but I’m printing it and I can read the data clearly. This is very confusing. I don’t know what I’m doing wrong. I’ve been stuck on this all day

Jest – Mock method of default class exported as named component of a package module

We have the below classes:

Component 1:

import React, { Component } from 'react'
import {foo} from 'blah'
import {bar} from 'blah-blah'

export default class Component1 extends Component {
  static propTypes = {
    ...
    ...
  }

  ...
  ...

  save() {
    doSomeOp()
  }

  render() {
    ...
    ...
  }
}

Component 2:

import React, { Component } from 'react'
import {foo} from 'blah'
import {bar} from 'blah-blah'

export default class Component2 extends Component {
  static propTypes = {
    ...
    ...
  }

  ...
  ...

  render() {
  }
}

Now, we have the following components within a package module – ‘@foo-bar/package’. The index.js for this package is as below:

index.js:

import Component1 from './src/component1'
import Component2 from './src/component2'
export { Component1, Component2 } 

This package is used in another component that I am trying to test. The code for this component is as below:

TestComponent:

import React from 'react'
import { Component1 } from '@foo-bar/package'

export function TestComponent(props) {
  ...
  ...

  return (
    <Component1 />   
  )
}

I have some logic in this TestComponent which triggers the save() method of Component1. What I intend to do is keep all the other properties of Component1 the same, but only mock the save() method. How could that be done? Thanks!

jest.mock('@foo-bar/package', () => {
  ???
})

Fetch to get array of objects, loop through array and and make another fetch for each object, construct final array

I’m using Redux Toolkit, with createAsyncThunk. What the goal is I make a request to my api, get back an array of movie objects. Then I need to loop through the array and have a second request to an external api (TheMovieDB) for images from each objects ID. Then if the movies ID matches the image ID, push the image information into each matching movie object and construct the final array to add to state.

Technically, it sort of works. Looking at the actions in Redux devtools this works but it makes a final action calling the original request again for movies and resetting the state. The actions look like:

  • “movies/getLatest”
  • “movies/getExternalImages”
  • “movies/getExternalImages”
  • “movies/getExternalImages” — each object has the image info
  • “movies/getLatest” — unsure why this gets called again but resets the movies state

Initially I had two seperate thunks to do this, first one called my api, second called external and updated the state by:

 .addCase(getExternalMovieBackdrops.fulfilled, (state, action) => {
        state.movies = state.movies.map((item) => {
          if (item.UserData.Key == action.payload.id) {
            return { ...item, ...action.payload };
          }
          return item;
        });
      })

And in my component I used useEffect for the dispatches:

  useEffect(() => {
    dispatch(getLatest({ userId: user.Id, token: token }));
    getExternalImages();
  }, []);

  const getExternalImages = () => {
    return movies?.map((item) => {
      dispatch(getExternalMovieBackdrops(item));
    });
  };

Now what I’m trying to do is just have this in one thunk but I can’t seem to get it. Need to make the first request, loop through it, make second request, add items of second request to looped objects, build the array. I am just unsure how to build the array. This is what I’ve tried:

  const res = await axios.get(
    `${apiURL}/Users/${user.userId}/Items/Latest`,
    options
  );

  return res.data.map(async (item) => {
    const res2 = await axios.get(
      `https://api.themoviedb.org/3/movie/${item?.UserData.Key}/images?api_key=1234`
    );
    return res2.data;
  });

I through a lot on here but any help would be appreciated.

how to import node module in html/javascript page?

How to call my node module in HTML/Javascript page.

node.js page

exports.books = async (req, res) => {
const booksRef = db.collection('Books');
try{
        booksRef.get().then((snapshot) => {
        const data = snapshot.docs.map((doc) => ({
        id: doc.id,
        ...doc.data(),
    }));
        console.log(data);
        return res.status(201).json(data);
    })
} catch (error) {
    return res
    .status(500)
    .json({ general: "Something went wrong, please try again"});          
}

};

home.html page
how to import/call node module books in HTML/javascript function

<script type="module" src="./module.js"></script>
    
function funs_del(a)
    {   
        alert('start');
        **// call node module(books) here.......**
        alert('stop');
        
    }

    

Web socket.io with AdonisJs not working properly

Web socket.io with AdonisJs not working properly.

I’m using a lib to perform tasks inside adonis, adonis5-scheduler.

Below is my task.

import { BaseTask } from 'adonis5-scheduler/build'

export default class GetRouletteGame extends BaseTask {
    public static get schedule() {
        return '*/3 * * * * *'
    }
    /**
     * Set enable use .lock file for block run retry task
     * Lock file save to `build/tmpTaskLock`
     */
    public static get useLock() {
        return false
    }

    public async handle() {
      Ws.io.emit(`taskName`, 1)
      console.log('ok')
    }
}

Below is my Ws.

import { Server } from 'socket.io'
import AdonisServer from '@ioc:Adonis/Core/Server'

class Ws {
  public io: Server
  private booted = false

  public boot() {
    /**
     * Ignore multiple calls to the boot method
     */
    if (this.booted) {
      return
    }

    this.booted = true
    this.io = new Server(AdonisServer.instance!, {
      cors: {
        origin: '*'
      }
    })
  }
}

export default new Ws()

Calling Ws.io.emit from the control works.

Calling Ws.io.emit from the task doesn’t work.

Note for the task Ws.io.emit does not work, however the console.log displays the message.

Task does not run Ws.io.emit

Disable pagination tooltip buttons (first, last, page numbers(1, 2, 3)) in Tabulator JS

I need only the previous and next buttons on my table for pagination. I don’t need (first, last, page numbers(1, 2, 3)) buttons. Is there any way to disable these pagination buttons similar to enabling/disabling paginationCounter? I’m using tabulator.js for my table implementation.

enter image description here

Reference:

  1. http://tabulator.info/docs/5.3/page#overview
  2. https://github.com/olifolkerd/tabulator
//define data array
var tabledata = [
  {
    id: 1,
    name: 'Oli Bob',
    progress: 12,
    gender: 'male',
    rating: 1,
    col: 'red',
    dob: '19/02/1984',
    car: 1,
  },
  {
    id: 2,
    name: 'Mary May',
    progress: 1,
    gender: 'female',
    rating: 2,
    col: 'blue',
    dob: '14/05/1982',
    car: true,
  },
  {
    id: 3,
    name: 'Christine Lobowski',
    progress: 42,
    gender: 'female',
    rating: 0,
    col: 'green',
    dob: '22/05/1982',
    car: 'true',
  },
  {
    id: 4,
    name: 'Brendon Philips',
    progress: 100,
    gender: 'male',
    rating: 1,
    col: 'orange',
    dob: '01/08/1980',
  },
  {
    id: 5,
    name: 'Margret Marmajuke',
    progress: 16,
    gender: 'female',
    rating: 5,
    col: 'yellow',
    dob: '31/01/1999',
  },
  {
    id: 6,
    name: 'Frank Harbours',
    progress: 38,
    gender: 'male',
    rating: 4,
    col: 'red',
    dob: '12/05/1966',
    car: 1,
  },
];

var table = new Tabulator('#example-table', {
  data: tabledata, //load row data from array
  layout: 'fitColumns', //fit columns to width of table
  responsiveLayout: 'hide', //hide columns that dont fit on the table
  tooltips: true, //show tool tips on cells
  addRowPos: 'top', //when adding a new row, add it to the top of the table
  history: true, //allow undo and redo actions on the table
  pagination: 'local', //paginate the data
  paginationSize: 2, //allow 7 rows per page of data
  paginationCounter: 'rows', //display count of paginated rows in footer
  movableColumns: true, //allow column order to be changed
  initialSort: [
    //set the initial sort order of the data
    { column: 'name', dir: 'asc' },
  ],
  columns: [
    //define the table columns
    { title: 'Name', field: 'name', editor: 'input' },
    {
      title: 'Task Progress',
      field: 'progress',
      hozAlign: 'left',
      formatter: 'progress',
      editor: true,
    },
    {
      title: 'Gender',
      field: 'gender',
      width: 95,
      editor: 'select',
      editorParams: { values: ['male', 'female'] },
    },
    {
      title: 'Rating',
      field: 'rating',
      formatter: 'star',
      hozAlign: 'center',
      width: 100,
      editor: true,
    },
    { title: 'Color', field: 'col', width: 130, editor: 'input' },
    {
      title: 'Date Of Birth',
      field: 'dob',
      width: 130,
      sorter: 'date',
      hozAlign: 'center',
    },
    {
      title: 'Driver',
      field: 'car',
      width: 90,
      hozAlign: 'center',
      formatter: 'tickCross',
      sorter: 'boolean',
      editor: true,
    },
  ],
});
<html>
  <link
    href="https://unpkg.com/[email protected]/dist/css/tabulator.min.css"
    rel="stylesheet"
  />
  <body>
    <div id="example-table"></div>
  </body>

  <script
    type="text/javascript"
    src="https://unpkg.com/[email protected]/dist/js/tabulator.min.js"
  ></script>
  <script type="module" src="./index.js"></script>
</html>

How to get Firestore “has sync to the cloud” status for a specific collection?

I’m trying to get the sync status for a collection in Firestore.

The app supports both online and offline. Before the user closes a screen I want to check whether all data in the collection has synced to the cloud.

What I have tried currently is the hasPendingWrites attribute. But I always get false.

db.collection("cities").onSnapshot((querySnapshot)=> {
  console.log(querySnapshot.metadata.hasPendingWrites);
});

How to compare month and year in javascript

i need to compare date.like input date is greater than current next month.using normal date in java script.

                  //comparison_date is date which is current date + one month
                  // 14/07/2022 + One Month
                    input_date : 14/07/2022
                    comparison_date : 14/08/2022
                    if(input_date> comparison_date){
                    // false
                    }


                    input_date : 14/08/2022
                    comparison_date : 14/08/2022
                    if(input_date> comparison_date){
                    // false
                    }

                    input_date : 14/09/2022
                    comparison_date : 14/08/2022
                    if(input_date> comparison_date){
                    // true
                    }

                    input_date : 22/12/2022
                    comparison_date : 14/01/2023
                    if(input_date> comparison_date){
                    // false
                    }

Error Functions are not valid as a React child. This can happen if you return a Component instead of from render

I tell you that I am making a shopping cart and I get the following warning “Functions are not valid as a React child. This can happen if you return a Component instead of from render. Or maybe you meant to call this function instead of returning it.”, what I am doing is passing through an event information to the father from the son to be used later in the Cart.

the codes are these:

ItemDetial (detail of the product selected by the customer):

import React, { useState } from "react";
import '../App.css';
import 'materialize-css/dist/css/materialize.css';
import Count from './ItemCount';
import { Link } from "react-router-dom";


export const ItemDetail = (({item}) => {  

  const [itemSell, setItemSell] = useState(false);

  const onAdd = (count) => {
    setItemSell(true);
  }
 
  return (
    <>
      {
        <main className="row soloProduct" id= {item.id}>
            <aside>
              <img src={item.image} alt="item" className="itemImg responsive-img"/>
            </aside>
            <article>
              <div className=" col s12 m8">
                <h5 className="itemName">{item.title}</h5>
              </div>
              <div className="col s12 m4">
                <p className="itemPrice"> {item.price}</p>
              </div>
              <div className="col s12 m12">
                <p className="itemDescription">{item.description}</p>
              </div>
              <div className="col s12">
               {
                  itemSell ? <Link to="/cart"><button className="waves-effect waves-light btn-large">Finalizar Compra</button></Link> : <Count stockInitial={5} onAdd= { onAdd } />
                }
                
              </div>
            </article>
        </main>
      }
    </>
  )

});

export default ItemDetail;

ItemCount (it is a counter so that the client has the possibility of buying more than one product):

import React, { useState} from 'react';
import 'materialize-css/dist/css/materialize.css';
import '../App.css';
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome';
import {faPlus, faMinus, faPowerOff} from '@fortawesome/free-solid-svg-icons';

const ItemCount = ({stockInitial, initial = 0, onAdd}) => {
  const [contador, setContador] = useState(initial)
  const [stock, setStock] = useState(stockInitial)

  
  const sumar = () => {  
    setContador(contador + 1)
    setStock(stock - 1);
    avisarStock();
  }

  const restar= () => {
    if(contador > 0){
      setContador(contador - 1);
      setStock(stock + 1);      
    }
    else
    {
      setContador(0);
    }
  }

  const reset = () =>{
    setContador(0);
    setStock(stockInitial);
  }

  const avisarStock = () => {
    if(stock > 0 ){
      
    } 
    else{
      alert('No podemos enviar su envio no hay stock');
      setStock(0);
      setContador(contador)     
    }

  }

  const agregarAlCarrito = () => {
    onAdd(contador);
  }

  return(
    <>
      <div className=" row left text">Stock: {stock}</div>

      <article>{contador}</article>
      <div className="buttonCount">
        <button onClick={sumar}>
          <FontAwesomeIcon icon ={faPlus}/>
        </button>
        <button onClick={restar}>
          <FontAwesomeIcon icon={faMinus}/>
        </button>
        <button onClick={reset}>
          <FontAwesomeIcon icon={faPowerOff}/>
        </button>
        <br/><h2>{avisarStock}</h2>
        <button onClick={agregarAlCarrito}> Agregar al carrito </button>
      </div>
    </>
  )
}

export default ItemCount;

if you can give me a hand
Thank you

Map Object of Objects without knowing Object Key – React Native

I need to get “primarySprayCanRGB” and “primarySprayCanHighLightRGB” from each individual object in the object and add them to the array.
But I don’t know the individual object keys. => The paint names are different.
I’m working in React Native

for example get: [[“#000000”, “#131313”],[“#292b2d”, “#7b7d80”],[“#6b0913”, “#bc3038”],…]

The code I have so far, to get the data to add to the array, but the code returns only the first oibject because the id is not incremented :

//data == object.paints
//loadinga == false => when data is ready to use
{!loadinga && data.map((object,id) => console.log(object[id].primarySprayCan.primarySprayCanRGB))}

Link to JSON file:

https://cdn.imagin.studio/getPaintSwatches?customer=imagin&make=tesla&paints=pbsb,pmng,ppmr,ppsb,ppsw