teleren/devto huggingface dataset:
useState hook simplified!
Tags: react, typescript, javascript, webdev
Published: 2021-03-06 11:36:48

# Lets Begin the discussion 

useState is a react hook, we call it inside a functional component to add some local state to it. Between re-renders React actually preserves the state.

useState returns a pair 
* 1. current state
* 2.  function that lets you update it.

this is how you declare `const [ age, setAge ] = React.useState(10);`

consider this functional component, it updates the age.

```jsx
const Age = () => {
     const [ age, setAge ] = React.useState(10);
     // Onclick function to update the state
     const updateAge = ()=> {
           setAge(age => age + 1);
     }
     return (
             <div>
                <button onClick={updateAge}> {age}</button>
             </div>   
    );
}
```

## What happens here lets discuss 
* Whenever this button is clicked updateAge function is called.
* The setAge method is called and state is updated.
* The Component renders.
* useState is called for updated state value. 

This perception is very **Wrong !!**, personally, I had the same misconception. To clear this and prove this point, I will ask you a question

## Did it ever occur to you that useState hook doesn't update immediately ?
The answer to this is because they don't make any direct change to the state object, instead they create queue to optimize performance. This is why they Do not reflect immediately.

`React.useState` create queues for React core to update the state object of a React component.

So the process to update React state is `asynchronous` for performance reasons. That’s why changes don’t feel immediate.

Since `react.useState` is asynchronous now how someone will perform something after after react state is changed 

```jsx
 const Age = () => {
     const [ age, setAge ] = React.useState(10);
     // Onclick function to update the state
     const updateAge = ()=> {
           setAge(age => age + 1);
     }
     // This part will act as a callback whenever state updated 
     React.useEffect(()=>{
     if(age < 0){
        alert("Age can't be less then 0, you dumb");
      }
     },[age])
     return (
             <div>
                <button onClick={updateAge}> {age}</button>
             </div>   
    );
}
```

# Rules for using useState 
* 1. Only call Hooks at the top level.
* 2. Only call Hooks from React functions

Thanks for Bearing,
I will be writing articles explaining each hook provided by react in upcoming articles please follow to stay connected.
Whether to update old code
Tags: coding
Published: 2021-03-06 11:31:50

I was updating my portfolio recently, and wanted to make a few changes, as well as updating the projects on it. Going through my SCSS some of my choices were... interesting. Logical at the time, but looking back on it with more knowledge, I went a bit overboard with mixins.

I thought about changing it, considered the amount of code and the amount of time it would take me. I thought about my list of other projects I want do and things I want to learn. In the end I decided it wasn't so wrong it needed fixing - after all it works and didn't take long to figure out what was going on.

Something similar happened at work. I had to make some updates on the first thing I ever wrote in jQuery, a couple of years before. By this point I was a lot better at it and we'd developed a house style, after we'd all learnt jQuery at the same time.

What I'd written back then was terrible. It was mostly one, very long, function. Some of my variables had more than one name. It was just hard to read. But it worked, so no one had touched it - we had so many things on our never-ending to do list that fixing things that aren't broke didn't make the cut.

Until we needed to make some changes.

Having looked through my old code, I decided that writing it again, incorporating the required updates, would be quicker than just updating it. It wasn't like I was writing it from scratch - there was code in there I could re-use. And after I'd done it, we had code that anyone could understand, because it was much like all our other code.

So the answer to the question of whether to update old code is: it depends. Like all things in coding, there is rarely one hard and fast rule.
Como configuro meu editor e desktop para gravar código
Tags: braziliandevs, video
Published: 2021-05-03 16:03:04

---
title: Como configuro meu editor e desktop para gravar código
published: true
date: 2021-03-06 11:30:49 UTC
series: Dicas Rápidas
tags: 
  - braziliandevs
  - video
canonical_url: https://willianjusten.com.br/como-configuro-meu-editor-e-desktop-para-gravar-codigo/
---

## Introdução

