Click unsaved contact in web.whatsapp with Selenium

I’m using it to do a project for automation testing on web.whatsapp, using Selenium Webdriver, Chromedriver and C# .

I would like to send a message to a contact that is not yet on the list and is not saved in the smartphone’s phonebook.

Using “api.whatsapp” it is possible to send to a contact, but it refreshes the page again. The need is for it to be sent without refreshing the page.

I found this code using javascript, but it’s not working.

IJavaScriptExecutor js = (IJavaScriptExecutor)webDriver;
js.ExecuteScript("document.getElementsByClassName('executor')[0].setAttribute(arguments[0], arguments[1]);", "href", "https://api.whatsapp.com/send?phone=number");

can you help with this?

How to get a timezone name from ISO string in Javascript?

Here I have a ISO string – 2023-02-23T14:30:00+11:00
I tried using luxon to get the timezone name but it returns “UTC+11” instead I wanted it to return a timezone name like Australia/Sydney. I do understand there will be different timezones with the same offset. But that is not a problem for me.

Is there a way to achieve this. I went through all stackoverflow questions and none of the suggested solutions works for me.

Here is my code snippet

  let dt = DateTime.fromISO('2023-02-23T14:30:00+11:00', { setZone: true });
  console.log(dt.zone.name) // returns UTC+11

Add line breaks in AJAX data

I’m using ajax to pass some data from an advanced custom field wysiwyg editor. In the markup I added, it is the div with class ‘bio’ I’m referring to. The problem is that when I get the data back it’s all in one big paragraph, rather than broken up into multiple like it is in the wysiwyg. I’m guessing this is because it’s sending json instead of markup??? When I log the data being passed in the console, I can see it is separated into paragraphs. Is there a way I can render this out in separate p tags, or is there a way JS can detect the end of a paragraph and I can append a
or something?

Here is my php file

<div id="<?php echo $post->ID; ?>" class="team-section__member" data-ajax-url="<?php echo admin_url("admin-ajax.php"); ?>">
    <img src="<?php echo get_the_post_thumbnail_url(); ?>" alt="">
    <div class="info">
        <?php
        $s = get_the_title();
        $name = explode(' ', trim($s));
        ?>
        <h4 class="name"><?php echo get_the_title(); ?></h4>
        <h6 class="title"><?php echo get_field('team_member_title'); ?></h6>
        <a class="phone" href="tel:<?php echo get_field('team_member_phone_number'); ?>"><?php echo get_field('team_member_phone_number'); ?></a>
        <a class="email" data-email="<?php echo get_field('team_member_email'); ?>" href="mailto:<?php echo get_field('team_member_email'); ?>">Email <?php echo $name[0] . "n"; ?></a>
        <div class="bio"><?php echo get_field('team_member_bio'); ?></div>
    </div>
