Importar la librería

No se encontró ningún archivo de declaración para el módulo ‘jspdf’. ‘D:/proyectoTitulaciòn/angularPDF/WordPdf/node_modules/jspdf/dist/jspdf.min.js’ tiene un tipo “any” de forma implícita.

pequeño ejemplo:

    import { Component } from '@angular/core';
    import jspdf from 'jspdf';
    import html2canvas from 'html2canvas';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'WordPdf';
      constructor() {
        this.downloadPDF();
      }
      public downloadPDF(): void {
        const doc = new jspdf();

doc.text('Hello world!', 10, 10);
doc.save('hello-world.pdf');

}
}

Change the pattern of an input to allow only multidates

I have a field in my form. That field has to accept multidates, for that I am using:

$("#myInput").datepicker({
    format: "dd/mm/yyyy",
    multidate: true,
    templates: {
        rightArrow: '>',
        leftArrow: '<'
    }
});

<input type="text" id="myInput" name="myInput" placeholder="DD/MM/YYYY" class="form-control" autocomplete="off">

It works great, but I would like to prevent the user to input some illegal character with some regex pattern.

I’ve found some alphanumeric examples, but could not find an example for multidate. The idea is accepting numbers [0-9] and the characters "," and "/" only.

I also found this example for a single date, and I tried it but it did not work for multiple dates:

^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)dd$

The accepted format is this: DD/MM/YYYY,DD/MM/YYYY,DD/MM/YYYY

E.g.

23/01/2022,25/01/2022,27/01/2022

why icon is showing on above description while sharing?

I am sharing my website on whatapps from mobile to another mobile . Don’t know why my icon come on top.

My website url :

https://staging.ezylegal.in/legal-consultation

enter image description here

I used like this

<meta property='og:image' content='https://ezylegal.in/images/ezylogo.jpeg'/>
      <meta property="og:image:width" content="200" />
      <meta property="og:image:height" content="200" />

but when I am sharing another web site from my mobile to another mobile . it looks good. Icon show in left side of title and description

link : https://vakilsearch.com/. it is working fine as expected .

why my site icon goes to top while sharing from mobile.
enter image description here

Fetching data using a async function in react [duplicate]

I have been trying to create a table from an array of objects. I’m able to console the data inside the async function. But I couldn’t console it outside.

My code :

useEffect(() => {
  listingCampaignsModels()
}, []);


async function listingCampaignsModels() {
    const apiData = await DataStore.query(Campaign);
    console.log(apiData);
    console.log(typeof(apiData));
    return apiData;
  };

When I tried to console apiData outside, it returns apiData is not defined error.

The data looks like this :

[Model, Model, Model, Model, Model, Model]

Each Model looks like :

-> 1: Model {id: 'c40d6b22-840f-467a-909c-7b2b19960ffb', campaignOwner: 'eumagnas', campaignName: "mollitlab", startDate: "2022/08/15", endDate: "2022/10/25", expectedRevenue: 25, budgetedCost: 27, actualCost: 28}

I want loop through all the Models and create a table as :

Campaign Owner Campaign Name Start Date End Date Expected Revenue Budgeted Cost Actual Cost
eumagnas mollitlab 2022/08/15 2022/10/25 25 27 28

props.history.push() not working. Not able to route

I am trying to learn GraphQL. But I am stuck at props.history.push. I am not able to route it to another page.

Register.js

import React, { useState }  from 'react'
import {  Row, Col, Form, Button } from 'react-bootstrap'
import { gql, useMutation } from '@apollo/client';

const REGISTER_USER = gql`
  mutation register(
    $username: String!
    $email: String!
    $password: String!
    $confirmPassword: String!
  ) {
    register(
      username: $username
      email: $email
      password: $password
      confirmPassword: $confirmPassword
    ) {
      username
      email
      createdAt
    }
  }
`

