teleren/devto huggingface dataset:
Intro to React Hook Form 
Tags: react, javascript
Published: 2020-06-26 17:34:43

A quick way to render your form and get some user input is to incorporate the React Hook Form in your next app. Forms have always seemed to have many moving parts to me, but using React Hook Form simplified the process. 


To get started, enter this into the command line -
`npm install react-hook-form`

Once you've done that, write this line at the top of your Form.js file - 
`import {useForm} from 'react-hook-form'`

This imports the function useForm(). 
Next, we will focus on three variables that useForm() returns: register, handleSubmit, and errors. 

It will look like this: 
![useForm() syntax](https://dev-to-uploads.s3.amazonaws.com/i/800xw4719yzlx0alifxa.png)

Now we'll set up a basic form before adding in the variables from useForm().

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/34e5le2i9417754oyz54.png)

The register variable will handle tracking changes on the input fields of your form. Pass in `{register}` as the value for the ref property of the input, like so. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ij7i4iye26bo15lycs6u.png)


The form needs an onSubmit property so we can send the data from the form. The value of onSubmit will be `handleSubmit` which will take a callback function as its argument.

For demo purposes, we will console log our form data to ensure we are getting it when we click submit.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/b56m754r7iucfea4i8ff.png)

In your browser, open up the console, fill out the form, and click submit. You should see an object with the form data in the console. At this point, temporarily remove `errors` as one of the variables retrieved from useForm(), otherwise it will error out. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/vwx3a26ghyvzjm0lq1op.png)

<h3>Validations</h3>

The React Hook Form makes it quick and simple to implement validation in your forms. You can include `errors` again as one of the variables retrieved from calling useForm(). In your `register` value, pass in an object containing key/value pairs with proper validations. 

We want to ensure a user types in a password, and that it is a sufficient length. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/8yqfstz8tkrqmmzauv7r.png)

For the user to know the requirements for the password, we need to notify them using `errors`.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/eh19x21zbpzypn6y9hnw.png)

Your form will display an error message if a password has not been entered or if it was too short. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/z7im3yit76aadch4p2vx.png)

There's much more to React Hook Form and I encourage using the resources below!

<h3>Resources</h3>

Here are the resources I used to learn about React Hook Form. 

