teleren/devto huggingface dataset:
Pods - Kubernetes (BR)
Tags: kubernetes, devops
Published: 2023-07-10 22:23:55

---
title: Pods - Kubernetes (BR)
published: true
description: Entendendo sobre pods 
tags: #kubernetes #devops
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-07-10 12:50 +0000
---
O que são os pods no kubernetes ?

> É um contexto compartilhado dividindo o mesmo isolamento tanto lógico quanto físico, também é semelhante a um conjunto de containers com volumes e namespaces compartilhados.

Exemplo de criação de um **Pod** no kubernetes:

`Utilizando a última versão do nginx` 

```Yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  containers:
  - name: nginx
    image: nginx:latest
    ports:
    - containerPort: 80
```

---

Para rodar o exemplo acima basta utilizar o seguinte comando no mesmo diretório do arquivo:
```Bash
kubectl apply -f {nome_do_seu_arquivo}
```

---

Esse caso de criação de **Pod** é somente usado para estudos dentro do kubernetes, geralmente você não cria os **Pods** diretamente, você pode usar outros recursos como **Deployment**/[**ReplicasSet**](https://dev.to/daniellcas/replicaset-kubernetes-55gn) ou para casos de rastrear o estado use **StatefulSet**.


## Como se trabalhar com **Pods**.


Nós temos duas principais maneiras de se trabalhar com **Pods**:

> ### 1/1 - Um **Pod** para um **container**
  a maneira mais comum de se trabalhar.
  Exemplo: **Pod** é como um wrapper(embrulho) no container, Kubernetes gerencia **Pods** em vez de gerenciar os containers diretamente. 


---

> ### 1/x - Um **Pod** para múltiplos **containers**
Para casos onde você tem uma aplicação fortemente acoplada, que precisa compartilhar seus recursos. Exemplo: Um container atende os dados de um **Volume** enquanto outro container é utilizado para atualizar esses dados.

---

**Pods** são na maioria das vezes projetados para serem efêmeros e descartáveis. Os **Pods** permanecerão ativos até que:
- Termine a execução.
- O **Pod** seja excluído.
- O **Pod** seja removido por falta de recursos
- Ou caso o **node** falhe.

> Um **Pod** não é um processo, mas um ambiente para execução de containers, um **Pod** persiste até ser excluído por motivos listados acima. Por isso reiniciar um container é **diferente** de reiniciar um **Pod**.

---

## Conclusão
Para concluir pense assim, um **Pod** é um ambiente para execução de containers, olhe a imagem a seguir.
![Exemplo Pods](https://kubebyexample.com/sites/default/files/2021-06/pod-to-pod.svg_.png)

Basicamente, containers do mesmo **Pod** podem se comunicar através do localhost por compartilhar os mesmo recursos de rede, agora para acessar outros **Pods** precisamos do seus IP's e portas dos containers.

> Esse foi minha explicação sobre os **Pods**. Fique atento para os posts explicando os recursos como Deployment, [ReplicasSet](https://dev.to/daniellcas/replicaset-kubernetes-55gn) e StatefulSet.

---

> ## Referências:
>> [Kubernetes.io] (https://kubernetes.io/docs/concepts/workloads/pods/)
Constructor Parameter Properties in TypeScript
Tags: typescript, oop, constructor, cleancode
Published: 2023-07-10 22:06:34

Let's learn how to use the OOP, **Constructor Parameter Properties** in your TypeScript class (known as **TypeScript Constructor Shorthand** or **Constructor Property Promotion** in PHP 8). 
Using the Parameter Properties in your TypeScript projects will make your code cleaner, more readable and more concise.

{% youtube 7kS2h0gYhNo %}
Two-Tier vs. Three-Tier Architecture and Normalization in Database Design
Published: 2023-07-10 22:05:19

## Two-Tier Architecture:

A two-tier architecture, also known as a client-server architecture, consists of two main layers: a client layer and a server layer. The client layer is responsible for interacting with the user and presenting data to them, while the server layer is responsible for processing requests and managing the application's data and business logic.

In a two-tier architecture, the client layer communicates directly with the server layer. This can result in a simpler and more efficient system, but can also make it more difficult to scale and maintain as the application grows.

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

## Three-Tier Architecture:

A three-tier architecture, also known as a multi-tier architecture, consists of three main layers: a presentation layer, an application layer, and a data layer. The presentation layer is responsible for interacting with the user and presenting data to them, the application layer is responsible for processing requests and managing the application's business logic, and the data layer is responsible for managing the application's data.

In a three-tier architecture, each layer communicates with the layer directly above or below it. This can make the system more complex, but also more flexible and easier to maintain and scale as the application grows.

## Normalization:

Normalization is a technique used in database design to eliminate redundancy and improve data integrity. It involves organizing data into tables and ensuring that each table has a unique primary key and that all other attributes in the table depend on that key. This helps to ensure that data is consistent and accurate and reduces the risk of errors or inconsistencies in the data.

Normalization is typically achieved through a series of steps or "normal forms," with each normal form building on the previous one. The most commonly used normal forms are first normal form (1NF), second normal form (2NF), and third normal form (3NF), although there are higher levels of normalization as well.

In summary, two-tier and three-tier architectures are types of system architectures used in software development, with three-tier architectures consisting of three main layers and two-tier architectures consisting of two. Normalization is a technique used in database design for eliminating redundancy and improving data integrity, accomplished through organizing data into tables and ensuring each table has a unique primary key and all other attributes depend on that key._
Parallel algorithms series. Part 1: A little bit about sequential algorithms.
Tags: algorithms
Published: 2023-07-10 21:53:52

#Introduction

If you are reading this post, I am pretty sure that you have already implemented some form of a sequential model. It can be a an algorithm for sorting, a function that returns a fibonacci sequence or something as simple as Adding all the items in a list.
Most of the algorithms that you have come across till now utilizes a single core.
And probably that is not what you are interested in. But to get into parallel algorithms, first look at the machine models that we use for sequential computations.

##RAM Model

Lets talk about adding two numbers, each having d = 5 digits
e.g 23568 + 98321
What will be the cost of adding these two numbers ? 
For this particular use case , you might have guessed "constant time" and you are probably right. 
We have two numbers that can be easily contained in a 64 bit integer and the addition might happen in 1 or 2 operation cycles. 

But thing changes if the number itself is too big, and does not fit into the 64bit . In that case, there will be a split, some carryovers and then we will get the result. One can say it depends upon the size the number of digits we are adding. 
The analysis of the code will get complex if we start considering these cases as well, hence we need a standard to follow to make things easier for ourselves. Generally, we use RAM Model, a standard for sequential computation. 

**What is RAM Model then ?**
RAM Model or Random Access Model is a machine model that has the following attributes
*Unlimited memory. Any size of input can be accomodated easily in memory cells.
* Fixed amount of registers. Registers are temporary storage sitting next to the processors. They cannot be unlimited, or else why do we even need memory ? Save everything in the registers. Hence, we have limited amount of storage to hold data at a time. 
* memory cells and registers can save w size integers (or numbers from 0 to 2^w-1). Here w = logn. The size of integer will increase logarithmically wrt to the number. 

In the RAM Model, the total cost is the number of instructions executed. These instructions are 
1. Load into registers from memory, and vice versa. 
2. Arithematic Operations (+,-, %, *, AND , OR , XOR etc)
3. conditional/unconditional jumps (Those if cases have some cost as well!)

So the next time, when you see a program with n iterations and multiple operations and if-else conditions, you can tell your friends that they aren't wrong, but they aren't right either.  Here is an example below 

```
    var i,n, sum int
    fmt.Print("Enter the value of n: ")
    fmt.Scan(&n)
    for i <= n {
        sum += i
        i++
    }
    fmt.Println(sum)
```
The time complexity here is O(n). But really, its 2n instructions. (add operation on sum and add operation on i). 


I am trying to keep the articles short and sweet. In the Next One, we will dive into PRAM Model.
ABEND dump #5
Tags: news
Published: 2023-07-10 21:50:18

Hi there, it’s been a while!

After some vacationing, the ABEND dump is back. The ABEND dump is the issue where I share the most interesting content I’ve been reading, listening to, and watching lately.

Want to check the previous issue? Read it here: [ABEND dump #4](https://dev.to/bitmaybewise/abend-dump-4-1c16)

Here it is:

## [Unit or integration tests?](https://effectivesoftwaretesting.substack.com/p/unit-or-integration-tests?r=915pz)

TLDR:

> It doesn't matter!

> As long as tests run fast, are easy to be written, and give good feedback, we are fine.

Mauricio Aniche is a reference when it comes to software testing. Go check his book and newsletter and thank me later ;-)

## [Writing a Faster Jsonnet Compiler](https://www.databricks.com/blog/2018/10/12/writing-a-faster-jsonnet-compiler.html)

Compilers are the kind of software that amazes me. It’s beautiful to see a human-readable text format being translated into a machine-executable binary. Lately, my work has been writing, reading, and maintaining a lot of [jsonnet](https://jsonnet.org/). While performance so far has not been a problem for me, it was an issue for some clever developers working at Databricks, to the point of rewriting the compiler in Scala aiming to improve the compilation time for their usage, giving birth to [sjsonnet](https://github.com/databricks/sjsonnet).

## [jsonnet: habemus std.flattenDeepArray](https://github.com/google/jsonnet/pull/1082)

If you have custom jsonnet code to flatten a deep array, soon the standard library will have the std.flattenDeepArray function to do it. 

---

In my last post, I wrote for new programmers still in doubt about choosing a programming language:

{% embed https://dev.to/bitmaybewise/dont-obsess-about-choosing-a-first-programming-language-be-water-1jb7 %}

And in the [last issue of GitHub’s Branching Out newsletter](https://www.linkedin.com/pulse/deciding-adopt-tool-can-hard-enough-what-seems-break-paradigms/), Damien Katz (creator of Apache CouchDB) gave an answer when asked about a piece of advice he would give to new developers, and his answer resonates with what I think (and is related to the post above):

> Don’t be dogmatic and get too married to any style, paradigm, or methodology. They all work, and they all don't work. And success really has a lot to do with the team and the team cohesiveness and how well they've bought into whatever it is. The culture and psychological safety in the team—those are the kinds of things that actually make projects succeed or fail, more so than any methodology or technology.

---

If you liked this post, consider subscribing to my newsletter [Bit Maybe Wise](http://bitmaybewise.com/).

You can also follow me on [Twitter](https://twitter.com/bitmaybewise) and [Mastodon](https://mastodon.online/@bitmaybewise).
Simple JavaScript Challenges with solutions
Tags: javascript, tutorial, beginners
Published: 2023-07-10 21:50:08

As a programmer, or maybe a JavaScript developer, there are some simple challenges you face maybe in an interview or maybe with your own project. In this article, I will be taking you through two simple JavaScript challenges and their solutions.

## String length and Retrieving the Number.
In a website, you might see a section that is been given to the user to write some text and there is always a limit to the number of characters they are supposed to write, so in this example we will be seeing a simple JavaScript code that can calculate the number of characters entered by the user and the number of characters remaining. 
**Example:**

```
// prompt the user to enter a tweet
var tweet = prompt("Compose your tweet");

// count the length of character entered
var tweetCount = tweet.lenght;

// display output
alert("You have written " + tweetCount + "Characters ,and you have " + (140 - tweetCount) + " Characters remaining")
```

## Slice and extracting Parts of a string.
Let's consider another example where you will prompt the user to enter their name, and the code we are to write is supposed to convert the first letter of their name and display with a greeting message like hello `name`.

```
// prompt the user to enter name
var name = prompt("What is your name");

// extract first letter of name
var firstChar = name.slice(0,1);
//convert first letter to uppercase
var upperCaseFirstChar = firstChar.toUpperCase();
//extract remaing letters of name
var restOfChar = name.slice(1,name.length);
//convert remaining letters of name to lowercase in case the user write a name like this noEl
restOfChar = restOfChar.toLowerCase();
//join the first letter and other letters
var combined  = upperCaseFirstChar + restOfChar;
//output
alert("Hello " + combined);
```
Okay, that's the two I have got for now but there are other challenges like `fizzBuzz` and so many others and you can try to figure out other methods in which you can achieve the same goal. Thanks for you time. Adios
Hello World
Tags: hello, python, internetspeedtest
Published: 2023-07-10 21:49:58

I made a simple Speed test Checker in Python!!!
<u>**Background:**</u> OOKLA Speedtest website: https://speedtest.net, made a Python module to check the ping and internet speed. 
Using this module, I am checking the internet ping, download and upload speed.
s.results.share():: Makes an HTTP POST request to speedtest.net with your results and returns a link to an image of your results
Let's begin
<u>**Step1:  **</u>
Install speedtest-cli package 

`pip install speedtest-cli`

Step 2:

`import speedtest as st
def InternetSpeedTester():
    # Set Best Server
    server = st.Speedtest()
    server.get_best_server()

    # Test Download Speed
    down = server.download()
    down = down / 1000000
    print(f"Download Speed: {down} Mb/s")

    # Test Upload Speed
    up = server.upload()
    up = up / 1000000
    print(f"Upload Speed: {up} Mb/s")

    # Test Ping
    ping = server.results.ping
    print(f"Ping Speed: {ping}")
    server.results.share()

if __name__ == '__main__':
    InternetSpeedTester()
`
MEDO da reunião DIÁRIA
Published: 2023-07-10 21:44:54

{% embed https://youtu.be/JPJnPm5u04o %}

Muita gente morre de medo de falar em público, mas trabalhando em equipe essa é uma realidade diária. Nesse vídeo eu trago alguns padrões que, se aplicados corretamente, ajudam você a encarar e até a superar esse medo transformando aquilo que era um “martírio” em oportunidade de crescimento.
A chave para evoluir na carreira de programador
Published: 2023-07-10 21:43:47

{% embed https://youtu.be/ogKVJb-qgfk %}

Os jovens que chegam hoje ao mercado de trabalho tem uma dificuldade muito grande de se comunicar e trabalhar em equipe e eu não sou diferente de você nisso. A única diferença, realmente, é que tive que aprender na marra aquilo que você pode ter agora mastigado.

Se quiser saber mais, basta deixar um comentário e entrar em contato comigo. Estamos sempre contratando jovens programadores que demonstram interesse em evoluir e você pode acabar fazendo parte da minha equipe.
CookieDB: Meu projeto de banco de dados noSQL open-source 🍪
Tags: database, python, nosql, opensource
Published: 2023-07-10 21:24:56

O CookieDB é um banco de dados noSQL que usa o modelo de documento para armazenar os dados. Desenvolvido totalmente em Python, o CookieDB foi projetado para ser seguro, moderno, leve e fácil de usar. Feito para todos os tipos de projetos, especialmente para aqueles que não necessitam de um banco de dados complexo e complicado de configurar.

Você pode **contribuir para o avanço do projeto** enviando sugestões, adicionando funcionalidades ou corrigindo erros por meio de PRs, reportando falhas de segurança ou bugs no [repositório do CookieDB](https://github.com/jaedsonpys/cookiedb) no Github, qualquer tipo de contribuição é bem-vinda!

Além disso, você pode usar as [Issues do GitHub](https://github.com/jaedsonpys/cookiedb/issues) para tirar suas dúvidas ou reportar falhas.

- [Documentação do CookieDB](https://jaedsonpys.github.io/cookiedb/)
- [Código-fonte do CookieDB](https://github.com/jaedsonpys/cookiedb)
- [Projeto no PyPI](https://pypi.org/project/cookiedb)

Outros projetos relacionados ao CookieDB também estão disponíveis, como um servidor e um cliente Python para acesso ao servidor ([CookieDB Server](https://github.com/jaedsonpys/cookiedb-server) e [CookieDB Client](https://github.com/jaedsonpys/cookiedb-client) respectivamente).

## 🔒 Segurança

Para manter a segurança, todos os dados armazenados em um banco de dados CookieDB são criptografados utilizando o **algoritmo AES-256**, além de conter um código *otimizado* para melhorar a velocidade de criptografia.

## 🚀 Velocidade

Desde a primeira versão, venho buscando novas formas de fazer com que o armazenamento de dados seja rápido. A última versão do CookieDB será a mais rápida e otimizada, com novos métodos de armazenamento que são testados várias vezes para comprovar o desempenho.

## ✌️ Fácil de usar

O CookieDB possui documentação **clara e atualizada** sobre cada método que você precisar utilizar, seja para criar, obter, atualizar ou deletar dados no banco. Você pode adicionar praticamente qualquer tipo de dado ao banco de dados, como listas, dicionários, strings, números, valores booleanos, sets e tuplas. Veja um [simples exemplo de uso](https://github.com/jaedsonpys/cookiedb/blob/master/examples/example.py) do CookieDB:

```python
from cookiedb import CookieDB

database = CookieDB('MyDatabase', key='secret')
database.add('languages/python', {'creator': 'Guido', 'ext': '.py'})

python_creator = database.get('languages/python/creator')
python_ext = database.get('languages/python/ext')

print(f'Python creator: {python_creator}')
print(f'Python extension: {python_ext}')
```

Todos os dados são armazenados em um arquivo `.cookiedb`, onde você pode realizar cópias facilmente para manter seus dados seguros.
How to create pull request on GitHub using bash shell and gh command line tool for coding review
Tags: github, shell, git, codereview
Published: 2023-07-10 21:24:41

In this post I show how to create a pull request on [GitHub](https://github.com/) to ask a coding review to another coder (e.g. a supervisor, a team leader or just another coder). To do that, I'll use the **bash shell** and the **GitHub CLI**.

## What do you need?

- [Bash shell](https://www.gnu.org/software/bash/)
- [GitHub CLI](https://github.com/cli/cli)

## The script
You can download the script [here](https://gist.github.com/animusna/35527304f74d500620095c40cfaff6b3).

```
#!/bin/bash

coder="animusna" # THE CODER NAME WILL RECEIVE THE CODING REVIEW REQUEST
branch="develop" # THE ORIGIN BRANCH ON WHICH YOU'LL MAKE THE PULL REQUEST 

if [ $# -eq 0 ]
  then
    echo "***No arguments supplied"
    exit 1
fi

if [ -z "$1" ]
  then
    echo "***Pull request title not supplied"
    exit 1
fi


if [ -z "$2" ]
  then
    echo "***Pull request message not supplied"
    exit 1
fi

currentBranch=`git rev-parse --abbrev-ref HEAD`

echo -e "\nChecking login status Github cli"

gh auth status

echo -e "\nPushing you branch to origin..."

git push origin $currentBranch

echo -e "\nCreating pull request for branch \"$branch\" asking to \"$coder\" to review...\n"
gh pr create --title "$1" --body "$2" -r $coder -B $branch


echo -e "\n\nbye ;)"
```

The script requires to be configured:
- The GitHub account name of the coder will receive the coding review request.
- The branch on which you'll open the pull request.

These parameters are hard coded, but you can change the script to receive these values via shell parameters.

## Before to run the script

You'll need to install the GitHub command line tool following [these instructions](https://github.com/cli/cli#installation).

After the setup, you must authenticate typing the following command:

```
animus@devto:~$gh auth login
```
Follow the instructions and complete the authentication process.

![gh authetnication wizard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t2pbvmt46obb7l61qukp.png)

## How to run the script

To run the script, you must provide the following parameters:
- **Pull request title**
- **Pull request message**

```
animus@devto:~$./ps.sh 'smart feature' 'check this out...'
```

Running the script, you'll see something like shown in the image below.

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

After the execution of the script, the reviewer will receive a notification about the request just created.


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


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




## Conclusions

The script described in this post is very simple, and it shows just one of many potential that the **GitHub CLI** could offer in a team to collaborate and to automate operations on GitHub repositories.
RxJS Operators: bufferCount
Tags: rxjs, webdev, javascript, typescript
Published: 2023-07-10 21:08:09

RxJS is a JavaScript library that enables the creation of asynchronous and event-based programs. The main type is the `Observable` and a suite of functions and operators are provided to make it easier to work with the data coming through. This series will detail those operators (and a few stand-alone functions) and provide examples of their use.

In this post, we’re going to cover the `bufferCount` operator.

## What does it do?

The `bufferCount` operator is used to batch a certain number of values together. When we add `bufferCount` to our pipeline we pass it a number that indicates the number of values to batch. Once enough values have been received, `bufferCount` will combine all values into an array and send them through the pipeline. 

## Example

```tsx
import { bufferCount, interval } from 'rxjs';

interval(1000)
    .pipe(bufferCount(10))
    .subscribe(x => {
        console.log(x);
    });
```

We’re using `interval` to provide us with incrementing numbers every second. When we add `bufferCount` we’re telling it to wait for 10 values, so every time it receives 10 from `interval` an array will be sent down the pipeline. Running this will print:

```bash
[
  0, 1, 2, 3, 4,
  5, 6, 7, 8, 9
]
[
  10, 11, 12, 13, 14,
  15, 16, 17, 18, 19
]
```

If the original observable completes the buffer will send whatever values it has collected through the pipeline immediately. 

The source code for this example is available on GitHub:
{% embed https://github.com/drownedintech/rxjs-operators %}
class
Published: 2023-07-10 20:48:38

## What is a Class in Programming?

A class is a blueprint or template in programming that defines the properties and behavior of a certain type of object. It specifies the attributes and methods that objects of that class will have, and instances of a class can be created through a process called instantiation. Classes allow for modular, reusable code and promote more natural, intuitive software design.

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