teleren/devto huggingface dataset:
[Desafio] - Circuit Breaker
Published: 2022-03-31 13:42:40

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

---

Ei dev, você quer impressionar seu crush no próximo date sem ficar falando só de CRUD? Claro, né?!

Então aceite esse desafio técnico pra aprender NA PRÁTICA o que é e como funciona um CIRCUIT BREAKER!

🧵👇

![Date Sucesso com Circuit Breaker](https://pbs.twimg.com/media/FNlD2DNXsA4n6If?format=jpg&name=large)

---

Circuit Breaker é um padrão usado pra proteger um recurso (API, serviço, qualquer componente) que não esteja funcionando bem.

Uma boa referência pra entender melhor tá aqui: [https://martinfowler.com/bliki/CircuitBreaker.html](https://martinfowler.com/bliki/CircuitBreaker.html)

Vou me basear nesse post aí do Martin Fowler pro desafio.

![Circuit Breaker](https://pbs.twimg.com/media/FNkzrEkX0AQjE43?format=png&name=900x900)

---

Desafio:

Crie duas APIs que funcionem mais ou menos como esse desenho. Sério, faça do seu jeito – fica mais legal!

![Desafio](https://pbs.twimg.com/media/FNk51IQWQAs4vYH?format=png&name=large)

---

Para a API 02: Faça com que ela falhe algumas vezes consecutivamente. Por exemplo:

```
falhar = (agora.segundos  >= 0 and agora.segundos <= 15)

if (falhar)
  retorna erro;
```

Aí ela vai falhar por 15 segundos consecutivos a cada minuto.

---

Agora o bicho pega! Para a API 01: Implemente o circuit breaker. Você precisa definir um limiar (fala "threshold" pra impressionar o crush, tá?). Por exemplo "se falhar 5x consecutivas, eu abro o circuito (desarmar)". Você terá que usar um contador de erros.

---

Você também precisa implementar algo que faça com que o circuito seja fechado novamente (volte a funcionar). Você pode usar um temporizador, por exemplo.
Algo como: "ah, já tem 10 segs que esse troço tá desarmado, deixa eu armar novamente e ver se funciona".

---

É fundamental definir na API 01 como a indisponibilidade será informada.

É um erro HTTP 4XX, um 5XX, um 2XX!?

Tem que terminar o date com essa treta resolvida, tá?

---

Circuit Breaker não é só pra quando tem erro no recurso protegido, tá? É comum desarmar o circuito quando o tempo de resposta começa a ficar alto também, por exemplo.

---

A thread original foi inspirada [nesse post aqui](https://twitter.com/Estefanadie/status/1501532116617777156) da [@Estefanadie](https://twitter.com/Estefanadie)
Sharing what I learned in React js 👇
Tags: javascript, webdev, react, beginners
Published: 2022-03-31 13:40:35

So I started learning React & here's what I learned.

1) Why React?
2) JSX(Javascript & HTML)
3) Custom components
4) Declarative vs Imperative programming
5) React setup
6) Rendering Components
7) Made 2 static pages
[Link to one of my static page](https://react-74nspa.stackblitz.io/)
[Desafio] - Sistema de Votação BBB
Tags: beginners, rabbitmq, distributedsystems, desafio
Published: 2022-03-31 13:22:18

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

---

Esses dias um monte de gente comentou sobre a infra/arquitetura da Globo pra aguentar a porrada das votações do #BBB22.

Se você quiser ter uma ideia NA PRÁTICA de como isso funciona, aceite esse desafio técnico aqui. Dá uma lida aqui :)

cc @sseraphini

🧵👇

---

A ideia geral é separar o processo em dois:

1 - Receber o voto: é a parte delicada que tem que aceitar as milhares de requisições/segundo.

2 - Computar o voto: é a parte que realmente "salva o seu voto no banco de dados".