</div>   
   // Member Bio modal w/ajax
        $(".team-section__member .button").click(function () {
            let member = $(this).parent().parent();
            let memberId = member.attr('id');
            let ajaxUrl = member.data('ajaxUrl');
            let name = member.children('.info').find('.name').text();
            let image = member.children('img').attr('src');
            let title = member.children('.info').find('.title').text();
            let email = member.children('.info').find('.email').data('email');
            let phone = member.children('.info').find('.phone').text();
            let bio = member.children('.info').find('.bio').text();
            $("body").toggleClass("scroll-lock");
            console.log(bio);
            $.ajax({
                type: "POST",
                url: ajaxUrl,
                dataType: 'json',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
                },
                data: {
                    action: 'post_member_id',
                    id: memberId,
                    image: image,
                    name: name,
                    title: title,
                    email: email,
                    phone: phone,
                    bio: bio,
                },
                success:
                    function (data) {
                        $(".team-modal__content").empty();
                        $(".team-modal__content").append(

                            "<div class='team-modal__container'>" +
                            "<button class='modal-button'><span></span><span></span></button>" +

                            "<div class='team-modal__image-wrapper'>" +
                            "<img class='team-modal__image' src=" + image + ">" +
                            "</div>" +

                            "<div class='team-modal__info-wrapper'>" +
                            "<h3 class='team-modal__name'>" + name + "</h3>" +
                            "<h5 class='team-modal__title'>" + title + "</h1>" +
                            "<a class='team-modal__email' href=mailto:" + email + ">" + email + "</a>" +
                            "<a class='team-modal__phone' href=tel:" + phone + ">" + phone + "</a>" +
                            "<div class='team-modal__bio'>" +
                            bio +
                            "</div>" +

                            "</div>" +
                            "</div>"
                        );
                    },
                error: function (error) { console.log(error) },
            });

enter image description here

anki overdrive skd error “Uncaught Error Error: Error: LIBUSB_ERROR_NOT_SUPPORTED”

when I try to use the Anki overdrive sdk I always get the following error:

Uncaught Error Error: Error: LIBUSB_ERROR_NOT_SUPPORTED
    at setUpNoble (c:Usersjuliunode_modulesanki-overdrive-sdklibscanner.js:32:19)
    at processTicksAndRejections (internal/process/task_queues:95:5)

I think I have everything installed.

npm ls

+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
+-- [email protected]
`-- [email protected]

My code:

const anki = require('anki-overdrive-sdk')


console.log("Started")
anki.setUp()
.then(() => {
    console.log("Connected")
})
.catch((err) => {
    throw new Error(err)
})

I tried to reinstall everything it didnt work.

How do i pull youtube video and descriptiron in Java Script?

I want build web page for a web site. But i don’t know how do i am trying to pull this data without any backend project. So my question is how can i build a web page with this components ?

I work on this code for videos

import React from "react";
import PropTypes from "prop-types";

const YoutubeEmbed = ({ Id }) => (
    <div className="video-responsive">
        <iframe
            width="400"
            height="224"
            src={`https://www.youtube.com/embed/${Id}`}
            frameBorder="0"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowFullScreen
            title="Embedded youtube"
        />
    </div>
);

YoutubeEmbed.propTypes = {
    embedId: PropTypes.string.isRequired
};

export default YoutubeEmbed;

React Form submission Bug

I’ve been trying to create a registration form, and storing the data on my browser, using localStorage, but the bug I’m facing is that, only on clicking two times on the register button, the data gets stored on the browser

I’ve created states for the inputs, and called the the handleSubmit function, on submission of the form
and expecting the data to be stored on the browser, on the first click of the button

below is the code is the code I have written

import React, {useState} from "react";
import { Form, Button, Container } from "react-bootstrap";
import { Link } from "react-router-dom";

const Register = () => {
  let [users, setUsers] = useState([])
  let [name, setName] = useState('');
  let [email, setEmail] = useState('');
  let [pswd, setPswd] = useState(''); 

  const handleSubmit = (e)=>{
    e.preventDefault()
    let newData = {uName:name, uEmail:email, uPswd:pswd}
    let newValues = [...users, newData];
    setUsers(newValues);
    localStorage.setItem('users', JSON.stringify(users))
  }

  return (
    <>
      <Container className="border border-success bg-success mt-5">
        <div className="mt-5 d-flex flex-column align-items-center jusitify-content-center">
        <h1 className="text-white">Create An Account</h1>
        <Form className="my-5 w-100" onSubmit={(e)=>handleSubmit(e)}>
          <Form.Group className="mb-3" controlId="formBasicEmail">
            <Form.Label className="text-white">Your Name</Form.Label>
            <Form.Control type="text" placeholder="Enter your name" value={name}  onChange={(e)=>setName(e.target.value)}/>
          </Form.Group>

          <Form.Group className="mb-3" controlId="formBasicEmail">
            <Form.Label className="text-white">Email address</Form.Label>
            <Form.Control type="email" placeholder="Enter email" value={email} onChange={(e)=>setEmail(e.target.value)}/>
          </Form.Group>

          <Form.Group className="mb-3" controlId="formBasicPassword">
            <Form.Label className="text-white">Password</Form.Label>
            <Form.Control type="password" placeholder="Password" value={pswd} onChange={(e)=>setPswd(e.target.value)}/>
          </Form.Group>

          <div className="w-100 d-flex justify-content-center">
          <Button variant="dark" type="submit" className="py-2 px-4 fs-4 fw-bold">
            Register
          </Button>
          </div>

          <div className="text-center pt-4">
            <p className="text-white">Have an account already? <Link to={'/login'} className='text-dark fw-bold'>Login here</Link></p>
          </div>
        </Form>
        </div>
      </Container>
    </>
  );
};

