Export pdf with javascript in laravel

my code in index.blade.php to display the data to be exported to pdf.

<div class="card-body">
                                    <div class="table-responsive table-bordered"  id="pdf">
                                        <table class="table mb-0">
                                            <thead>
                                                <tr>
                                                    <th>NAMA</th>
                                                    <th>PERUSAHAAN</th>
                                                    <th>LOKASI ABSEN</th>
                                                    <th>MASUK</th>
                                                    <th>PULANG</th>
                                                    <TH>KETERANGAN</TH>
                                                </tr>
                                            </thead>
                                            <tbody>                          
                                                @foreach ($absen as $data)
                                                    @php
                                                        $work_hour_start = $data->work_hour_start;
                                                        $attendance_time = CarbonCarbon::parse($data->in_time)->format('H:i:s');
                                                        $tolerance = CarbonCarbon::parse($attendance_time)->subMinutes($data->late_tolerance);
                                                        $hour = $tolerance->format('H:i:s');

                                                        $attendance_grp = AppModelsAttendanceGroup::where('id', $data->attendance_group_id)
                                                            ->select('ignore_work_hour')
                                                            ->first();

                                                        if (isset($attendande_grp)) {
                                                            if ($data->ignore_work_hour == 0 || $attendance_grp->ignore_work_hour == 0) {
                                                                if ($hour > $work_hour_start) {
                                                                    $is_late = 'Terlambat';
                                                                } else {
                                                                    $is_late = 'Tepat Waktu';
                                                                }
                                                            }
                                                        } 
                                                    @endphp
                                                    <tr>
                                                        <td>{{ $data->name ?? '' }}</td>
                                                        <td>{{ $data->alias ?? '' }}</td>
                                                        <td>{{ $data->location_name ?? '' }}</td>
                                                        <td>
                                                            <span class="badge badge-success">
                                                                {{ CarbonCarbon::parse($data->in_time)->format('H:i:s') }}
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <span class=" @if ($data->out_time != null) badge badge-info @else  @endif">
                                                                @if ($data->out_time != null)
                                                                    {{ CarbonCarbon::parse($data->out_time)->format('H:i:s') }}
                                                                @else
                                                                    {{ '-' }}
                                                                @endif
                                                            </span>
                                                        </td>
                                                        <td>{{ $is_late }}</td>
                                                    </tr>
                                                @endforeach
                                            </tbody>
                                        </table>
                                    </div>
                                </div>

result view
enter image description here

my javascript code to export pdf data from index.blade.php

   <script>
            var doc = new jsPDF();

            function printDiv(divId,title) 
            {
                let mywindow = window.open('', 'PRINT', 'height=650,width=900,top=100,left=150');

                mywindow.document.write(`<html><head><title>${title}</title>`);
                mywindow.document.write('</head><body >');
                mywindow.document.write(document.getElementById(divId).innerHTML);
                mywindow.document.write('</body></html>');

                mywindow.document.close(); // necessary for IE >= 10
                mywindow.focus(); // necessary for IE >= 10*/

                mywindow.print();
                mywindow.close();

                return true;
            }

        </script>

results after exporting pdf
enter image description here

in my view i create data in tableform, i will export this data in tableform too, but the problem is the view after i export is not in table form, to export pdf i use javascript, is there any way to change my javascript code to export pdf so it can take the form of a table?

Mongoose find.where in a schema with an attribute of type ObjectId

I have this schemas:

UserLike

const UserLikeSchema = Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: "User",
    required: [true, "User is required"],
  },
  game: {
    type: Schema.Types.ObjectId,
    ref: "Game",
    required: [true, "Game is required"],
  }
});

Game

const GameSchema = Schema({
  title: {
    type: String,
    required: [true, "Title is required"],
  },
  status: {
    type: Boolean,
    default: true,
  },
});

I need to find all UserLikes where populated Game.status are true

I’m trying with a code like this

  const games = await UserLike.find()
  .populate("game")
  .where("game.status")
  .equals(true);

But I can’t find a solution 🙁

key/value find/filter instead of looping object [duplicate]

Is there a way to find key/value instead of looping through the itemList? The below code works but it does not look like this code is optimized, is there a better way to do than this ?

for (var i = 0; i < this.itemList.length; i++) {
    if(this.itemList[i].type){
      if (this.itemList[i].type === 'ERT' || this.itemList[i].type === 'PRT' || this.itemList[i].type === 'Complete') {
         this.updateFlag = true; 
      }
    }
}