export default function Register(props) {
  const [variables, setVariables] = useState({
    email: '',
    username: '',
    password: '',
    confirmPassword: '',
  })
  const [errors, setErrors] = useState({})

  const [registerUser, { loading }] = useMutation(REGISTER_USER, {
    update: (_, __) => props.history.push('/login'),
    onError: (err) => setErrors(err.graphQLErrors[0].extensions.errors),
  })

  const submitRegistrationForm= (e) => {
    e.preventDefault()

    registerUser({ variables })
  }

    return (
        <Row className="bg-white py-5 justify-content-center">
        <Col sm={8} md={6} lg={4} >

          <h1 className="text-center">
            Register
          </h1>

          <Form onSubmit={submitRegistrationForm}>
          <Form.Group className="mb-3">
            <Form.Label className={errors.email && 'text-danger'}>
              {errors.email ?? 'Email address'}
            </Form.Label>
            <Form.Control
              type="email"
              value={variables.email}
              className={errors.email && 'is-invalid'}
              onChange={(e) =>
                setVariables({ ...variables, email: e.target.value })
              }
            />
            
          </Form.Group>
          <Form.Group className="mb-3">
            <Form.Label className={errors.username && 'text-danger'}>
              {errors.username ?? 'Username'}
            </Form.Label>
            <Form.Control
              type="text"
              value={variables.username}
              className={errors.username && 'is-invalid'}
              onChange={(e) =>
                setVariables({ ...variables, username: e.target.value })
              }
            />
          </Form.Group>
          <Form.Group className="mb-3">
            <Form.Label className={errors.password && 'text-danger'}>
              {errors.password ?? 'Password'}
            </Form.Label>
            <Form.Control
              type="password"
              value={variables.password}
              className={errors.password && 'is-invalid'}
              onChange={(e) =>
                setVariables({ ...variables, password: e.target.value })
              }
            />
          </Form.Group>
          <Form.Group className="mb-3">
            <Form.Label className={errors.confirmPassword && 'text-danger'}>
              {errors.confirmPassword ?? 'Confirm password'}
            </Form.Label>
            <Form.Control
              type="password"
              value={variables.confirmPassword}
              className={errors.confirmPassword && 'is-invalid'}
              onChange={(e) =>
                setVariables({
                  ...variables,
                  confirmPassword: e.target.value,
                })
              }
            />
          </Form.Group>

            <div className="text-center">
              <Button variant="success" type="submit" disables={loading}>
                  {loading ? 'loading..':'Register'}
               
              </Button>
            </div>
          </Form>

        </Col>
      </Row>
    )
}

App.js

import React from 'react';
import { Container} from 'react-bootstrap';
import {BrowserRouter, Route, Routes} from 'react-router-dom';

import ApolloProvider from "./ApolloProvider";

import './App.scss';

import Home from "./pages/Home";
import Register from "./pages/Register";
import Login from "./pages/Login";


function App() {


  return (
    <ApolloProvider>
      <BrowserRouter>
        <Container className="pt-5">
          <Routes>
          <Route  exact path="/" element={<Home />}/>
          <Route path="/register"  element={<Register />} />
          <Route path="/login"  element={<Login />} />
          </Routes>
        </Container>
      </BrowserRouter>
    </ApolloProvider>
  );
}

export default App;

I am able to get the entries in mySQL table, but after register I am not able to redirect to /login.

I am getting the TypeError in console. But I am not sure why I am getting this.

enter image description here

package.json

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@apollo/client": "^3.5.7",
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^12.0.0",
    "@testing-library/user-event": "^13.2.1",
    "bootstrap": "^5.1.3",
    "graphql": "^16.2.0",
    "node-sass": "^7.0.1",
    "react": "^17.0.2",
    "react-bootstrap": "^2.1.0",
    "react-dom": "^17.0.2",
    "react-router-dom": "^6.2.1",
    "react-scripts": "5.0.0",
    "web-vitals": "^2.1.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Using v6 of "react-router-dom".

Remove an array from an Array if a certain value exists in the array in javascript

Trying to remove an entire array if within my data if it contains a certain value.

What would be the best approach to this problem?