export default Register;

How can I implement method which would return me the same object but with the populated fields based on the provided list of the fields

I’m new to javascript and typescript, please help with the following question.

I have an object with some prepopulated fields:

Person = {
firstName: “John”,
lattName: “Silver”,
birthDater: ”male”,
hearColor:”green”
}

How can I implement method which would return me the same object but with the populated fields based on the provided list of the fields. E.g I need retain fields in the object only that specified in criteria.
Ex:

person: Person = {
firstName: “John”,
lattName: “Silver”,
birthDater: ”male”,
hearColor:”green”
}

requiredFields: Array<string> = [“firstName”, “lattName”]

patialPerson: Person = createObjectequiredFieldsOnly(person, requiredFields: Array<string>)

private createObjectequiredFieldsOnly (person, requiredFields ): Person {
  return Person but with the field provided in requiredFields array, 
         all other fields are empty or not present in object at all.
}

Output:

patialyPopulatedPerson: Person {
firstName: “John”,
lattName: “Silver”
}

One thing must be mentioned here that the partialPerson could substitute the Person in further methods calls. e.g I must be able to do:

proceedWithPerson(person);
proceedWithPerson(partialPerson);

Thanks in advance for the help.

Scale to selected element

I have some boxes and I want to zoom it from position of the clicked box.

Here is UI . Now it will just scale from center, but I want it to scale from position of clicked element

1

Here is my code.

import React, { useState } from "react";
import {
  addDays,
  eachDayOfInterval,
  endOfMonth,
  format,
  getDay,
  startOfMonth,
  subDays,
} from "date-fns";
import { AnimatePresence, motion } from "framer-motion";

const getDaysOfMonth = (date) => {
  const start = startOfMonth(new Date(date));
  const end = endOfMonth(new Date(date));
  return eachDayOfInterval({ start, end });
};

const Calendar = () => {
  const [currentDate, setCurrentDate] = useState(new Date());
  const [selectedDay, setSelectedDay] = useState(null);

  console.log(selectedDay);

  const handleDayClick = (day) => {
    setSelectedDay(day);
  };

  const changeDateByDay = (numberOfDays) => {
    if (numberOfDays < 0) {
      numberOfDays = Math.abs(numberOfDays);
      setCurrentDate(subDays(currentDate, numberOfDays));
    } else {
      setCurrentDate(addDays(currentDate, numberOfDays));
    }
  };

  return (
    <div className="px-4 pt-10">
      <h1 className="text-center font-bold">Calendar</h1>

      <div className="text-center mb-4">
        <h2>
          Current Date: <b>{format(currentDate, "dd-LL-yyyy")}</b>
        </h2>
        <div>
          <button
            className="p-2 border m-4 "
            onClick={() => changeDateByDay(-1)}
          >
            Prev Day
          </button>
          <button
            className="p-2 border m-4 "
            onClick={() => setSelectedDay(null)}
          >
            Clear
          </button>
          <button
            className="p-2 border m-4 "
            onClick={() => changeDateByDay(1)}
          >
            Next Day
          </button>
        </div>
      </div>

      <div className="relative">
        <AnimatePresence>
          {selectedDay === null && (
            <motion.div
              exit={{
                scale: 6,
              }}
              transition={{
                duration: 0.8,
                ease: "easeInOut",
              }}
              className="grid grid-cols-7"
            >
              {getDaysOfMonth(currentDate).map((el, idx) => (
                <div
                  onClick={() => handleDayClick(el)}
                  className="h-16 border p-2 hover:bg-gray-100 transform"
                  key={idx}
                >
                  {format(el, "dd")}
                </div>
              ))}
            </motion.div>
          )}
        </AnimatePresence>

        {selectedDay !== null && (
          <motion.div
            initial={{
              scale: 0,
              y: 0,
            }}
            animate={{
              scale: 1,
            }}
            transition={{
              duration: 0.8,
              ease: "easeInOut",
            }}
            className="absolute top-0"
          >
            <div>
              <h2>20-2-2023</h2>
              <h1>Goinf onward</h1>
              <p>
                Lorem ipsum dolor, sit amet consectetur adipisicing elit. Quae
                placeat, rem, doloremque, tempore optio repellat architecto
                earum esse repellendus nemo tempora qui accusantium sapiente
                ullam inventore id quia explicabo dignissimos?
              </p>
            </div>
          </motion.div>
        )}
      </div>
    </div>
  );
};