Fala pessoal, eu recentemente comecei uma [série de vídeos com dicas bem rápidas](https://www.youtube.com/watch?v=1dNNL95BsJE&list=PLlAbYrWSYTiOviR_zL01FMa-kWEMDIjeO) lá no meu canal do YouTube, mas como eu também gosto de texto e também quero facilitar a busca seja pelo Google ou pelo YouTube, vou portar os vídeos para cá também. Espero que dê certo =)

## Vídeo

{% youtube Ed6ym3TthsE %} 

## Nem todo mundo tem tela 4k gigante

Quando for gravar seus vídeos com código, lembre-se que você pode estar enxergando lindo na sua tela, mas tem muita gente que acessa por celular e as vezes um celular bem fraquinho, com uma tela pequena.

Pensando nisso, quando for gravar, tente seguir alguns desses passos:

- Utilize fontes bem grandes
- Se preocupe com um bom contraste para que dê para ler sem forçar
- Remova qualquer coisa que ocupe espaço em tela e não seja útil

## Evite distrações!

Quando você está ensinando algo, o que você menos quer é que o aluno perca a atenção e fique olhando outras coisas, ao invés do principal, que é sua aula.

Existem alunos com TDAH, outros que são simplesmente curiosos, então faça o seguinte:

- Esconda sua barra de tarefas (dock)
- Esconda qualquer notificação 
- Feche janelas desnecessárias
- Evite ficar trocando muito rápido entre janelas/abas

## Conclusão

Pode ter certeza que só de fazer esses pequenos ajustes, os alunos irão conseguir prestar muito mais atenção, além de aprender muito mais com isso.

E aí, gostou da dica? Se curtiu, não deixa de se inscrever lá no [canal do YouTube](https://www.youtube.com/WillianJustenCursos/) para essa e mais outras dicas.
Como deixar a imagem da webcam redonda no OBS
Tags: braziliandevs, video
Published: 2021-05-03 16:02:21

---
title: Como deixar a imagem da webcam redonda no OBS
published: true
date: 2021-03-06 11:15:30 UTC
series: Dicas Rápidas
tags: 
  - braziliandevs
  - video
canonical_url: https://willianjusten.com.br/como-deixar-a-imagem-da-webcam-redonda-no-obs/
---

## Introdução

Fala pessoal, eu recentemente comecei uma [série de vídeos com dicas bem rápidas](https://www.youtube.com/watch?v=1dNNL95BsJE&list=PLlAbYrWSYTiOviR_zL01FMa-kWEMDIjeO) lá no meu canal do YouTube, mas como eu também gosto de texto e também quero facilitar a busca seja pelo Google ou pelo YouTube, vou portar os vídeos para cá também. Espero que dê certo =)

## Vídeo

{% youtube uE_-V8Ipb-Q %}

## Máscara!

Bom, a ideia dessas dicas rápidas vai do código a qualquer outra coisa. Um aluno me perguntou como eu fazia para ter minha imagem redonda nos meus vídeos, então porque não ensinar isso?

Bom, eu utilizo o [OBS Studio](https://obsproject.com/), que além de ser um projeto opensource, ele funciona em qualquer Sistema Operacional, o que facilitou minha vida, já que eu uso muito Mac OS e Windows.

Para fazer esse círculo, a única coisa que você precisa fazer é adicionar um filtro de máscara e utilizar uma máscara [como essa aqui](https://github.com/willianjusten/willianjusten.com.br/blob/b64731bae5466f63f9c7a7d34d607ee812ce3006/static/assets/img/mask.png), onde ela basicamente remove tudo que é preto, deixa só a bolinha redonda.

## Conclusão

E aí, gostou da dica? Se curtiu, não deixa de se inscrever lá no [canal do YouTube](https://www.youtube.com/WillianJustenCursos/) para essa e mais outras dicas.
How to Build Q&A Models in Python (Transformers)
Tags: python, machinelearning, deeplearning, tutorial
Published: 2021-03-06 10:31:29

{% youtube scJsty_DR3o %}

In this video, we'll cover how to build a question-answering model in Python using HuggingFace's Transformers.

You will need to install the transformers library with:

```
pip install transformers
```

Alongside either TensorFlow or PyTorch (to follow this video exactly you will need PyTorch). To install TensorFlow just type:

```
pip install tensorflow
OR
conda install tensorflow
```

And for PyTorch follow the instructions under 'Install PyTorch' here:
https://pytorch.org/
Error, Panic, and Recover in Golang
Tags: go, webdev, tutorial, backend
Published: 2021-03-06 10:21:43



Ok so here we'll learn about use of __error__ , besides we'll also learn about the use of __Panic__ to set up _Panic Error_ and __Recover__ to cover it.

# Using Error

__error__ is a type which has one property of _error()__ method. This method returns the details of the message error in the string and includes the type which contained the _Nil_. 

Below is a simple program sample to detect ingestion from the user, whether numeric or not.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rw3dwqrtnwdqi4q979x6.JPG)

Result, if we type number and string: 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ocmr854ipg346angyl4f.JPG)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o1iy9mts03apngyjov6l.JPG)

The statement _fmt.Scanln(&input)_ used to capture typed by the user before he hits the enter, then keeps it as a _string_ to the _input_ variable. 

Next, those variables are converted to numerical types using _strconv.Atoi()_. The function returns the 2 data, contained by number and err.


# Panic

Panic is used to display _stack trace error_ while also halting flow goroutine ( because main() is goroutine, the same drag is also applied ).

Panic displayed an error message in the console, just like _fmt.Println()_. The information of error displayed is stack trace error, so it`s very detailed on hilarious.

Next, back to your code and changed in block condition else.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sj733urjg3pfweai8x8n.JPG)

Result: 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1se39qmutupesbkq9xty.JPG)

# Recover

Recover useful to handle panic error, at the time of panic error __Recover__ take over goroutine are panic (the panic message won`t appear).

Next, We add the catch() function, this function is a statement that he will revisit the panic error message that was supposed to appear.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2gbvnq9sfog4quoyxmtn.JPG)

Result: 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nw1li17r8989r9rlh92n.JPG)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k0imltye00b28uopi4k2.JPG)

