teleren/devto huggingface dataset:
[Conceito] - Idempotência
Published: 2022-03-31 15:03:36

> Conteúdo original [nessa thread to twitter](https://twitter.com/zanfranceschi/status/1505694913496817667).

---

Se sua mãe te mandasse tomar banho mais de uma vez, vc ia mesmo tendo acabado de tomar?

Não né?

Então pq suas aplicações não são idempotentes? Ou são?

Dá uma olhada aqui pra alguns exemplos simples.

👇
---

Processamento de arquivos:

Colocar o mesmo arquivo pra processar mais de uma vez, sem cagar tudo (duplicar coisas, por exemplo). A idempotência pode ser do arquivo como um todo ou linha a linha.

---

Banco de dados:

`UPDATE saldo SET valor = 200 WHERE valor = 100 and id = 1;`

Assim você garante que o saldo vai sair do estado que você sabia pra outro estado também conhecido. Se 'valor' mudou no meio do caminho, não vai dar ruim.

---

Processamentos de mensagens (APIs HTTP, mensagens de filas, etc.)

Isso pode ser mais chato, mas você pode exigir uma identificação de correlação (correlation id) de quem produz a mensagem ou faz a chamada.

Faz um exercício mental de como evitar um pagamento duplicado, p. ex.

---

Agora aquela parte que eu sei que você curte: decorar coisas buzinísticas pra arrasar nas festas.

Mostra isso pros amigos, ó:

```
f(x) = f(f(x))

10 * 1 = 10

34 + 0 = 34
```

Tudo isso aí são exemplos de idempotência na matemática (* 1, + 0).

Inventa uma cantada com isso, inventa. 💙

---

"Acabei de observar uma propriedade idempotente em ti, ó! bela mulher: sua beleza somada ao tempo, continua apenas sua beleza! Este – que é tão imperdoável – nada lhe afeta."

(Sério, eu não falaria isso. Sei lá, talvez bêbado.)
[Desafio] - Cache
Published: 2022-03-31 15:00:49

> Conteúdo original [nessa thread to twitter](https://twitter.com/zanfranceschi/status/1504681037099585536).

---

Dev iniciante, quer aprender a trazer seu crush pra perto de forma mais rápida? Claro, né? Vou lançar um desafio brabo pra vc.

Vamos aprender usar CACHE pra isso (não cash 💵, blz?)!

to: <dev-junior>
cc: @sseraphini, @wilcorrea
bcc: @FryRsquared ♥️

🧵👇

---

Primeiro, o que é cache?

É um armazenamento temporário pra acesso rápido. É usado pra melhorar performance de consultas. Por exemplo, quando sua api estiver uma bosta de lenta, considere usar cache pras coisas que não mudam tão rápido. (hello, "lista bosta de cidades")

---

Desafio:

Crie uma API para acessar seus crushes:

GET /crushes/{apelido}

Use o banco, resposta, e linguagem que quiser, blz? Se solta ─ mostra a pantera louca dentro de você.

![img](https://pbs.twimg.com/media/FOGwptKWUBQLrSQ?format=jpg&name=large)

---

Qual é a lógica fundamental por trás de um cache? É essa aí da imagem (claro que super simplificada). Se liga no esquema de expiração, mas não se preocupe com isso agora – só faz funcionar, fechado?

Essa é a parte que vc tem que implementar pra entender o básico, blz?

![pseudo código](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/17kpntmkv7xpvb0bj02x.png)

---

O que deve acontecer é o seguinte: você chama a primeira vez e a resposta não vai estar no cache. Aí a API vai incluir no cache essa resposta pra que, da próxima vez que vc chamar, a API retorne a resposta do cache que é mais rápido.

---

Aí tem os termos buzinísticos pra vc aprender e impressionar nas festas:

- cache miss: quando o negócio não está no cache e retorna mais devagar.

- cache hit: mizerávi tava no cache e o retorno é rápido bagarai.

---

Como sempre, obrigado para um c@ra**o se vc chegou até aqui. Puta assunto chato pra maioria das pessoas, e vc é fera. ♥️
What's Automatic Batching? React 18 feature explained
Tags: react
Published: 2022-03-31 14:57:49

---
title: What's Automatic Batching? React 18 feature explained
published: true
description: Learn how changes to automatic batching in React 18 can improve your app's performance
tags: #react
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/odcpwsa8klkmd59z1j69.png
---

If you've ever built a component in React, chances are you've used state variables. If you've ever build a kinda-complex component in React, chances are you've got multiple state variables in use.

So, what happens when we update those variables? The component re-renders, right? Make changes to a bunch of state variables and a bunch of re-rendering happens. All this rendering could have performance implications for your app.

Introducing automatic batching. Now, batching has been around for a bit in React. But, React only automatically batched state changes for you if they were called inside a hook or browser event. Like say, a click event:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/izhu7idp3rd2lzxz13vf.png)

Console Output:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/21ucjjt64f2xjt9lwphe.png)

This is automatic batching. React takes multiple state changes and groups them together so they don't happen independently -- fantastic stuff. 

So where's the improvement?

There are other places you may want to change state in your component(promises, timeouts). Let's say we have a component that fetches some data after a button click. We have two state variables, an array of users and a page counter. We want to update these inside a promise once the data is returned. In React 17, this will cause the component to re-render twice.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/odcpwsa8klkmd59z1j69.png)

Console Output React 17:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/itp92lu79jbkhxmnw2tb.png)