export default Calendar;

Here is the ideas that I want to do https://dribbble.com/shots/10224104-Calendar-app.

I will also appreciate if you can give some ideas how to built it.

urllib brings does not bring all elements in website

I am trying to use this code for scraping:

from bs4 import BeautifulSoup
open_url = urllib.request.urlopen('https://en.wikipedia.org/wiki/Guitar')

guitars = open_url.read()

soup = BeautifulSoup(guitars, 'html.parser') 

soup

I am getting a result in HTML that includes the following line:

<div class="vector-sitenotice-container">
<div id="siteNotice"><!-- CentralNotice --></div>
</div>
<input class="mw-checkbox-hack-checkbox" id="vector-toc-collapsed-checkbox" type="checkbox"/>

But when I analyze the website, I see the following elements:

enter image description here

As you can see, the style element is missing and the <div dir = "ltr" id="w112021"> is missing. This includes de <a></a> element inside.

Why isn´t the code returning these elements?

Uncaught FetchError: invalid json response body Unexpected token < in JSON at position 0 [closed]

I am stack with and hopefully someone can help me. While trying to run my project I get an error in the console: Uncaught FetchError: invalid json response body at http://localhost:3000/api/getProjects reason: Unexpected token < in JSON at position 0

The problem is somewhere in the getProjects component and fetchProject, I think it reurns html instead of JSON. But I do not know how to fix it.

GetProjects.ts component:

const query = groq`
    *[_type == "project"]
      ...,
      technologies[]->
  }
`;


type Data = {
  projects: Project[];
};

export default async function handler(
  _req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  
  const projects: Project[] = await sanityClient.fetch(query);

  res.status(200).json({ projects });
}
 

FetchProject.ts component:

import { Project } from "../typing";