data = [['true', 'visiting-today', 'DVM-Wiessman','J-001'],
['false', 'visiting-tommorrow', 'DVM-Stevens','K-001'],
['true', 'visiting-tommorrow', 'DVM-Stevens','Z-001'],
['false', 'visiting-tommorrow', 'DVM-Kon','J-001']]


var del_value = 'J-001';

function remove_from_list(list) {
    for( var i = 0; i < list.length; i++) { 
        for( var j =0; j < Object.keys(list[i]).length.length; j++) {
            if(del_value == list[i][j]) {
                list.splice(list[i], 1);
            }
        }
    }
    return list;
}

actual output

data = 
[['true', 'visiting-today', 'DVM-Wiessman','J-001'],
['false', 'visiting-tommorrow', 'DVM-Stevens','K-001'],
['true', 'visiting-tommorrow', 'DVM-Stevens','Z-001'],
['false', 'visiting-tommorrow', 'DVM-Kon','J-001']]

desired result — to remove all arrays that have the value 'J-001'

data = 
[['false', 'visiting-tommorrow', 'DVM-Stevens','K-001'],
['true', 'visiting-tommorrow', 'DVM-Stevens','Z-001']]

Looping a Rock, Paper Scissors game multiple times in Javascript using a function

I am currently working on a simple rock, paper scissor game while using different functions. I want to have the game loop a couple of times, but I get lost in terms of where I add the loop into the function. I’ve seen a few different solutions online, but nothing that fits what I have done so far. Any guidance would be appreciated, thanks!

const computerSelection = computerPlay

function playerSelection() {
    const playerSelection = prompt("Lets play rock, paper, scissors. Which is yours?")

    return playerSelection
}

function computerPlay() {
    const pieces = ['rock', 'paper', 'scissors'];
    const piece = pieces[Math.floor(Math.random() * pieces.length)]
    
    return piece;
}

function playRound(playerSelection, computerSelection) {
    // Rock 
    if (playerSelection == 'rock') {
        if (computerSelection == 'scissors') {
            return 'You win! Rock beats Scissors!'
        } else if (computerSelection == 'paper') {
            return 'You lose! Paper beats rock!'
        } else if (computerSelection == 'rock') {
            return 'Its a tie!'
        }
    }

    // Scissors
    if (playerSelection == 'scissors') {
        if (computerSelection == 'rock') {
            return 'You lose! Rock beats scissors!'
        } else if (computerSelection == 'paper') {
            return 'You win! Scissors beats paper!'
        } else if (computerSelection == 'scissors') {
            return 'Its a tie!'
        }
    }

    // Paper
    if (playerSelection == 'paper') {
        if (computerSelection == 'rock') {
            return 'You win! Paper beats rock!'
        } else if (computerSelection == 'scissors') {
            return 'You lose! Scissors beats paper!'
        } else if (computerSelection == 'paper') {
            return 'Its a tie!'
        }
    }
}

function game(playRound) {
    for (var i = 0; i < 5; i++){
    }
    return playRound
}

console.log(game())
//console.log(playRound(playerSelection(), computerSelection()));

React renders repeatedly on event

I’m using sockets in my website and there’s an event where one user can send a word to the server, which emits (art-addpic) an image URL corresponding to that word to everyone, but only the user with isArtist=true gets to respond to the event.
The artist’s page is supposed to update an existing list of image URLs (optionImages) with the received URL once. But when the event is received, all images in the list are replaced by the received URL. Furthermore, the component rendering the list of images ArtBoard is not re-rendered with updated URLs.
I’m new to React. Where am I going wrong?

I’ve checked the server and the event art-addpic is broadcasted only once.

Arena.js: (The webpage where this happens):