![Parte 01 - Recepção do Voto](https://pbs.twimg.com/media/FNasoqcXsAMOuCL?format=png&name=4096x4096)

---

Desafio:

1 – Crie uma API que receba um voto e publique numa fila e rapidamente retorne algo como "solicitação aceita" (vc não sabe se deu tudo certo, né?).

2 – Crie um processo em plano de fundo que leia dessa fila e salve o voto no banco de dados (ou só memória pra praticar).

---

A sugestão para essa tal de fila é usar o RabbitMQ num container docker pra ficar mais fácil.

`$ docker run -p 15672:15672 -p 5672:5672 rabbitmq:3-management`

e acesse [http://localhost:15672](http://localhost:15672) com usuário e senha `guest/guest`

---

Sobre como usar o RabbitMQ (publicar/consumir), use o tutorial 3 – "Publish/Subscribe" do tutorial oficial e escolha sua linguagem preferida.

[https://www.rabbitmq.com/getstarted.html](https://www.rabbitmq.com/getstarted.html)

![Tutorial 03 RabbitMQ - Pub/Sub](https://pbs.twimg.com/media/FNav5xyXoAAVIQe?format=png&name=small)

Claro, se vc não tiver familiaridade com filas e rabbitmq, siga os tutoriais desde o início – vale a pena.

---

Se tiver alguma dúvida, coloca aqui que a gente vai se ajudando. É um exercício muito legal que vai molhar seu pé em sistemas distribuídos.

Claro que é uma versão simplificada e que a Globo não faz exatamente assim – esse desenho é só um hello world da ideia geral.

---

Se esse assunto te interessa, recomendo fortemente que leia o livro EIP (Enterprise Integration Patterns) do Gregor Hohpe e Bobby Woolf – é um must read pra qualquer um inserido/interessado em integrações via filas. O livro é antigo, mas seus conceitos são atemporais; servem pra tecnologias modernas.

![EIP - Enterprise Integration Patterns]
(https://pbs.twimg.com/media/FNgR69cWQAAw99w?format=png&name=small)

Esse livro [tem um site](https://www.enterpriseintegrationpatterns.com/) com os padrões e explicações breves sobre cada um. É um ótimo lugar para referências rápidas.
How My shmancy overthinking self-precludes (me) from online work. Commentary on underwhelming job listings.
Published: 2022-03-31 13:17:07

---
title:How My shmancy overthinking self-precludes (me) from online work. Commentary on underwhelming job listings. 
published: true
description: 
tags: 
//cover_image: https://direct_url_to_image.jpg
---

https://medium.com/p/3c96b019a816
Adding periodic task in Elixir with OTP
Tags: elixir, programming, tutorial
Published: 2022-03-31 13:01:44

In this post, I'll show how to create a simple periodic task using Elixir OTP.

In this example, we'll create a simple server calculator. For somehow, we want to keep adding numbers periodically over time. The initial structure for this process is:
```elixir
defmodule Calculator do
  use GenServer

  @doc """
  Starts the calculator.
  """
  def start_link(opts) do
    GenServer.start_link(__MODULE__, :ok, opts)
  end

  @impl true
  def init(:ok) do
    IO.puts("starting calculator")
    {:ok, 0}
  end

  @impl true
  def handle_call({:add, num}, _from, state) do
    result = state + num
    IO.puts(result)
    {:reply, {:ok, result}, result}
  end

  def add(server, num) do
    {:ok, result} = GenServer.call(server, {:add, num})
    result
  end
end
```

Here, we can **add** a number by sending a message `{:add, num}` to the server. The client function for this purpose is `add/2`.

Then, we need to create a new process that will handle the periodic tasks.
```elixir
defmodule Periodic do
  use GenServer

  defstruct freq: nil, server: nil, callback: nil

  def start_link(opts) do
    GenServer.start_link(__MODULE__, :ok, opts)
  end

  @impl true
  def init(:ok) do
    {:ok, %{}}
  end

  @impl true
  def handle_call({:periodic, data}, _from, state) do
    Process.send_after(data.server, {:tick, data}, data.freq)

    {:reply, data, state}
  end

  @impl true
  def handle_info({:tick, data}, state) do
    data.callback.()

    Process.send_after(data.server, {:tick, data}, data.freq)

    {:noreply, state}
  end

  def retry(server, data) do
    data = Map.put(data, :server, server)
    GenServer.call(data.server, {:periodic, data})
  end
end
```
The periodic task is created using the `Process.send_after/3` function. By doing this, a message `{:tick, data}` is sent to the server after a time of `data.freq` _ms_.

The idea behind this server is that the client must provide a `callback` function that is run periodically in a frequency (in _ms_) also defined by the client. Therefore, the client must provide two inputs: `callback` and `freq`.

In order to run a periodic task, a client must call the `retry/2` function, passing the `callback` and `freq` information.

Finally, we need to define the periodic task that must be run the in `Calculator` server. Remember, we want to keep adding numbers periodically. For this, we define a new function `add_periodic` and a constant `freq` (set to be 1000 _ms_) at the `Calculator` module:
```elixir
defmodule Calculator do
  ...
  alias Periodic

  @freq 1000

  def add_periodic(server, num, freq \\ @freq) do
    {:ok, pid} = Periodic.start_link([])

    callback = fn -> add(server, num) end

    Periodic.retry(pid, %Periodic{freq: freq, callback: callback})
  end
```

The entire code can be found [HERE](https://github.com/rafaquelhodev/periodic-task) .

---
## Usage example:
First open the iex shell by:
```sh
iex -S mix
```

Then,
```elixir
import Calculator

{:ok, pid} = Calculator.start_link([])

Calculator.add_periodic(pid, 2)
```

And voila, we'll see something like this:
```sh
2
4
6
8
...
```
What do you think of my HTML5 game?
Tags: webdev, javascript, discuss, showdev
Published: 2022-03-31 12:43:49

---
title: What do you think of my HTML5 game?
published: true
description: Eight Colors is a block shifting game where the goal is to shift circular blocks to reach the target
tags: #webdev #javascript #discuss #showdev
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8v5x975it0gapf478i6v.png
---

Past two weeks, I have been working on an HTML5 puzzle game: [Eight Colors](https://eightcolors.net/). The rules of the game are pretty simple but it does get a little challenging after the first few levels. It was super-fun to design and implement this game (not so fun though hacking around quirks of iOS Safari 😅)

Let me know what you folks think. Happy to answer any question if you have.
javascript validation library - volder
Tags: hackwithdg, javascript, webdev, beginners
Published: 2022-03-31 12:39:54


### Overview of My Submission
[Note]: # (Please make sure the project links to the appropriate GitHub repository, and includes the [Apache-2 permissive license](https://www.apache.org/licenses/LICENSE-2.0)  and README.)


### Submission Category: javascript oss library

### Link to Code on GitHub https://github.com/devSupporters/volder


### Additional Resources (documentation and api):
https://volder.vercel.app/



### Introduction

this is my best project, i share it to you to see my my work.
I hope this project will help you. 

### My Deepgram Use-Case

javascript Object validation and schema builder and parsing

### Dive into Details

volder is powerful Object schema validation, it lets you describe your data using a simple and readable schema and transform a value to match the requirements, it has custom error messages, custom types and nested schemas.



### Conclusion
pls support me
Hire NodeJS Developer
Published: 2022-03-31 12:31:50

Looking For a NodeJS Developer? Then you at the right place

**[Hire Node.JS developers](https://hourlydeveloper.io/hire-dedicated-node-js-developer/)** from **HourlyDeveloper.io** to create fully responsive and highly designed web applications tailored for your business requirements.

With our dedicated hire NodeJS developer service, we provide the best app experiences without compromising usability and security.

Our Node.js developers have helped our clients build server-side apps that need scalability, the ability to multitask for executing numerous actions concurrently, significantly reduce the startup time, and even migration from a monolithic architecture to microservices.

Our dedicated, skilled, & highly trained Node.js developers are competent to build apps that cater to our client’s diverse business needs.

**So in case you are looking for a NodeJS developer, Contact us.**
About mantine-ui
Tags: react, design, webdev, beginners
Published: 2022-03-31 12:31:44

Ps: This is not a promotional post. Just sharing my opinion.

From past few weeks i am working with `mantine` in my side projects. I liked it. I had worked with `material, antd and semantic` earlier. I felt `mantine` is more useful if you don't want to spend time in developing ui components and utils methods. Unlike other `libs` *mantine* will come with 
1. State management utils
2. Dom utils
3. Browser/logging utils
4. Spotlight and
5. Rich text editor etc...

There are also some drawbacks. Major drawback is lack of community support as it is growing fast i am expecting it will reach wider audience soon. If you are working on side projects or your personal projects or if you want to give a life to your idea quickly then you can definitely try this. Trust me it won't disappoint you.

Thank you!!

Here is a link for mantine-ui https://mantine.dev/
Github: https://github.com/mantinedev/mantine
3 nices features on PHP8.0
Tags: php, webdev, productivity
Published: 2022-03-31 12:24:14

---
title: 3 nices features on PHP8.0
published: true
description: I just want to share with you really cool feature off PHP 8.0
tags:  PHP, Webdev, Productivity
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s6vl2q1txngvwggy8sx9.jpg
---

I just want to share with you really cool feature off PHP 8.0

## Named Argument

The use-case of this feature is when you want to use a function who has a lot of optional argument like this one:
```PHP
function exampleFunction(
    $param1,
    $param2 = "param2",
    $param3="param3", 
    $param4="param4")
{
    # some actions
}
```
If you need to use this function with the default parameters, except the last one, you used to do something like: 
```PHP
    exampleFunction($param1,"param2","param3","param4-v2");
```
That's long. Too long. But don't panic. With php8.0 You don't have to repeat all arguments anymore. You could just pass the required parameters, and the optional you want by naming them. That would look like this:
```PHP
    exampleFunction($param1,param4:"param4-v2");
```

## Nullsafe operator

This time, we'll talk about objects. If you want to access to the methods of an object, you should check if the object is initialized. To do that,you would probably do something like:

```PHP
if(isset($parent) && $parent!== null)
{
    $parent->method();
}
```

But now you could just write : 
```PHP
$parent?->method();
```

That's particularly useful if you need to access a value by chaining methods. For example, in an MVC, if you want to access an attribute of the returned value of a fetch method of your model in your controller, you could write: 
```PHP
$this?->model??->fetch($id)?->name;
```

## Simplification of writing class

If you write a class in PHP, you have to define your attributes and give them a security level. Formerly, that was done outside the __constructor. That means you can't assign value based on the __constructor's argument at the same time you defined that attributes.

```PHP
class Example{
  public float $attribute;
  public function __construct(
    float $attribute,
  ) {
    $this->attribute = $attribute;
  }
}
```

Since PHP 8.0, you can define your attributes directly in the constructor: 

```PHP
class Example{
  public function __construct(
    public float $attribute,
  ) {
  }
}
```

### Thank's for reading

Have a good day
Kisses

French version of this post just here :
{% link https://dev.to/jeremymonatte/3-fonctionnalites-cools-de-php-80-5ej %}
3 Fonctionnalités cools de PHP 8.0
Tags: php, webdev, productivity, french
Published: 2022-03-31 12:24:06

---
title: 3 Fonctionnalités cools de PHP 8.0
published: true
description: Je veux juste vous montrer quelques fonctionnalités cool de PHP 8.0
tags: PHP, Webdev, Productivity, French
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s6vl2q1txngvwggy8sx9.jpg
---

Je veux juste vous montrer quelques fonctionnalités cool de PHP 8.0

## Argument nommé

Vous voyez quant vous voulez utiliser une fonction avec de multiple argument optionnels ?

```PHP
function exampleFunction(
    $param1,
    $param2 = "param2",
    $param3="param3", 
    $param4="param4")
{
    # some actions
}
```

Si vous voulez appeler cette fonction en laissant les paramètres par défaut, sauf le dernier, vous deviez jusque-là tous les répéter ;

```PHP
    exampleFunction($param1,"param2","param3","param4-v2");
```

C'est bien trop long. Mais rassurez-vous, j'ai la solution pour vous. Avec Php 8.0, vous pouvez spécifier quel paramètre vous passé en donnant son nom. Cela permet de se soustraire à la contrainte de l'ordre des paramètres, et d'onc d'éviter de devoir réécrire tous les paramètres optionnels :

```PHP
    exampleFunction($param1,param4:"param4-v2");
```

## Nullsafe operateur

Cette fois, on va parler d'objets. Is vous voulez accéder à la méthode d'un objet, vous devez vérifier que l'objet en question est bien initialisé. Pour cela vous allez surement écrire quelque chose qui ressemble à :

```PHP
if(isset($parent) && $parent!= null)
{
    $parent->method();
}
```

Mais en fait, vous pourriez vous contenter d'écrire : 

```PHP
$parent?->method();
```

C'est particulièrement utile quand vous voulez accéder à une valeur en enchainant les méthodes.
Par exemple, dans un MVC, si vous voulez accéder à un attribut de l'objet retourné par une méthode fetch d'un modèle, dans votre contrôler, is suffit d'écrire ;

```PHP
$this?->model??->fetch($id)?->name;
```

## Simplification de l'écriture des classes

Si vous écrivez une classe en PHP, vous devez définir les attributs et leur niveau de confidentialité. Avant, vous deviez les définir en dehors du constructeur. Ce qui veut dire que vous ne pouviez pas définir et initialiser l'attribut en même temps avec une valeur dépendant des paramètres du constructeur.

```PHP
class Example{
  public float $attribute;
  public function __construct(
    float $attribute,
  ) {
    $this->attribute = $attribute;
  }
}
```

Avec PHP 8.0, vous pouvez définir les attributs de votre class comme étant les paramètres de votre constructeur : 

```PHP
class Example{
  public function __construct(
    public float $attribute,
  ) {
  }
}
```

### Merci de m'avoir lu

Passez une bonne journée.
Bisous.

Vous pouvez retrouvez la version anglaise de ce post juste ici :
{% link https://dev.to/jeremymonatte/3-nices-features-on-php80-4pn2 %}
New article Part 02 of Publish your first Web Application in AWS
Tags: aws, webdev, beginners, challenge
Published: 2022-03-31 12:23:32

Hi,
I just uploaded a Part 02 of Publish your first Web Application in AWS

Article Link: https://aravindkumarvemula.medium.com/publish-your-first-web-application-in-aws-f13d889b3543


If there is any mistake in my article pls.. comment down. So, that i can improve myself.
![gif](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4qbq3ch9y7sudh33h5a1.png)
Why z-index doesn't work all the time 🤯 ?
Tags: css, html
Published: 2022-03-31 12:23:00

_If you have struggled with `z-index` you are not alone._ 

Look at the code snippet below:

{% codepen https://codepen.io/hunzaboy/pen/jOYGNqX default-tab=css,result %}

The circle `div` has a `z-index` of `99999` but it is still showing under the header which has a `z-index` of `2`. why is this happening? Should `circle` be on top as it has the highest `z-index`? 

`z-index` doesn't simply place element on top of lower `z-index` or no `z-index` items. There is a logic to it. If you understand this logic, then next time when you add a z-index property, you will know where to put it and why.

Lets dig into it:

`z-index` is based on the stacking context of the HTML elements. Stacking context simply means how the elements are stacked in the HTML tree whether the elements are in same stacking context or not e.g in the code snippet above the stacking context of `header` and `main` is different than `circle`. We can create new stacking context as soon as we add z-index properties to the elements. 

> 
There are also many other ways of creating stacking context. If you want to dig deeper you can read about it [here](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context)

if we add z-index to header element then it will create a new stacking context comparing `main` and `header`. The circle z-index will have no effect as it has its own stacking context inside the `main` element's context. But if we create a z-index on the circle `div` then the context will be between it siblings ( if any ). 

In order to solve the problem, all we need to do is remove the z-index from the main which will remove the new stacking context. Now it will simply be `header` and then `circle` in terms of stacking context. 

{% codepen https://codepen.io/hunzaboy/pen/LYezEYa default-tab=css,result %}


Related Links:
[Stacking Context](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context)
[Stacking without z-index](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/Stacking_without_z-index)


I hope you enjoyed this article. Follow for more css tips and tricks. 

{% embed https://dev.to/hunzaboy %}
Azure Runbook Asyncio Error
Tags: azure, python, devops
Published: 2022-03-31 12:13:10

We recently had a project that required the use of Azure runbook. I found my Python code was not working as expected. It works locally but not in Azure runbook.

After debugging, I found the issue is related to Asyncio. Even if I ran the following sample code, I still got an error.

```python
import asyncio
loop = asyncio.get_event_loop()
```

The error message:

```python
**Traceback (most recent call last):  File "C:\Temp\vls2h0kl.4gk\04a596c9-5b8c-4a2d-828b-2bb185668277", line 53, in <module>    loop = asyncio.ProactorEventLoop()  File "C:\WPy64-3800\python-3.8.0.amd64\lib\asyncio\windows_events.py", line 310, in __init__    super().__init__(proactor)  File "C:\WPy64-3800\python-3.8.0.amd64\lib\asyncio\proactor_events.py", line 629, in __init__    self._make_self_pipe()  File "C:\WPy64-3800\python-3.8.0.amd64\lib\asyncio\proactor_events.py", line 760, in _make_self_pipe    self._ssock, self._csock = socket.socketpair()  File "C:\WPy64-3800\python-3.8.0.amd64\lib\socket.py", line 597, in socketpair    lsock.listen()OSError: [WinError 10050] A socket operation encountered a dead networkException ignored in: <function BaseEventLoop.__del__ at 0x0000000784F8C310>Traceback (most recent call last):  File "C:\WPy64-3800\python-3.8.0.amd64\lib\asyncio\base_events.py", line 648, in __del__  File "C:\WPy64-3800\python-3.8.0.amd64\lib\asyncio\proactor_events.py", line 684, in close  File "C:\WPy64-3800\python-3.8.0.amd64\lib\asyncio\proactor_events.py", line 752, in _close_self_pipeAttributeError: 'ProactorEventLoop' object has no attribute '_ssock'**
```

I raised a ticket to Azure Team. I was told it is because Azure runbook only allows on 31 kernel calls and this module seems to be using something out of this range hence getting this error. 

Their product team is working on enabling full stack of OS calls from Azure runbook but it will be delivered for Python by end of 2022. 

So, the temporary workaround is customer can use hybrid runbook worker as of now. 

[Azure Automation Hybrid Runbook Worker overview](https://docs.microsoft.com/en-us/azure/automation/automation-hybrid-runbook-worker)