export const fetchProjects = async() => {
  const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/getProjects`);

  const data = await res.json();
  const projects = await data.projects;

  return projects ;

};

Also this is my index.tsx and the getStaticProps:

export const getStaticProps: GetStaticProps<Props> = async () => {
  const pageInfo: PageInfo = await fetchPageInfo();
  const skills: Skill [] = await fetchSkills();
  const projects: Project[]  = await fetchProjects();
  const socials: Social []= await fetchSocial();

  return {
    props: {
      pageInfo,
      projects,
      skills,
      socials,
    },
  }

I checked my data structure and it seems everything to be fine, changed the res.status(200).json({ projects }); to stringify but still not working.

Reading binary files with fetch in Javascript

I am trying to parse and read some data from a binary file. I have implemented this using a file input and FileReader but using fetch to get the bin file doesn’t seem to work.

(async () => {
      let response = await fetch("./test.bin");
      let result = await response.arrayBuffer();
      console.log(result);
    })();

Above is the code I am using. It seems for every binary file I try, I get a response of an ArrayBuffer with a byteLength of 1710 and not the file itself.

how to write a function wrapper with correct TS props checking

So basically for my use case, assume we have these functions

const fn1 = ({level, type}) => { console.log(level,type)}
const fn2 = ({level, username}) => { console.log(level,username)}
const fn3 = ({level, age}) => { console.log(level,age)}

Now I have 2 components that calling these functions,

const Component1 = () => { 
   const {level} = useGetUserInfo();
   useEffect((fn1({level, type: 1})) => {}, [])
}

const Component2 = () => { 
   const {level} = useGetUserInfo();
   useEffect((fn2({level, username: 'username'})) => {}, [])
   useEffect((fn3({level, age: '27'})) => {}, [])

}

so as you can see, the part to get level is the same between two components, and I dont want this to happen (in reality, other than level, there is a set of common information taking from different places which making the code longer and more repeated)

So what I want to achieve is write a custom hook that take in the fn array and return the wrapper fn

So that i can write like this

const Component1 = () => { 
   const [returnFn1] = useWrapperFn(fn1);
   useEffect((returnFn1({type: 1})) => {}, []). // --> here i dont need to pass level anymore
}

const Component2 = () => { 
   const [returnFn2, returnFn3] = useWrapperFn(fn2,fn3);
   useEffect((returnFn2({username: 'username'})) => {}, []) // --> no need to pass in level
   useEffect((returnFn3({age: '27'})) => {}, []) // --> no need to pass in level
}

so far this is my hook that appriciate your help to give feedback for fixing:

const useWrapperFn = <T extends any[]>(fns: ((...args: T) => void)[]) => {
   const {level} = useGetUserInfo();

  const returnFns = fns.map((fn) => {
    return ((...args: any[]) => {
      // @ts-ignore
      fn({ ...args[0], level}); //-> here i inject the level
    }) as (props: Omit<NonNullable<Parameters<typeof fn>[0]>, 'level'>) => void;
  });

  return returnFns;
};

export default useWrapperFn;

What I want is when i used the returnFn, it should still having correct props type checking for the remaining fields. For example when I called returnFn1 and doesnt pass in type, TS error will be prompt.

returnFn1({type: 1}) // -> works 
returnFn1() // -> will throw ts error missing type

Current behavior

Currently JS wise, the logic is correct

For TS lint check wise, it is working with Component 1 ( passing only 1 fn to array)

However, for Component2 (passing more than 1 fn), then the TS lint will be a combination of all function props

This would mean that

returnFn2({username: 'username'}) // --> currently prompt that missing `age` , wherease `age` belong to fn3

returnFn3({age: '27'}) // --> currently prompt that missing `usernamse` , wherease `username` belong to fn2

So is there anyway to modify my useWrapperFn hook, so that the returnedFn arrays it return will have correct props type

Query MongoDB no es como esperaba [closed]

Tengo una colleccion que guarda datos de unos vehiculos de la siguiente forma:

enter image description here

Los vehiculos se repiten y el campo de horometro y odometro son acumuladores. Y lo que me interesa obtener es una agrupacion de los vehiculos que tenga el ultimo odometro y el ultimo horometro y adicional a esto dos campos de horometro_total y odometro_total que tenga el total del de la suma de todos los vehiculos del odometro y el horometro. Algo asi:

enter image description here

Habia tratatdo de hacerlo de esta forma:

const modelHistoryDetailedReport = function(){

    const projectOptions = {
        'ficha': 1,
        'odometro_veh': 1,
        'horometro_veh': 1,
        'horometer': { $round: [ "$horometer_sum", 4 ] },
        'odometer': { $round: [ "$odometer_sum", 4 ] },
    }
    
    this.objectQuery = [
        { $match: thisFilter },
        {
            $group : {
                _id: "$ficha",
                horometer_sum: { '$sum': '$horometro_veh' },
                odometer_sum: { '$sum': '$odometro_veh' },
            }
        },
        { $project: projectOptions },
        
    ];
}

Pero soy novato en MongoDB por tanto no ha quedado bien.