[Video tutorial](https://www.youtube.com/watch?v=bU_eq8qyjic)

[React-hook-form](https://react-hook-form.com/get-started)
Web scraping using Python, requests and beautiful soup.
Tags: python
Published: 2020-06-26 17:29:41

Hello, noobs, 
So this is my second post in this forum and we are going to learn how to scrape data from a website using <strong>Python,beautifulsoup4 and requests</strong> in this series.

I will presume that you are using a Unix based os for the purposes of this tutorial.
Now heading onto the yummy part of it. We will start by creating a new directory,.

```
   cd Desktop && mkdir webscraping && cd webscraping
```
While still on your terminal, create a virtual environment, activate it.
```
   python3 -m virtualenv venv && source venv/bin/activate
```
Now we install the libraries we need.
```
  pip install requests  beautifulsoup4 pandas
```
Now we are all set up to go. In the webscraping folder that we had  created earlier create a file named <strong>app.py</strong>
```
   touch app.py
```

In the file, import the modules that we need.
```
 from bs4 import BeautifulSoup
 import requests
 import pandas as pd
```
We will use century21 as our data source for the purpose of this tutorial. we will now call the URL 
```
url = "https://www.century21.com/real-estate/rock-springs-wy/LCWYROCKSPRINGS/?ty=0"

response = requests.get(url)
c = response.content
```
We can now start our webscraping part.
```
soup = BeautifulSoup(c,'html.parser')
all = (I for I in soup.find_all('div',{'class':'infinite-item'} )

d = {}
l = []
for i in all:
    price = i.find('a',{'class':'listing-price'},text=True)
    if price:
        d['price'] = price.get_text().strip()
    beds= i.find('div',{'class':'property-beds'})
    if beds:
        d['beds'] = beds.get_text().strip()
    bath = i.find('div',{'class':'property-baths'})
    if bath:
        d['bath'] = bath.get_text().strip()

    address = i.find('div',{'class':'property-address'})
    if address:
        d['address'] = address.get_text().strip()

    address_city = i.find('div',{'class':'property-address-city'})
    if address_city:
        d['address_city'] = address_city.get_text().strip()
    l.append(d)
```
we can now save the data in a pandas data frame and a csv file
```
df = pd.DataFrame(l)
df.to_csv('Output.csv',mode='a',header='False'
```
Hooray... You now have a working webscraping script that is functional.
You can follow me on GitHub https://github.com/manulangat1

Corrections and criticism are highly welcomed and appreciated.
See you next time...
Day-10: Bash Scripting - #2
Tags: cybersecurity, security, bash, blogaday
Published: 2020-06-26 17:29:05

**Day-10:** So I did continued with bash scripting today! Going more deep in bash scripts! Check out my [Bash Scripting - #1](https://dev.to/fenilshah16/day-9-bash-scripting-1-mi7) before reading the below notes! 

### **Variables!**
- In bash syntax, variables $1 to represent the first command-line argument, $2 to represent the second command-line argument, and so on. And “$@” is the variable name for all arguments passed in. Use the syntax `VARIABLE_NAME=VARIABLE_VALUE`

```
#!/bin/bash

BIRTHDATE=$1
```

### **Operating the Variables!**
- The user’s input string will be in the format of “2020–05–06”, we can convert the user’s birthdate to a Unix timestamp.
```
#!/bin/bash

BIRTHDATE=$(date -jf “%Y-%m-%d” $1 +%s)
NOW=$(date -jf “%a %b %d %T %Z %Y” “$(date)” +%s)

DIFF_IN_SECONDS=$(expr $NOW — $BIRTHDATE)
DIFF_IN_DAYS=$(expr $DIFF_IN_SECONDS / 86400)

echo "You are $DIFF_IN_DAYS days old."
```
- Breaking down, The $() tells Unix to execute the command surrounded by the parenthesis and replace the variable with the output of the command. This is called "command substitution".
- Date: displays time on Unix systems!
- `-jf`: Convert one date format to another
- '%Y-%m-%d': Tells date that the input date string will be in the format of year-month-day!
- $1: Specifies that the input string is the first argument of the script!
- +%s: Tells date to output the date as the number of seconds that have passed since the “Unix epoch”.

- The second line command: `NOW=$(date -jf “%a %b %d %T %Z %Y” “$(date)” +%s)` in this converted the current time into a Unix timestamp.
- The third line command:`DIFF_IN_SECONDS=$(expr $NOW — $BIRTHDATE)` in this calculated the difference between the two dates in seconds. We can calculate the difference between the two timestamps by using `"expr"`.
- The fourth line command: `DIFF_IN_DAYS=$(expr $DIFF_IN_SECONDS / 86400)` then converted the difference in seconds to a difference in days by dividing the time difference in seconds by 86400. 86400 Seconds = 1 day.
- The fifth line command: `echo "You are $DIFF_IN_DAYS days old."` used echo then to display the time difference!



---

# **Resources:**

**Bash Scripting Cheatsheet:** https://devhints.io/bash
**Bash Script examples:** https://linuxhint.com/30_bash_script_examples/
**Medium Blog:** [Bash Scripting](https://medium.com/swlh/the-bash-scripting-tutorial-part-2-e94d113cf33) (You need Premium subs to access this!)



# **Contact:**

Got doubts? Contact me on [Twitter](https://twitter.com/FenilShah1616). 
Feedbacks are welcomed, do comment it down below! :)
Fallout hacking minigame in JS
Tags: showdev, javascript, css, sideprojects
Published: 2020-06-26 17:26:33

Here is a follow-up of my completely pointless but incredibly fun side-project to [create a retro CRT screen in JS and CSS](https://dev.to/ekeijl/retro-crt-terminal-screen-in-css-js-4afh).

This time I decided to build the [hacking minigame from the Fallout game series](https://www.youtube.com/watch?v=jDJHtLCHuAg), which was also the inspiration to start this project in the first place.

{% codesandbox tlijm module=%2Fcommands%2Ffallout.js initialpath=%2F%3Fcommand%3Dfallout %}

Check the [full Sandbox](https://codesandbox.io/embed/crt-terminal-in-css-js-tlijm?fontsize=14&hidenavigation=1&initialpath=%3Fcommand%3Dfallout&module=%2Fcommands%2Ffallout.js&theme=dark) for a bigger screen.

The goal of the game is to find the password that is hidden in this garbled mess of characters. You can click a word or move with the arrow keys and use the enter key to confirm. Incorrect guesses will result in a hint indicating how many letters the password has in common with your guess.

# Some of the stuff I've learned

- Hexadecimal numbers (`0xffff`) can be used as regular numbers in JS, so you can easily add and subtract them. Seems obvious, just never thought about it.
- The CSS `ch` unit ([width of one character](https://meyerweb.com/eric/thoughts/2018/06/28/what-is-the-css-ch-unit/)) combined with a [monospace font](https://fonts.google.com/specimen/VT323?selection.family=VT323&sidebar.open) is super useful for building these kind of text based interfaces, where I want to have a maximum of exactly 80 characters on every line.
- [CSS columns](https://css-tricks.com/almanac/properties/c/columns/) is something I rarely use, but works perfectly here. The `column-fill: auto` property was crucial for filling columns one by one, instead of in a balanced manner.
- To word-break the passwords and highlight them over multiple lines, I first tried putting a password in a single span with the  `word-break: break-all` property, but later switched to one `<span>` per character, since that makes the whole thing easier to control using JS and also easier to position. I then assign some `data` attributes to the span to keep track of which word is being clicked and highlighted.

# Any cool ideas?

What should I build next? Know any other games with terminal screens like these? Let me know! 👇👇👇
Happy Pride! 🌈
Tags: happypride, lwt, pridesummit, swag
Published: 2020-06-26 17:15:48

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/15td633nbjcvvmtgyhvn.jpeg)
Got my Lesbians Who Tech's QueerWomenCode t-shirt this morning, and just in time for LWT's (NotIRL) Pride Summit today! 

Here's their last day's agenda: https://events.bizzabo.com/225938/agenda

I'm stoked and looking forward to "[The Power of Representation with the Creator & Cast of the L Word: Generation Q](https://events.bizzabo.com/225938/agenda/session/271248)" tonight, it's 10PM Irish time! 

I haven't been watching it all live as it's all PDT, but they have it all recorded, so I'll be checking those replays out.
Nome do índice muito longo? Escolha outro!
Tags: laravel, migration, eloquent
Published: 2020-06-26 17:03:44

```
Syntax error or access violation: 1059 Identifier name 'XXXX' is too long 
```
Quando criamos um índice no Laravel, as vezes esse nome pode ser maior do que o suportado pelo banco. Então ao invés de só criar o relacionamento, adicione o nome customizado

 $table->foreign('pessoa_id', 'NOME_DO_INDICE')
            ->references('id')->on('pessoas')
            ->onDelete('cascade');

Show!
Share a quick tip you learned about web dev this year
Tags: webdev, html, css, discuss
Published: 2020-06-26 17:02:52

Hey everyone! Let's share one tip that we learned recently, whether its about javascript, html, css, react, etc. So beginners and even pros can learn something that they didn't before!

<h4>Tip</h4>
In JavaScript, Use event.stopImmediatePropagation() method to stop actions from a child element to bubble up to the parent.

So if for eample both parent and child execute a different action, clicking on the child element will execute its action and the action of its parent as well. Thus, by using event.stopImmediatePropagation() we can effectively prevent that.


You can comment your tip below

Can't wait to hear all of yours!
Discuss: What's the one thing you hate about programming?
Tags: discuss, watercooler, career
Published: 2020-06-26 17:01:41

What's that **one thing** that annoys you? What's that **one thing** that you would improve if you were made the god of programming?

Alternatively, what was that **one thing** that was a significant roadblock in your programming history?

(PS: You can rant about more than one issue)
Day 1 of #30DaysOfCode
Tags: go, codenewbie, motivation, challenge
Published: 2020-06-26 16:50:39

I'm starting #30DaysOfCode challenge of learning new things nonstop for the next 30 days. I would be learning a new programming language called #golang and would be improving my NodeJs(Restful API Development) skills. In addition to learning these two things, I would be documenting my journey here on Instagram and all other mediums. Also, I will be reading some books to make my life better. The books I would be reading includes The Power Of Habit by Charles Duhigg, The Rudest Book Ever by  Shwetabh Gangwar, etc.
Okay.
Today is day 1 and I have started learning the Go Programming Language. I learnt writing Variables, Slices, Functions, Return Type Function, For Loops, Custom Type Declaration, Receiver Functions, Multiple Return Values and more. I can't even believe that I learnt this much in a single day. But it's true and all thanks to years of coding and struggles that I have gone through. Because of my knowledge and skills in other programming languages, I was able to learn Go very quickly.
I should say that Go will replace Swift as my favourite programming language. I really enjoyed learning and coding In Go. It was a good experience and I look forward to learning more Go in the upcoming days.
Alright, Signing Off.

Image Credit: <a href="https://www.instagram.com/dev.kyle" target="_blank" rel="noopener noreferrer">Kyle The Dev</a>

Connect With Me:
Youtube: <a href="https://www.youtube.com/c/ShubhamSauravYT" target="_blank" rel="noopener noreferrer">ShubhamSauravYT</a>.
Twitter: <a href="https://www.twitter.com/hiShubhamSaurav" target="_blank" rel="noopener noreferrer">@hiShubhamSaurav</a>
Instagram: <a href="https://www.instagram.com/hiShubhamSaurav" target="_blank" rel="noopener noreferrer">@hiShubhamSaurav</a>
Facebook: <a href="https://facebook.com/hiShubhamSaurav" target="_blank" rel="noopener noreferrer">@hiShubhamSaurav</a>
Ecommerce website using Django for backend and React for frontend
Tags: react, python, django, redux
Published: 2020-06-26 16:47:08

Hello noobs, 
This is my first time posting to the forum, so pardon any mistakes in the post.
As from tomorrow, I would start an eight-part series on building an e-commerce application using Django for the backend (and also Django rest framework) and React for the frontend.
See you then.
```
  print("Happy hacking!!!!")
```
Am sorry guys I could start the series due to personal reasons. But now we are good to go.
Password Generator in Python
Tags: python, coding, programming
Published: 2020-06-26 16:32:29

Let's make [password generator tool](https://tools.codesnail.com/strong-password-generator/) in python

```python
import string
import random

if __name__ == "__main__":
    s1 = string.ascii_lowercase
    s2 = string.ascii_uppercase
    s3 = string.digits
    s4 = string.punctuation

    plen = int(input("Enter password length: "))
    s = []
    s.extend(list(s1))
    s.extend(list(s2))
    s.extend(list(s3))
    s.extend(list(s4))

    print("Your password: ", end="")
    print("".join(random.sample(s, plen)))
```
source: https://bit.ly/2YBHofb
🤷‍♀️ Which DataScience related blogs/ magazines. Do you read? ??
Tags: discuss, watercooler, python, datascience
Published: 2020-06-26 16:30:20

---

title:  🤷‍♀️ Which DataScience related blogs/ magazines. Do you read? ??
published: true
description: Weigh in with your thoughts.
tags: discuss, watercooler, python, datascience
cover: https://dev-to-uploads.s3.amazonaws.com/i/7uv6h3oc8s99t2v0lj0h.png
series: career questions for data folks
---

Weigh in with your favorites places to read amazing Data Science content from 👇.

{% twitter 1276551637159608322 %}
> inspired by @ravinwashere
What was your win this week?
Tags: discuss, weeklyretro
Published: 2020-06-26 16:27:32

---
title: What was your win this week?
published: true
description: Got to all your meetings on time? Started a new project? Fixed a tricky bug?
tags: discuss, weeklyretro
cover_image: https://cl.ly/188e843c2985/download/Image%202019-02-15%20at%202.36.37%20PM.png
---

👋👋👋👋

Looking back on your week, what was something you're proud of?

All wins count — big or small 🎉

Examples of 'wins' include:

- Getting a promotion!
- Starting a new project
- Fixing a tricky bug
- Cleaning your house...or whatever else that may spark joy 😄

Happy Friday!

![winning!](https://media.giphy.com/media/gsrkIo59dnI8E/giphy.gif).
sublime text ha venido para quedarse
Published: 2020-06-26 16:17:35

---
title: sublime text ha venido para quedarse
published: true
description: sublime text 4 released
tags: 
cover_image: https://www.sublimetext.com/images/og-full.jpg
---

El 21 de Mayo de 2021 se liberó la nueva versión de este magnífico editor, de la era pre-vs-code y pre-phpstorm.
Desde hace poco más de 3 años el desarrollo se paralizó y probablemente lo dejaron abandonado , posiblemente
por culpa de los IDES más poderosos y versátiles de la marca **JETBRAINS** y **VS-CODE**, esté último de Microsoft.

Sin embargo, quiero apuntar una anécdota sobre este editor, y quiero darle una oportunidad.

[Mi equipo](https://dev.to/robertomanchado/como-crear-un-equipo-de-bajo-presupuesto-para-desarrollar-10gd) es de bajo rendimiento y **PHPSTORM** funciona a duras penas y me resulta frustrante tener que utilizar
otros editores de código rápido tipo **NotePad++** y sobre todo mi querido **SublimeText3**, de cuando lo utilizaba 
para desarrollar.

Actualicé mi sistema **Lubuntu18.04** el día 29 de Mayo y mi sorpresa fue, al abrir de nuevo SublimeText, la interfaz
había cambiado.

No le presté demasiada atención a la actualización de Sublime, pero apunté el detalle. Me dispuse a realizar
una prueba técnica apostando por este último editor que ya conocía en lugar de **PHPSTORM** . 
La prueba tenía una duración de 2 horas, y exigía cierto nivel de precisión con **PHP-UNIT** y **POO** en **PHP-PLAIN**	, sin ningún
tipo de framework o microframework.

SublimeText, se estaba comportando perfectamente, casi igual o mejor que **PHPSTORM**, pero con una tremenda ventaja. Es extraordinariamente
rápido.

Desarrollé la práctica en apenas 1 hora y después me entero de que la nueva versión de Sublime Text, es una nueva versión
actualizada después de 3 o 4 años, supuestamente abandonado el desarrollo. [SUBLIME](https://www.sublimetext.com/blog/articles/sublime-text-4).

El editor se comportó para mi sistema, mucho mejor que **PHPSTORM**. 

Esto no quiere decir que la nueva versión de SublimeText, sea mejor que los productos de JETBRAINS. Ni mucho menos faltar el respeto a otros magníficos editores
(Brackets,Nova ...). Le queda mucho camino que recorrer pero apunta a maneras y bastante bien. Está probado perfectamente en mi equipo y aunque probablemente existan herramientas para extenderlo, puede convertirse de nuevo en un editor de referencia.

Si cojen lo mejor de **PHPSTORM**, **( ver las diferencias con GIT, autocompletado de clases y métodos, xDebug )** y quitan las , que creo que son
demasiadas opciones que tiene, sin malgastar velocidad y memoria y lo enfocan, sólo para eso, desarrollar en PHP con un nombre por ejemplo: **Sublime-PHP**, tienes el producto vendido.

Si además , la licencia de uso , es **justo la mitad** que los productos de JETBRAINS, unos **99US**, tanto que mejor.

Asi que bueno, darle una oportunidad a **Sublime Text 4**. No tiene nada desperdicio.

fdo: roberto manchado
Know Your Tools
Tags: engineeringproductivity, debugger, productivity
Published: 2020-06-26 16:10:53

---
title: Know Your Tools
published: true
date: 2020-06-26 16:05:19 UTC
tags: EngineeringProductivity, Debugger, Productivity
canonical_url: https://www.journeytomastery.net/2020/06/26/know-your-tools/
---

A few months back I switched companies. For me this means new team, new domain, new programming language, new tools. After starting with my first project I quickly learned that I had a lot to learn.

## Waiting

I am working on end2end tests of a web application. If you ever worked on this you know, that end2end tests are very slow.. Because I just started with the programming language (actually this was my first code I wrote in it), I made a lot of newbie errors. Missing imports, missing semicolons, … But the tools I thought were standard didn’t do auto imports or highlighting compiler errors (this does not mean that they did not support this, but I definitely used them wrong). So I always run the build command just to learn 30seconds later that I missed something obvious. When finally everything compiled, the tests were failing. I was also new to the testing framework, so I did not know all features that were supported nor how to use it properly. I need to do some trial and error.

After spending a whole afternoon waiting, I felt very frustrated. I am working in an engineering productivity team. This was definitely not engineering productivity. I want to consult people and support them in being more efficient, but I was not able to be efficient myself. Not even close.

## Increase Productivity – The Power of the Debugger

So I decided to spend the next day to work on my developer setup. I read the documentation and guess what, they were suggesting a different IDE. After setting up the IDE I felt relieved. Compiler errors were displayed immediately, as well as missing imports. This alone would save me hours. I learned how I can execute single test cases (I already knew how to execute single test files but running single tests increased the build runtime even more).

I asked the dev team how I can reduce execution time and got a few more hints. And then I realized that I could just debug the test and evaluate expressions and scroll threw the object instances on the fly. Suddenly I was pretty fast compared to the day before. End2end tests are still slow, I’m not able to change this (at least not in short term), but getting to know the tools, their features and how to use them increased my productivity a lot.

In the past I met some developers who just lived with such a situation. “It’s slow, what can I do? That is how it is.” and they waited and waited (and complained about the slow end2end tests and that they do not want to write more tests). Don’t do this. **Invest a few hours to make a good setup and learn about the recommended tools. Afterwards you are much faster and much happier.**