import React, { useEffect, useState } from "react";
import Leaderboard from "../comps/Leaderboard";
import { io } from "socket.io-client";
import Service from "../Service";
import DetBoard from "../comps/DetBoard";
import ArtBoard from "../comps/ArtBoard";
const username = "Nick"
const roomkey="abc"
let userid;
if(localStorage.getItem('userid')){
    userid = localStorage.getItem('userid')
}
else{
    userid = Service.makeid(5);
    localStorage.setItem('userid', userid);
}
function useForceUpdate(){
    const [value, setValue] = useState(0); // integer state
    return () => setValue(value => value + 1); // update the state to force render
}
// const [userid,setUserId] = 
const socket = io('http://localhost:3001', {query:"username="+username+"&roomkey="+roomkey+"&userid="+userid});
const Arena = (props)=>{
    const [isArtist, setIsArtist] = useState(false);
    const [focusImage, setFocusImage] = useState('https://i.imgur.com/61HsZCU.jpeg')
    const [players, setPlayers] = useState([]);
    const [optionImages, setOptionImages] = useState([
        'https://i.imgur.com/61HsZCU.jpeg',
        'https://i.imgur.com/61HsZCU.jpeg',
        'https://i.imgur.com/61HsZCU.jpeg',
        'https://i.imgur.com/61HsZCU.jpeg',
        'https://i.imgur.com/61HsZCU.jpeg'
    ])
    useEffect(()=>{
        socket.on('connect',()=>{
            console.log("connected")
        })
        socket.on('players', (data)=>{
            data = JSON.parse(data)
            console.log(data)
            setPlayers(data)
        })
        socket.on('artist', (data)=>{
            if(data===userid){
                console.log('You are an artist, Mr White.')
                setIsArtist(true);
            }
            else{
                setIsArtist(false);
            }
        })    
        socket.on('art-addpic', (data)=>{
            data = JSON.parse(data)
            console.log(data)
            let tempOps =optionImages;
            tempOps.splice(0, 1);
            tempOps.push(data.url)
            console.log(tempOps)
            setOptionImages(tempOps);
        })
    }, [
        optionImages
    ]);
    if(isArtist){
        return(
            <div>
            <Leaderboard players={players}></Leaderboard>
            {/* <ArtBoard></ArtBoard> */}
            <ArtBoard socket={socket} focusImage={focusImage} optionImages={optionImages} setOptionImages={setOptionImages}/>         
        </div>
        );
    }
    else{
        return (
            <div>
            <Leaderboard players={players}></Leaderboard>
            {/* <ArtBoard></ArtBoard> */}
            <DetBoard socket={socket} focusImage={focusImage}/>         
        </div>
        );
    }
}
export default Arena;

How to always place upload field right side next to preview file in Dropzone?

Currently I have a customized dropzone that I styled on my own. However, after uploaded a file, I want the upload field is always right side next file preview, just like this:

enter image description here

But by the default dropzone always places the upload field left side to the file preview as in my current script below.

$(document).ready(function() {

  var previewNode = document.querySelector('.upload-thumbnail');
  previewNode.id = "";

  var previewTemplate = previewNode.parentNode.innerHTML;
  previewNode.parentNode.removeChild(previewNode);


  default_dz_option = {
    url: '/upload',
    method: "post",
    autoProcessQueue: false,
    uploadMultiple: true,
    parallelUploads: 100,
    thumbnailWidth: 80,
    thumbnailHeight: 80,
    timeout: 0,
    previewTemplate: previewTemplate,
    previewsContainer: '.thumbnail-container'
  };

  myDropzone = new Dropzone('#upload_field', default_dz_option);

});
.thumbnail-container {
  padding: 0 10px;
}

.upload-thumbnail {
  background: #E7F3FF;
  color: #1977F2;
  padding: 5px 16px 5px 7px;
  border-radius: 50px;
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  flex-grow: 0;
  min-width: 100px;
  position: relative !important;
  margin-right: 8px;
  margin-bottom: 10px;
  position: relative;
}

.upload-thumbnail {
  font-size: 10px;
}

.upload-thumbnail a {
  font-size: 11px;
  text-decoration: none;
}

.upload-thumbnail span {
  font-size: 11px;
}