react with puppeteer i dont know how to collaborate

I have two sides of project,

1. Collect data from one page with puppeteer

2. React page that sorts and displays the data

My puppeteer code,

 const puppeteer = require('puppeteer');
 const fileSystem = require('fs/promises');

 let data = [{
  question: "question text"
}];

async function start() {

  /**
   * page opening
   */
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://www.jotform.com/answers/');

/**
   * reading data
   */
  const questionTextArr = await page.evaluate(() => {
      //Array.from(document.getElementsByClassName("dc-f-question"));
      let question = document.getElementsByClassName("dc-f-question-name");
      const questionList = [...question];

      return questionList.map(h => h.innerText);
  });


  for (let i = 0; i < questionTextArr.length; i++) {
      let object = {
          question: questionTextArr[i]
      };
      insertObject(data, object);
  } 

  await browser.close();
}

start();

function insertObject(arr, obj) {

  // append object
  arr.push(obj);
  
}

Normally I run this code with node index.js

Then I create a react app that i run with npm start or yarn start

import React from 'react';
import './App.scss';
import Page from './components/Page';

const App = () => {
  
  const data = [{question: ""}];

  return (
      <div>
        <Page 
        data={data} 
        />
      </div>
  );
}

How can i collaborate these two code into one? How can i use first code in my react app?

Is there a way in typescript to pass an optional parameter to a constructor only if it exist?

I have an object that has a constructor with an optional parameter like this:

class example{

   constructor(a,b,c,d?){
     ...
   }

}

I want to pass the parameter d only if it exists, and I hope I don’t have to do an if that checks this, because if I have more optional parameters it can get complicated. Is there a way in javascript/typescript to do this. Something like:

new example(
  A,
  B,
  C,
  D?
)

Most efficient way to compare multiple arrays based on a fixed element and copy the largest one?

I’ve four arrays of length 18 (k1,k2,k3&k4). I want to compare the last element of each array & copy the contents of the array with the largest final element.

Currently, this is how I’m doing it:

if (this.k4[17]>=this.k1[17] && this.k4[17]>=this.k2[17] && this.k4[17]>=this.k3[17])
            m = this.k4.filter(() => true);
        else if(this.k1[17]>=this.k4[17] && this.k1[17]>=this.k2[17] && this.k1[17]>=this.k3[17])
            m = this.k1.filter(() => true);
        else if(this.k2[17]>=this.k4[17] && this.k2[17]>=this.k1[17] && this.k2[17]>=this.k3[17])
            m = this.k2.filter(() => true);
        else
            m = this.k3.filter(() => true);

But this isn’t scalable incase I added more arrays in the future.

Here is another method:

var maxlast = [this.k1[17],this.k2[17],this.k3[17],this.k4[17]];
var max = maxlast.reduce(function(a,b){return Math.max(a, b)}, -Infinity);
var pos = maxlast.indexOf(max)+1;
m = eval("this.k"+pos+".filter(() => true);");

I’ve heard eval() is a major security risk, is there an alternative approach?

Not able to use useState in the default app function

I am very new to React and I was trying to use the useState hook to store a request that returns json data in the form :

[{"_id":"622fff9046722bfbaace77d1","Country":"United States","CoronavirusCases":81216268,"Deaths":991038,"Recovered":56282006},{"_id":"622fff9846722bfbaace789f","Country":"United Kingdom","CoronavirusCases":19700952,"Deaths":162873,"Recovered":18378375},{"_id":"622fff9846722bfbaace78a0","Country":"Brazil","CoronavirusCases":29382196,"Deaths":655326,"Recovered":27838793},{"_id":"622fff9846722bfbaace78a4","Country":"France","CoronavirusCases":23532997,"Deaths":140294,"Recovered":15867601},{"_id":"622fff9846722bfbaace78a5","Country":"India","CoronavirusCases":42995560,"Deaths":516005,"Recovered":42441449}]

I’m using this functional component to return the data:

export const FetchCovidData = () => {

  return axios.get('http://localhost:5000/country-ex')
  .then(function (response) {
    return response.data;
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });
}

This is my App function which should be trying to store the returned JSON into the array CovidData so that I can use it as the dataset for the graphs made using chartJS (which seem to be working fine with sample data I made up in the same format as the returned JSON data) :