Console Output React 18:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3x4f65j34qux0b28zioz.png)

This is great! You can make changes to a couple state variables and React will apply them all at the same time, automatically, for you. Awesome!

If you weren't aware of how batching worked in previous versions of React, hopefully you know the limitations now. And if you've got some components out there changing state variables inside promises, might be time to upgrade :)

Thanks!
Acra. Features: Logging, audit logging and crypto-signed audit logs
Tags: cryptography, security, encryption, database
Published: 2022-03-31 14:53:33

Audit logs, or audit trails, capture evidence about any activity in your software solution. They keep records about who did what and the system's response. 

💡 From a data security perspective, **logs are sensitive data too**—they can help to see when a system was compromised, define trust scope, and reconstruct the attack (see [NIST SP 800-92] (https://csrc.nist.gov/publications/detail/sp/800-92/final)). 

Have a look at logging in Acra.

> *[Use Acra Community Edition for free] (https://github.com/cossacklabs/acra). Check out [Acra Enterprise Edition] (https://www.cossacklabs.com/acra/#pricing) tailored for solutions with high security requirements.*

## 8️⃣ Security logs and events

As software that works with sensitive data, Acra produces technical logs on its activity. Acra supports multiple logging formats compatible with popular logging solutions. In addition to logs, Acra supports exporting of metrics and traces.

💡 Acra’s security log is specifically pre-configured to be helpful to SIEM/SOC operators in building analytics and automation around security events.

Read more about Acra’s [logs and security events.] (https://docs.cossacklabs.com/acra/security-controls/security-logging-and-events/) 

![Audit logging. Acra by Cossack Labs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4upfpdmwgvtmr97nbuea.png)

### Cryptographically signed audit logs

Acra generates audit logs for data-related operations—who access what using which keys.

To ensure that the audit log is secure itself, Acra provides cryptographic protection and validation of exported logs to prevent tampering. 

💡 **Cryptographic signature protects audit logs** from unnoticed adversarial changes. 

Each log message contains a special signature that depends on log content and previous log content—thus, **creating a chain-of-signed-logs.** This logging process guarantees that logs are created one-by-one and depend on each other. 

> Acra’s cryptographically protected audit log covers access, security events, ties sessions to consumers and extends application-level audit log with strong evidence. 

🔥 As you see Acra features cover different risks and threats, while supporting each other in their mission. Combining crypto signed audit logging with ongoing automated verification shortens MTTD and MTTR on potential incidents.
Taming PgAdmin's SQL Formatting
Tags: postgres, tutorial, sql, productivity
Published: 2022-03-31 13:10:55


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

<img width="100%" style="width: 100%" src="https://media.giphy.com/media/QZt3gtVDEzxRAiU3kQ/giphy-downsized-large.gif">

The example query I'm using came from [here](https://www.w3schools.com/sql/sql_case.asp).

## Qualifiers

I really appreciate [PgAdmin](https://github.com/postgres/pgadmin4) and [everyone who's built it.](https://github.com/postgres/pgadmin4/graphs/contributors)

Who knows what I'd be doing without their hard work.

<img width="100%" style="width: 100%" src="https://media.giphy.com/media/jemtcrzKEqWEU/giphy.gif">

## More Qualifiers

I haven't read every line of their documentation. Maybe their setup instructions include this on the very first page. Maybe they've surrounded it with exclamation points and made it bold & red. The point is, if they did- I missed it. If you find this helpful- great! If not, that's ok too. Take what works and leave the rest. Or don't, I'm not the cops.

<img width="100%" style="width: 100%" src="https://media.giphy.com/media/1fhFON1kTnDVN8ZXjN/giphy.gif">

## Getting to the Point

- Click inside your Query Editor and use this keyboard shortcut to format your SQL: 
  <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>k</kbd>
  - You'll need to do this after any change to these preferences in order to see the effects.
- From the top-most "File" menu:
  - File -> Preferences
  - Query Tool -> SQL formatting
  - [Set these options for very compact SQL.](#very-compact-sql)
  - [Set these options for less compact, but easier to read SQL.](#less-compact-easier-to-read)

### Very Compact SQL

| Option                   | Value |
|--------------------------|-------|
| Re-indent aligned?       | True  |
| Re-indent?               | False |
| Spaces around operators? | False |
| Tab size                 | 2     |
| Use spaces?              | True  |

![Compact Format](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7zuylngisyspc7uyuopr.png)

### Less Compact Easier to Read

| Option                   | Value |
|--------------------------|-------|
| Re-indent aligned?       | True  |
| Re-indent?               | True  |
| Spaces around operators? | False |
| Tab size                 | 2     |
| Use spaces?              | True  |


![Less Compact Format](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e81ipi9h35ry1k986yzs.png)
Python script to list unused IP addresses in AWS VPC Subnet
Tags: aws, vpc, network
Published: 2022-03-31 14:19:23

I wrote a Python script to list unused IP addresses (IPv4) in a subnet.

I have used [Henry's post](https://blog.ilearnaws.com/2020/10/08/how-do-i-know-the-unused-ip-addresses/) as a reference, thanks.

# Mechanism
1. Get the CIDR of specified subnet by [DescribeSubnets](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_subnets)
1. Get the used private IP addresses in specified subnet by  [DescribeNetworkInterfaces](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_network_interfaces) = Used IP addresses
1. Calculate the Unused IP addresses = "CIDR IP addresses" - "Used IP addresses" - "Reserved IP Addresses"

### note
 - I used [ipaddress module](https://docs.python.org/3/library/ipaddress.html) to calculate IP addresses within the CIDR.
 - I used "PrivateIpAddresses array" instead of "PrivateIpAddress" to extract both primary and secondary addresses from the NetworkInterface response.
 - Reserved IP addresses are described in [official documentation](https://docs.aws.amazon.com/vpc/latest/userguide/configure-subnets.html#subnet-sizing)

>For example, if you create a VPC with CIDR block 10.0.0.0/24, it supports 256 IP addresses. You can break this CIDR block into two subnets, each supporting 128 IP addresses. One subnet uses CIDR block 10.0.0.0/25 (for addresses 10.0.0.0 - 10.0.0.127) and the other uses CIDR block 10.0.0.128/25 (for addresses 10.0.0.128 - 10.0.0.255).

# Python script
https://github.com/shu85t/aws_describe_unused_ips

## Requirements

- \>Python3.8
- boto3
- AWS Permissions
    - ec2:DescribeSubnets
    - ec2:DescribeNetworkInterfaces

## Usage

```
export AWS_DEFAULT_REGION={region name}
export AWS_DEFAULT_PROFILE={aws profile name}
python describe_unused_ips.py {subnet-id}
```


```
export AWS_DEFAULT_REGION=ap-northeast-1
export AWS_DEFAULT_PROFILE=my_aws_account
python describe_unused_ips.py subnet-000000000000
```

### output

```
subnet_id='subnet-000000000000' mode='normal'
cidr='10.1.0.0/24'
cidr_ips=['10.1.0.0', '10.1.0.1', '10.1.0.2', '10.1.0.3', '10.1.0.4', ...]
-----------
reserved_ips=['10.1.0.0', '10.1.0.1', '10.1.0.2', '10.1.0.3', '10.1.0.255']
-----------
used_ips=['10.1.0.39']
-----------
unused_ips=['10.1.0.4', '10.1.0.5', '10.1.0.6', ...]
-----------
cidr=10.1.0.0/24 cidr_ips=256 reserved=5 used=1 unused=250
```


This post is an English rewrite of [an post I wrote in Japanese](https://iret.media/61691).
Copy Paste Select All Made Easy by Bind it to F function Keys F1 F2 F3
Tags: keyboard, beginners, tutorial
Published: 2022-03-31 14:18:18

If your job made your pinky finger sore and hurt by copy pasting everyday, I have good news for you 😏

I want to share you about simpler way to copy paste by bind Copy (Ctrl+C) Paste (Ctrl+V) and Select All (Ctrl+A) function with F function like F1, F2 or F3

## Install Auto Hotkey

First you have to do is install [Auto Hotkey software](https://www.autohotkey.com/) (Only works with **Windows OS**), and then after installation completed, follow this steps :

Right click on your File Explorer and Create AutoHotkey Script

![New file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gafvqr4913tw5l5nh0e3.png)

New file `New AutoHotkey Script.ahk` was created -> right click on that file -> select Edit Script.

Copy paste this script to your text editor (notepad), and save it! :

```
F1::Send, ^c
F2::Send, ^v
F3::Send, ^a
```

Run the script by right click on `New AutoHotkey Script.ahk`, choose Run Script

![This indicates auto-hotkey script is running on background](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5qde5yirhpd5jbw5pb0e.png)

Try to Copy (Ctrl+C) with F1, Paste (Ctrl+V) with F2, and Select All (Ctrl+A) with F3

You can pause the copy-paste auto-hotkey script by Right Click on background minimized icon and select "Pause Script"

Done !

## Copy and Paste made easy by compiling it to .exe

If you want to compile New AutoHotkey Script.ahk  to an .exe :

Right click on New AutoHotkey Script.ahk and select "Compile Script (GUI)", and then

New windows pop-up "Script to EXE Converter" :

![Ahk2Exe for AutoHotkey](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y4j8zukkz5fl5klexqxj.png)

Choose destination (.exe file), and you can select custom custom icon by click Browse button and click > Convert < to start convert it!

![Copy Paste Enjoyer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5cul4tte8uyja5evuslh.png)

Done ! Now you can enjoy copy-pasting-select all by F1 F2 F3 😎

Thanks for reading !
Exploring the World of DApps
Tags: blockchain, dapp, web3
Published: 2022-03-31 14:08:31

> A DApp is a kind of Internet application whose backend runs on a decentralized peer-to-peer network and its source code is open source. No single node in the network has complete control over the DApp. 

Depending on the functionality of the DApp, different data structures are used to store application data. For example, the Bitcoin DApp uses the blockchain data structure.

These peers can be any computer connected to the Internet; therefore, it becomes a big challenge to detect and prevent peers from making invalid changes to the application data and sharing wrong information with others. So we need some sort of consensus between the peers regarding whether the data published by a peer is right or wrong. 

There is no central server in a DApp to coordinate the peers and decide what is right and wrong; therefore, it becomes really difficult to solve this challenge. 

There are certain protocols (specifically called consensus protocols) to tackle this challenge. Consensus protocols are designed specifically for the type of data structure the DApp uses. 

For example, Bitcoin uses the proof-of-work protocol to achieve consensus.

Every DApp needs a client for the user to use the DApp. To use a DApp, we first need a node in the network by running our own node server of the DApp and then connecting the client to the node server. 

Nodes of a DApp provide an API only and let the developer community develop various clients using the API. Some DApp developers officially provide a client. Clients of DApps should be open source and should be downloaded for use; otherwise, the whole idea of decentralization will fail.

But this architecture of a client is cumbersome to set up, especially if the user is a non-developer; therefore, clients are usually hosted and/or nodes are hosted as a service to make the process of using a DApp easier.

What are distributed applications?

Distributed applications are those applications that are spread across multiple servers instead of just one. This is necessary when application data and traffic becomes huge and application downtime is not affordable. 

In distributed applications, data is replicated among various servers to achieve high availability of data. 

Centralized applications may or may not be distributed, but decentralized applications are always distributed. 

---

_Follow me on Twitter for the upcoming updates [@dominguezdaniel](https://twitter.com/dominguezdaniel)_

---
Paracetamol.js💊| #88: Explica este código JavaScript
Tags: javascript, webdev, spanish, beginners
Published: 2022-03-31 14:06:17

## **Explica este código JavaScript**

```js
const frutas  = ["naranja","pera","zandia","banana","fresas"];
frutas.forEach(() => {
  console.count(); // ??
});
```

A. `5`
B. `SyntaxisError`
C. 
```js
default:1
default:2
default:3
default:4
default:5
```
D. Ninguna de las anteriores.

Respuesta en el primer comentario.

---
Intelligence Drought of American Corporates
Tags: america, economy, military
Published: 2022-03-31 14:01:13



Greed of corporate America to accumulate wealth for few while 80 percent of Americans fight for 20 percent of resources within American border is the beginning of greatest failures. After 2000 years of civilization, humans reached the moon, made nuclear bombs and installed puppet governments in every country or destroyed when refused; yet could not solve wealth inequality, homeless deaths and food shortages. 

Trillion dollar BlackRock bankers are the key financial advisors of elected American presidents. No wonder why majority of North Americans are mortgage hostages. American military is the tool of the corporate bankers to exercise violence on any nation in the planet. While, all corporate scams are sold as investment opportunity to end human foot print on earth.

American Empire has been occupying every part of the continent since WW2. However, America was miserable in sharing the wealth among fellow Americans and continents. The weakest part of a chain is its link. Corporate American culture prevented people from knowing the basics of evolutionary sciences and law of universe. Any species that cannot share resources, co-exist and live peacefully are doomed to face extinction. #america #intelligence #economy
[Desafio] - Explorar as Merdas da Concorrência
Published: 2022-03-31 13:58:23

> Conteúdo original [nessa thread to twitter](https://twitter.com/zanfranceschi/status/1509211177120940034).

---

\#bolhadev,

Gostaria de falar sobre maternidade e o papel do pai!

A gente sabe que mães 90% das vezes ficam com 98% da carga na criação dos filhos. E filhos demandam muito; concorrem à atenção da mãe.

O desafio hoje pra vc é praticar um pouco de empatia!

cc @sseraphini
  
🧵👇

![Concorrência](https://pbs.twimg.com/media/FPHI_SMXsAsewAv?format=jpg&name=large)

---

O desafio é simples:

Apenas explorar os problemas que a concorrência por um recurso gera. Como? Crie qq duas coisas (threads, processos, etc.) que concorram para escrever num mesmo arquivo. Vai lá, testa aí e se liga nas merdas que vão dar. Depois tenta resolver!

![Concorrência](https://pbs.twimg.com/media/FPHJrtLWQAgXpwv?format=jpg&name=large)

---

Use a linguagem que se sentir mais à vontade. Esse tipo de exercício/exploração é legal para iniciantes pq quando desenvolvemos localmente, raramente temos esse tipo de problema gerado por concorrência por causa da baixa demanda/carga. Aí, vamos descobrir as merdas em produção.

---

Se vc chegou até aqui e...

- é pai: se liga, hein? tem que colaborar (dividir a treta toda de forma igual), amigo.

- é mãe: você é muito foda! ser mãe E dev não é pra qq um, amiga! vc é uma 10x engineer!

- pra todos: dá um abraço aqui ó 🫂💕
#day 12 of solving 450 questions[36/450]
Tags: programming, python
Published: 2022-03-31 13:48:17

[Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b0rw0c01m7uu3fk8fvz1.png)
xD : Truly Pythonic


[split-a-string-in-balanced-strings](https://leetcode.com/problems/split-a-string-in-balanced-strings)
 ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rcrmj52vmi9q4xsmd9wp.png)
Wednesday Links - Edition 2021-12-22
Tags: java, jvm, kotlin, microservices
Published: 2021-12-22 08:37:48

Java: Why a Set Can Contain Duplicate Elements (3 min)🤖
http://minborgsjavapot.blogspot.com/2021/12/java-why-set-can-contain-duplicate.html

Evaluating performance of time series collections (12 min)⌛
https://blog.allegro.tech/2021/12/performance-evaluation-of-timeseries.html

Spring Boot 2.6 exposes a health group under the additional path (30 sec)❤️
https://twitter.com/piotr_minkowski/status/1468874124575580160

StampedLock as an alternative to using a ReadWriteLock (30 sec)🔒
https://twitter.com/piotr_minkowski/status/1472864669178208257

The current log4j adoption trends (1 min)📈
https://www.sonatype.com/resources/log4j-vulnerability-resource-center

The Best Spring Data JPA Logging Configuration in Spring Boot (5 min)🪵
https://thorben-janssen.com/spring-data-jpa-logging

Low Latency Microservices, A Retrospective (6 min)🚄
http://blog.vanillajava.blog/2021/12/low-latency-microservices-retrospective.html

The container throttling problem (22 min)✋
https://danluu.com/cgroup-throttling

Java 17 garbage collector options and the associated performance implications (30 min)🗑️
https://arxiv.org/pdf/2112.07880.pdf

Understanding Metaspace and Class Space GC Log Entries (7 min)🌃
https://poonamparhar.github.io/understanding-metaspace-gc-logs

SecurityManager and log4j exploit (3 min)👮
https://twitter.com/JohannesRabauer/status/1471012592495865860

Value Classes in Kotlin: Good-Bye, Type Aliases!? (6 min)💲
https://quickbirdstudios.com/blog/kotlin-value-classes

Beautify third-party API with Kotlin (3 min)🦋
https://blog.frankel.ch/beautify-third-party-api-kotlin