.upload-thumbnail .remove-thumbnail {
  transform: translateX(5px);
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0-10/css/all.min.css" integrity="sha512-Pv1WJMqAtVgNNct5vhq+4cgkKinKpV1jCwSWD4am9CjwxsJSCkLWKcE/ZBqHnEE1mHs01c8B0GMvcn/pQ/yrog==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-+YQ4JLhjyBLPDQt//I+STsc9iw4uQqACwlvpslubQzn4u2UU2UFM80nGisd026JF" crossorigin="anonymous"></script>

<div class="thumbnail-container" style="display: flex;flex-wrap: wrap;margin-top: 10px;position: relative;width: 600px;">
  <div class="upload-thumbnail" style="margin-right: 30px;">
    <div class="image">
      <i class="fa fa-paperclip" aria-hidden="true"></i>&nbsp;&nbsp;
      <a href="javascript:" class="image-name" data-dz-name></a href="javascript:">
    </div>
    <a href="javascript:" class="remove-thumbnail" data-dz-remove><i class="fas fa-times "></i></a>
  </div>
  <div class="" id="upload_field" style="width: 36px; height: 36px; border: 1px dashed; "> </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/min/dropzone.min.js" integrity="sha512-oQq8uth41D+gIH/NJvSJvVB85MFk1eWpMK6glnkg6I7EdMqC1XVkW7RxLheXwmFdG03qScCM7gKS/Cx3FYt7Tg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

How can I achieve that like in the picture? Thanks so much.

Sinon stub out module’s function from a middleware

Based on this question, I need to also make a test for a middleware which also uses the db-connection.js file. The middleware file will look like this:

const dbConnection = require('./db-connection.js')

module.exports = function (...args) {
   return async function (req, res, next) {
      // somethin' somethin' ...
      const dbClient = dbConnection.db
      const docs = await dbClient.collection('test').find()
 
      if (!docs) {
         return next(Boom.forbidden())
      }
   }
}

, the database connection file do not change, which is:

const MongoClient = require('mongodb').MongoClient
const dbName = 'test'
const url = process.env.MONGO_URL

const client = new MongoClient(url, { useNewUrlParser: true,
  useUnifiedTopology: true,
  bufferMaxEntries: 0 // dont buffer querys when not connected
})

const init = () => {
  return client.connect().then(() => {
    logger.info(`mongdb db:${dbName} connected`)

    const db = client.db(dbName)
  })
}

/**
 * @type {Connection}
 */
module.exports = {
  init,
  client,
  get db () {
    return client.db(dbName)
  }
}

How the middleware works is by passing list of strings (that strings is roles), I have to query to the database and check whether there is a record of each roles. If the record exists, I will return next(), while if the record does not exist, I will return next(Boom.forbidden()) (next function with a 403 status code from Boom module).

Given the details above, how does one make a test to test out the return value of the middleware if the record exists or not? This means I have to assert the next() and next(Boom.forbidden) to be exact.

How to use just 1 useState() for serveral states

I have a react component that uses several states which are initialized in the same way useState(false), is there a way to combine all these states into a single useState(false)

  const [loading, setLoading] = useState(false);
  const [fields, setFields] = useState(false);
  const [wrongImageType, setWrongImageType] = useState(false);
  const [aboutError, setAboutError] = useState(false);
  const [destinationError, setDestinationError] = useState(false)

how Variable assignment work in javascript?

class Node{
    constructor(val) {
        this.val = val;
        this.next = null;
    }
}

class SinglyLingkedList{
    constructor() {
        this.head = null;
        this.tail = null;
        this.length = 0;
    }

    push(val){
        var newNode = new Node(val)
        if (this.head == null) {
            this.head = newNode;
            this.tail = this.head;
        } else{
            this.tail.next = newNode;
            this.tail = newNode;
        }
        
        this.length++;
        return this
    }

    reverse(){
        var node = this.head;
        this.head.next = null;
        this.tail = this.head;
        return node;
    }
}

var list = new SinglyLingkedList()
list.push("1")
list.push("2")
list.push("3")
list.reverse()

I’m new at programming. I’m pretty confused with my variable assignment in the reverse method, especially at

        var node = this.head;
        this.head.next = null;
        this.tail = this.head;
        return node;

Why return node is affected by this.head.next null? is not like what I expected
its return

Node : {val: '1', next: null}

not

Node : {val: '1', next: Node}

I wanted to know why it happened?