Yeah, we done.

Follow me on: 
[Github](https://github.com/egaprsty)
[Instagram](https://instagram.com/svnberr)
Upwork blaj
Published: 2021-03-06 00:21:07

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ttyrsww9y9uoc7mm5772.PNG)

Ps: I'm the one getting paid less. 

Upwork has its ups and downs. So far I am top rated on there and for the most part enjoy the platform.  I got my first nightmare client recently. The company (1 or 2  grouchy people) want to emulate Codecademy so they hired for a JavaScript curriculum developer and author to write chapters (500 words max) and coding exercises.

I wrote a sample chapter upon which they hired me. In fact they hired me two times and paid me, before all this nonsense started. 

So far I have been dealing with making editorial changes so that chapters fit into their platform seamlessly, this means giving .md, .pdf and .html files. Which is all ok! but they haven't given me access to their platform!

I have never seen their platform. Since the work is getting outsourced on Upwork (the person I am dealing with on Upwork isn't the main client), all the important documentation has been stripped off so as to conceal the identity of the main client. All I get are copy pasted comments in a very poorly formatted document. 

Moreover, now they want a chapter summary to be added and a whole bunch of other changes never mentioned previously.

All this has been extremely stressful for me as I am dealing more with the formatting to fit their platform (without ever having seen it) rather than creating content itself. 

Their feedback is rude and pretty nasty as well, considering they have asked me to format and make changes about 7-8 times now. 

Their most recent feedback, after a month of changes (19+ changes) is about how the output of the console.log statements has double quotes around the strings... WTF

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

Their exact feedback is"r people who can create a JavaScript course for beginners and need to know JavaScript. Your cover letter states that you know JavaScript well. But from the chapters and assignments written, we can conclude that you know JavaScript at a fairly low level. If we take the last chapters she submitted as an example and looked at chapter 2.1, "JavaScript Syntax." In this chapter, we will look at the tasks you have completed and the “result” expected after your code runs. You will get just text without quotes after using console.log, but all your "output" has been quoted."

I'm unsure why they expect the output of the console.log of a string data type to be without quotes? Btw I checked on codepen since I don't have access to their platform:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zzhp89496w5ieamhxl4y.PNG)

It's not possible to work with people who want the behavior of JavaScript to change according to their platform!

I'm unsure of how to deal with this because I don't want my Upwork score affected.
Flutter App + Hashnode API (App Presentation).
Tags: flutter, hashnode, techwithwsam, programming
Published: 2021-03-06 10:16:08

In this video, I will be presenting the app I built with flutter that is connected with hashnode API.

Thank you so much for watching, please do subscribe, like, comment, and share. If you have any complaints kindly comment below and if you also want us to make any adjustments let us know in the comment section below. Thanks

[Subscribe to my Youtube Channel](https://youtube.com/c/TechWithSam): https://youtube.com/c/TechWithSam

Available on play store 👨‍💻
https://play.google.com/store/apps/details?id=com.acctgen1.hashnode

Source Code - Show some ❤️ by starring the repo and do follow me 😄
https://github.com/techwithsam/flutter-app-hashnode-API

Hashnode API:
https://api.hashnode.com/

Read Articles ✍:
Hashnode - https://acctgen1.hashnode.dev/flutter-app-hashnode-api-app-presentation
Medium - https://techwithsam.medium.com/flutter-app-hashnode-api-app-presentation-c06283a49a17
Techpadi - https://techpadi.africa/2021/01/flutter-app-hashnode-api-app-presentation/

🔗 Social Media / Let's Connect 🔗
📂 GitHub: https://github.com/techwithsam
📱 Twitter: https://twitter.com/techwithsam_
📱 Facebook: https://facebook.com/techwithsam
📝 LinkedIn: https://linkedin.com/in/techwithsam
📸 Instagram: https://instagram.com/techwithsam_
⭐ WhatsApp: https://wa.me/message/JLGQNNTPG64IH1
daily.dev --- dev.to --- hackernon = @techwithsam

Join the Flutter Developer's Community 
Facebook - https://www.facebook.com/groups/flutterdevsgroup
WhatsApp - https://chat.whatsapp.com/Cns1jo7dc5dCNrg6aG44My
Telegram - https://t.me/flutterdevsgroup
Signal - https://signal.group/#CjQKILccbSu9GnMF_qVrkdCFVQ_i2gmnigPDvweCy86JGpL3EhBg39kp1rftGQgZDYXLty7t

*#flutter #hashnode #techwithsam*
webpack5 compiler.plugin
Tags: webpack, javascript
Published: 2021-03-06 10:11:59

webpack5 has removed `compiler.plugin`.
So I want emit `html-webpack-plugin` 's `html-webpack-plugin-before-html-processing`, But I can't do this:

```js
# it's wrong
compilation.plugin('html-webpack-plugin-before-html-processing', (htmlData, callback) => {
  // do something
}
```

What should I do?
Step by step procedure on how to implement custom-like javax.validator using Jersey and Jax-rs in Springboot Application
Tags: java, spring, jersey, jaxrs
Published: 2021-03-06 09:57:35

Today I'm trying to implement a validator using jaxrs, I'm only familiar with springmvc using spring-starter-validator and hibernate-validator wherein the errors are bind in the BindingResult using @restController. So as I was working around I made this solution works.

1. create a custom global mapper for constraintViolationException.

```@Component
public class ConstraintValidatorExceptionMapper implements ExceptionMapper<ConstraintViolationException>{

	@Override
	public Response toResponse(ConstraintViolationException exception) {
		final Map<String, String> errorResponse =
			    exception.getConstraintViolations()
			      .stream()
			      .collect(Collectors.toMap(o -> o.getPropertyPath().toString(), o -> o.getMessage()));
		
		return Response
		         .status(Response.Status.BAD_REQUEST)
		         .entity(errorResponse)
		         .build();
	}

}
```
2. Next create a payload request for your API.
```
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@CompareDates
public class ViewTransactionHistoryRequest {

	@JsonProperty
	private String customerId;
	@JsonProperty
	private String cardSerNo;
	@JsonProperty 
	@NotBlank(message="contact id must not be null or empty")
	private String contactId;
	@JsonProperty
	private String dateFrom;
	@JsonProperty
	private String dateTo;
	@JsonProperty 
	private Double amountFrom;
	@JsonProperty
	private Double amountTo;
	@JsonProperty
	private int page;
}
```
3. Notice the `@CompareDates` I created a sample annotation validator for validating dates.

```
@Constraint(validatedBy = DateValidator.class)
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface CompareDates {

    String message() default "dateTo should not be less than dateFrom!";
    
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};

}
```
4. Next for our endpoint we need to add `@Valid` to trigger the validation.

```
    @POST
	@Path("/view-transaction")
	@Consumes("application/json")
	@ApiOperation(value = "Get transaction history")
	public Object fiterBy(@RequestBody @Valid ViewTransactionHistoryRequest request) {
		LOGGER.info("Get account contact transaction history"); 
		return accountContactService.viewTransactionHistory(request);
	}
```

5. Then register your custom validator in your jersey configuration file.

```
@Component
public class JerseyConfig extends ResourceConfig {

  @Value("${spring.jersey.application-path}")
  private String basePath;

  public JerseyConfig() {
    register(ConstraintValidatorExceptionMapper.class);
  }
}
```
That's it! Sample response in postman should be something like this: ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1zsi3043n7zt17m48esm.PNG)

In this way we can provide to the client which fields have errors instead of just relying the 400 bad request exception response.
Primer on Bitcoin for Data Scientist — Part 1
Tags: fraud, cryptocurrency, economy, bitcoin
Published: 2021-03-06 18:22:38

---
title: Primer on Bitcoin for Data Scientist — Part 1
published: true
date: 2021-03-06 08:30:19 UTC
tags: fraud,cryptocurrency,economy,bitcoin
canonical_url: https://medium.com/coinmonks/primer-on-bitcoin-for-data-scientist-part-1-e9a90ea5b536
---

[![](https://cdn-images-1.medium.com/max/2600/0*5aAnBqHiIADKMAZT)](https://medium.com/coinmonks/primer-on-bitcoin-for-data-scientist-part-1-e9a90ea5b536?source=rss----721b17443fd5---4)

Key concepts needed for data scientist and economists to perform analysis on the Bitcoin Ledger.

[Continue reading on Coinmonks »](https://medium.com/coinmonks/primer-on-bitcoin-for-data-scientist-part-1-e9a90ea5b536?source=rss----721b17443fd5---4)
To Jamstack and not to Jamstack
Published: 2021-03-06 08:09:19

Als ich awesomeBible starten wollte, hatte ich das Ziel einen Blog zu bauen, ohne viel Geld für Hosting auszugeben.
Zu der Zeit habe ich auch mit SSGs (Static Site Generators) experimentiert.
Ich hatte Hugo und Jekyll ausprobiert.

## Jamstack 
Die Seite sollte schnell sein, Jamstack und statische Blogs sind hier das perfekte Beispiel.

Das Hosting sollte wenig bis gar nichts kosten, dieses Kriterium ist mit Jamstack Hostern wie zum Beispiel Netlify oder Github Pages gegeben.
Das einzige, was hier noch Geld kosten würde, wäre die Domain. *Ersteinmal*.

### Kommentare
Ein Feature was ich unbedingt brauchte, waren Kommentare.
Die Möglichkeit der Leser, direkt ihre Meinung zu sagen.

Ein kostenloser Anbieter ist hier Disqus. *Meiner Erfahrung nach, echt nicht gut.*
Aus mehreren Gründen:
- unerwünschte Werbung
-  [Datenschutzprobleme, Breaches](https://blog.disqus.com/security-alert-user-info-breach) 

Es gibt noch einige andere Anbieter, die teils richtig gut sind, aber ich wollte für Kommentare nichts ausgeben (bzw. ich hätte meinem Vater erklären müssen, wie das mit Jamstack läuft, und wofür ich einen Drittanbieter brauche)

### Kontaktformulare
Kontaktformulare sind eine ähnliche Sache.
Ein Anbieter, der richtig gut ist, ist [Formspree](https://formspree.io/).
Und es gibt ja noch die gute alte E-Mail. 

## Not to Jamstack
Ich nehm's vorweg, ich habe mich schlussendlich doch nicht für den Jamstack entschieden. Warum?

Ich habe neben der Überlegung des Jamstack-Weges auch immer noch nach Hostingprovidern gesucht, die zu der Zeit günstig genug waren. (Mein Budget war tight. 💸)

Ziemlich schnell habe ich dann  [Manitu](https://manitu.de/)  gefunden.
Als ich den Preis gesehen habe, bin ich erstmal vom Stuhl gefallen:

![manitu_pricing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/57ebkt8hhethem4n9aux.png)

Im Vergleich dazu 1&1 ionos (Auch der 50 GB Tarif):

![ionos_pricing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jj5hco34blwldh97dhcz.png)

Lasst euch von den 2€ nicht täuschen, im Endeffekt sind das vier Euro pro Monat.

Anmerken möchte ich auch, das manitu die 50GB Webspace über alle Dienste zieht, sprich ich habe auf awesomebible.de eine Website liegen, und alle Mails und Datenbanken werden da auch noch dazu gerechnet.

Bei ionos nur 2 GB pro E-Mail-Postfach, und nur 2 GB pro Datenbank statt 50 GB.


### Wordpress
Es ist vielleicht schon aufgefallen, dass ich für [awesomebible.de](https://awesomebible.de) WordPress benutze.

Als Theme benutze ich [Blocksy](https://creativethemes.com/blocksy/), und auf der Plugin-side-of-Things ist Jetpack und WP Super Cache.

### Kommentare
Ja lol, Kommentare gibts for free.
Ich brauche keinen Drittanbieter.

* * *

Ich glaube das war's.

Das wars, danke fürs lesen! ❤️