export default function App() {
  const [CovidData, setCovidData] = useState([]);

  setCovidData(FetchCovidData());
  console.log(CovidData);
  return (

    <div className="App">
    
    <div className='block1'>
      <h1 className='head'>Covid-19</h1>  
      <br></br>
      <br></br>
      <br></br>
      <br></br>
      <br></br>
    </div>  

    <div className='block2'>
      <div className="bar" style={{width:500}}>
        <BarChart ChartData={ CovidData }/>
      </div>
      <br></br>
      <br></br>
      <br></br>
      <div className="pie" style={{width:500}}>
        <PieChart ChartData={ CovidData }/>
      </div>
      <br></br>
      <br></br>
      <br></br>
      <div className="doughnut" style={{width:500}}>
        <DoughnutChart ChartData={ CovidData }/>
      </div>
      <br></br>
      <br></br>
      <br></br>
      <div className="combined" style={{width:500}}>
        <CombinedChart ChartData={ CovidData }/>
      </div>
    </div>

    </div>
  );
}

When I look at the console on the website it tells shows me the link to a react error page titled “Invalid Hook Call Warning” pointing to the line where I’m defining the useState for CovidData. I checked that my react and react-dom were the same version. It also seems that using my hook at the top of the function which should be the right way of doing it. I have looked at other posts addressing the same error as me but I found them very difficult to understand and a lot more complicated compared to my situation. I would appreciate any help on this.

Make objects selectable in ThreeJS

Unfortunately, I’m new to ThreeJs.
I have a question, how I can make an object selectable in ThreeJS?
I mean that the user can select an object and in the background, I can detect its selection and work with it.

Does re-running a map in react re-call the expensive function?

I have the following loop (simplified):

const ExpensiveItems = useMemo(() => {
  return items.map((item, idx) => {
    const style = {
      marginTop: V_GAP,
      ...(idx === items.length - 1 && { marginBottom: V_GAP }),
    };
    return <ExpensiveComponent style={style} item={item} />;
  });
}, [items]);

return loading ? <div>Loading...</div> 
    : <div>{ExpensiveItems}</div>

Whenever, items changes will the ExpensiveComponent function be called N times where N is the length of items. Or will React diff the props first and only call the ExpensiveComponent function again if and only if the props have changed?

This is possibly premature optimization, but if the ExpensiveComponent function will be called N times each time the items array changes, I’d like to avoid calling it N times if possible, since usually at most 1 item in the items array will change at a given time.

So the question is: If re-calling items.map will call the ExpensiveComponent function N times, is there a way to optimize this map function further so that if a single item in the items array changes, I don’t do that?

Getting user input string without using input box

I’m working on a Django project that deals with tracking time of employees. I am using a barcode scanner that outputs ASCII strings and want to be able to capture those strings without having to click on any type of input box; the webpage needs to be configured to accept and store strings as soon as it is launched. I have little to no experience with JavaScript, but I think an event listener on the document is the way to go. Sorry if this is a dumb question, any help is greatly appreciated. Thank you!

JSON.stringify returns ” instead of “”

I’m looking to turn text like this into JSON:

Company     Team
Facebook    Marketing
Google      Engineering
Microsoft   Product

When I log the JSON.stringify returns &quot; instead of ". Why does that happen? What can I change to prevent this?

let pre = document.querySelector('pre').innerHTML;

var cells = pre.split('n').map(function (el) { return el.split(/s+/); });

var headings = cells.shift();

var obj = cells.map(function (el) {
  var obj = {};
  for (var i = 0, l = el.length; i < l; i++) {
    obj[headings[i]] = isNaN(Number(el[i])) ? el[i] : +el[i];
  }
  return obj;
});


var json = JSON.stringify(obj,null,5);
console.log(json)

JS Fiddle

How i can create object with nested arrays of objects by array of nested objects

i struggle with this piece of data, trying to convert it using javascript:

[{
    rawCol: "personalemail",
    template: "CONTACTS",
    modifiedCol: "URL"
}, {
    rawCol: "personId",
    template: "CONTACTS",
    modifiedCol: "PERSONCODE"
}, {
    rawCol: "ssn",
    template: "VITALS",
    modifiedCol: "IDENTITY"
}, {
    rawCol: "gender",
    template: "VITALS",
    modifiedCol: "GENDERCODE"
}, {
    rawCol: "ethnic",
    template: "VITALS",
    modifiedCol: "ETHNICCODE"
}, {
    rawCol: "birthdate",
    template: "VITALS",
    modifiedCol: "BIRTHDATE"
},  {
    rawCol: "contactType",
    template: "OTHER",
    modifiedCol: "NETCONTACTTYPE"
}, {
    rawCol: "workemail",
    template: "OTHER",
    modifiedCol: "EMAILADDRESS"
}]

I want to create the following structure: (I want to use the unique template values from the previous nexted objects, as follows)

{
CONTACTS: [
{rawFile: "personalemail", modifiedCol: "URL"},
{rawFile: "personId", modifiedCol: "PERSONCODE"}
],
VITALS: [
{rawFile: "ssn", modifiedCol: "IDENTITY"},
{rawFile: "gender", modifiedCol: "GENDERCODE"},
{rawFile: "ethnic", modifiedCol: "ETHNICCODE"},
{rawFile: "birthdate", modifiedCol: "BIRTHDATE"},
],
OTHER: [
{rawFile: "contactType", modifiedCol: "NETCONTACTTYPE"},
{rawFile: "workemail", modifiedCol: "EMAILADDRESS"},]
}

I will be very thankful for a good idea how i can achieve this with a function or method.

Multiplicação de Array

  • Complete a função ‘tripleTheChances’ abaixo.
  • O retorno da função é uma variável do tipo INTEGER_ARRAY.
  • A função aceita o parâmetro chances do tipo INTEGER_ARRAY.

function tripleTheChances(chances) {
let chances = [5, 2 , 3, 5, 8, 10]

}
function main()

Material UI DatePicker custom renderInput

I recently started using material-ui in my React + TypeScript project.
The code below was written based on the sample code on the official website.

import AdapterDateFns from '@mui/lab/AdapterDateFns';
import DatePicker from '@mui/lab/DatePicker';
import LocalizationProvider from '@mui/lab/LocalizationProvider';
import TextField from '@mui/material/TextField';
import React, { useState } from 'react';

const SampleDatePickerOriginal = () => {
  const [date, setDate] = useState<Date>(new Date());

  const onChangeHandler = (_date: Date | null, keyboardInputValue?: string) => {
    if (_date) {
      setDate(_date);
    }
  };
  return (
    <LocalizationProvider dateAdapter={AdapterDateFns}>
      <DatePicker
        onChange={onChangeHandler}
        value={date}
        renderInput={(params) => <TextField {...params} />}
      />
    </LocalizationProvider>
  );
};

export default SampleDatePickerOriginal;

I wanted to use input element instead of TextField in this code.
So I referred to material-ui’s issue (https://github.com/mui/material-ui-pickers/issues/1751) and wrote the code below.

import AdapterDateFns from '@mui/lab/AdapterDateFns';
import DatePicker from '@mui/lab/DatePicker';
import LocalizationProvider from '@mui/lab/LocalizationProvider';
import React, { useState } from 'react';

const SampleDatePickerCustom = () => {
  const [date, setDate] = useState<Date>(new Date());
  const [isOpen, setIsOpen] = useState<boolean>(false);

  const onChangeHandler = (_date: Date | null, keyboardInputValue?: string) => {
    if(_date){
      setDate(_date);
    }
  };

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns}>
      <DatePicker 
        onChange={onChangeHandler}
        onClose={() => {setIsOpen(false);}}
        open={isOpen}
        value={date} 
        renderInput={({
          ref,
          inputProps,
          disabled,
          onChange,
          value,
          ...other
        }) => (
          <div ref={ref}>
            <input
              style={{ display: 'none' }}
              value={date.toISOString()}
              onChange={onChange}
              disabled={disabled}
              {...inputProps}
            />
            <button onClick={() => {setIsOpen(!isOpen);}}>
              OPEN
            </button>
          </div>)} />
    </LocalizationProvider>
  );
};

export default SampleDatePickerCustom;

This code works fine, but the calendar that opens is in the upper left corner.
How can I make it appear just below the button like when I use TextField?

How can I read data from the resources of a loaded page?

When a page is loaded in the browser, the downloaded resources of the page are displayed in the network tab in devtools. I’m going to write a userscript for a specific page, can I read data from these resources (let’s say it’s json data) using js? (Is it possible to enter some command in the browser console to output the contents of the json that was loaded after the page request?)