teleren/devto huggingface dataset:
Missing Number
Tags: leetcode, dsa, theabbie
Published: 2022-06-11 22:00:44

Given an array `nums` containing `n` distinct numbers in the range `[0, n]`, return _the only number in the range that is missing from the array._

**Example 1:**

**Input:** nums = \[3,0,1\]
**Output:** 2
**Explanation:** n = 3 since there are 3 numbers, so all numbers are in the range \[0,3\]. 2 is the missing number in the range since it does not appear in nums.

**Example 2:**

**Input:** nums = \[0,1\]
**Output:** 2
**Explanation:** n = 2 since there are 2 numbers, so all numbers are in the range \[0,2\]. 2 is the missing number in the range since it does not appear in nums.

**Example 3:**

**Input:** nums = \[9,6,4,2,3,5,7,0,1\]
**Output:** 8
**Explanation:** n = 9 since there are 9 numbers, so all numbers are in the range \[0,9\]. 8 is the missing number in the range since it does not appear in nums.

**Constraints:**

*   `n == nums.length`
*   `1 <= n <= 104`
*   `0 <= nums[i] <= n`
*   All the numbers of `nums` are **unique**.

**Follow up:** Could you implement a solution using only `O(1)` extra space complexity and `O(n)` runtime complexity?

**SOLUTION:**

    class Solution:
        def missingNumber(self, nums: List[int]) -> int:
            n = len(nums)
            currxor = 0
            allxor = n
            for i in range(n):
                currxor ^= nums[i]
                allxor ^= i
            return currxor ^ allxor
Python Exercise 9: find the key with the minimum value in a dictionary
Tags: beginners, python
Published: 2022-06-11 21:45:09

## Question
- Get the key of a minimum value from the following dictionary

``` python
sample_dict = {
  'Physics': 82,
  'Math': 65,
  'history': 75
}
```
### Hint
- use build-in min() function

## My attempt
- search and read the min(), though it is easy, but cannot figure out the answer

## Recommend solution

```python
sample_dict = {
    'Physics': 82,
    'Math': 65,
    'history': 75
}
print(min(sample_dict, key=sample_dict.get))
```

### What the min() function here does is ,
- it call the simple_dict.get() method on each key of the sample_dict
	- i.e. sample_dict.get(Physics),simple_dict.get(Math),simple_dict.get(history) will be called
	- a list of values of the sample_dict will be return
-  and then use the values for comparison 
- at last, the min() function will return corresponding key for the lowest value.
### key point
- do not add () parentheses after the key=sample_dict.get
- as the min() function will execute the method for you, you just need to pass it the method name, not to execute it. 

## My reflection
- From this exercise, i learn there is more about the min() function, and understand why sometimes () parentheses is not added after method name or function name.

## Credit
- exerices on [Pynative](https://pynative.com/python-dictionary-exercise-with-solutions/)
Estrutura do Vim/Neovim
Tags: nvim, vim, linux, programming
Published: 2022-06-11 21:44:00

# Nvim structure

Eu estou aprendendo sobre como usar as pastas nativas do vim/neovim e quero deixar registrado uma das formas de como pode ser feita até mesmo para quem está iniciando. Este é o artigo de minha referência [Learning Vims Script](https://learnvimscriptthehardway.stevelosh.com/chapters/42.html#vimftplugin)

Em minhas configurações eu utilizo as pastas ([github nvim](https://github.com/evertonlopesc/nvim));

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

## init.lua
No arquivo **init.lua** eu configuro as __Options Summary__, o que me possibilita configurar sobre syntax, spell, number, relativenumber, etc.

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

## lua/plugins.lua
No arquivo **./lua/plugins.lua** eu instalo todos os plugins que preciso usando o gerenciador Packer, para quem usar lua, eu recomendo demais.

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

## plugin
Na pasta **./plugin/** como o nome já diz eu concentro as modificações de cada plugin. Eles têm suas configurações padrões, mas dependendo do que o usuário quer ou precisa, isso pode ser alterado. Nesta pasta eu posso escolher o que quero alterar que o nvim entenderá sem eu precisar fazer uma chamada no arquivo principal (o arquivo ./init.lua). O mais importante aqui é saber que o nome do arquivo deve ser o seu correspondente.

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

## ftdetect
Na pasta **./ftdetect/** eu posso criar ou copiar uma função para ver o resultado quando abrir o neovim.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yrkx4cssoeplwiw053lq.png)
  
## indent
Na pasta **./indent/** eu configuro cada linguagem passando o nome com a extensão lua (ruby.lua). Nos arquivos eu passo a endentação, máximo de linha, etc.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n93zblfzu3jr6hx39osw.png)
 
Até o momento esse foi o meu aprendizado dentre outras pastas que ainda quero aprender e compartilhar.
The need for Kubernetes and what it does?
Tags: kubernetes, devops, softwaredevelopment, beginners
Published: 2022-06-11 21:38:49

Containers are a good way to bundle and run your applications and to ensure that there is no downtime in a production environment, you need to manage the containers that run the applications. As an example, if a container goes down, another container needs to start. The question is, would it not be easier if a system handles this behavior?

Here, [Kubernetes](bpbonline.com/search?q=Kubernetes&type=product) come to the rescue! Kubernetes provides you with a framework taking care of scaling and failover for your application, providing deployment patterns to run distributed systems resiliently. A canary deployment for your system can easily be managed by Kubernetes, for example.

With Kubernetes you are provided with:
**Service discovery and load balancing**
Using the DNS name or using its own IP address, Kubernetes can expose a container. If traffic to a container is high, Kubernetes is able to load balance and distribute the network traffic so that the deployment is stable.

**Storage Orchestration**
Kubernetes allows you to automatically mount a storage system of your choice, such as local storage and public cloud providers.

**Automated rollouts and rollbacks **
At a controlled rate, the desired state for your deployed containers can be described, and it can change the actual state to the desired state using Kubernetes. To create new containers for your deployment, remove existing containers and adopt all their resources to the new container; you can automate Kubernetes.

**Automatic bin packing**
To run containerized tasks, Kubernetes is provided with a cluster of nodes that it can use. To make the best use of your resources, Kubernetes can fit containers onto your nodes upon your telling Kubernetes how much CPU and memory (RAM) each container needs.

**Self-heal**
The restarting of containers that fail, replacement of containers, and killing of containers that do not respond to your user-defined health check is done by Kubernetes, and until they are ready to serve, it does not advertise them to clients.

**Management of secret and configuration**
Kubernetes can be used to store and manage sensitive information, such as passwords, OAuth tokens, and SSH keys. You can deploy and update secrets and application configuration without rebuilding your container images and without exposing secrets in your stack configuration.

Hope this was helpful.
Prototypeless namespaces examples in JS | 2 ed.
Tags: javascript, webdev
Published: 2022-06-11 21:33:00

Revising prototype-based inheritance in JS discovered a worth mentioned way of defining , some may say "overhead", prototypeless namespaces in global & local scopes , i.e.:

```javascript
// global namespace :
global_namespace = Object.create(null)
global_namespace['namespace_name'] = "global_namespace"; 
console.log(global_namespace) // {namespace_name: 'global_namespace'}

// local namespace :
(function (){
    // TIP # classically we could use function-scoped var instead of let, but ***"let"*** it be :
    let local_namespace = Object.create(null);
    local_namespace['namespace_name'] = "local_namespace"
    return [local_namespace, global_namespace];
}())
/** Console output :
(2) [{…}, {…}]
0: {namespace_name: 'local_namespace'}
1: {namespace_name: 'global_namespace'} # NOTE : global accessible through n-th tuple nesting
length: 2
[[Prototype]]: Array(0)
*/

local_namespace // local_namespace is not defined at <anonymous> # just as expected
``` 

---

> Since ed. 2 :

**Prototypeless also means constructorless** a.k.a singleton, **but not vice versa** i.e. constructorless can be prototype-based in JS land :

{% embed https://gist.github.com/projektorius96/086921fd379f94d54ef1287c14ce5a25 %} 



---
### <u>Related articles</u>

- [Constructorless namespaces in ES5 & ES6](https://dev.to/projektorius96/constructorless-namespaces-in-es5-es6-14pk)
Maximum Split of Positive Even Integers
Tags: leetcode, dsa, theabbie
Published: 2022-06-11 21:30:39

You are given an integer `finalSum`. Split it into a sum of a **maximum** number of **unique** positive even integers.

*   For example, given `finalSum = 12`, the following splits are **valid** (unique positive even integers summing up to `finalSum`): `(12)`, `(2 + 10)`, `(2 + 4 + 6)`, and `(4 + 8)`. Among them, `(2 + 4 + 6)` contains the maximum number of integers. Note that `finalSum` cannot be split into `(2 + 2 + 4 + 4)` as all the numbers should be unique.

Return _a list of integers that represent a valid split containing a **maximum** number of integers_. If no valid split exists for `finalSum`, return _an **empty** list_. You may return the integers in **any** order.

**Example 1:**

**Input:** finalSum = 12
**Output:** \[2,4,6\]
**Explanation:** The following are valid splits: `(12)`, `(2 + 10)`, `(2 + 4 + 6)`, and `(4 + 8)`.
(2 + 4 + 6) has the maximum number of integers, which is 3. Thus, we return \[2,4,6\].
Note that \[2,6,4\], \[6,2,4\], etc. are also accepted.

**Example 2:**

**Input:** finalSum = 7
**Output:** \[\]
**Explanation:** There are no valid splits for the given finalSum.
Thus, we return an empty array.

**Example 3:**

**Input:** finalSum = 28
**Output:** \[6,8,2,12\]
**Explanation:** The following are valid splits: `(2 + 26)`, `(6 + 8 + 2 + 12)`, and `(4 + 24)`. 
`(6 + 8 + 2 + 12)` has the maximum number of integers, which is 4. Thus, we return \[6,8,2,12\].
Note that \[10,2,4,12\], \[6,2,4,16\], etc. are also accepted.

**Constraints:**

*   `1 <= finalSum <= 1010`

**SOLUTION:**

    class Solution:
        def maximumEvenSplit(self, finalSum: int) -> List[int]:
            res = []
            if finalSum & 1:
                return res
            i = 1
            while i * (i + 1) <= finalSum:
                res.append(2 * i)
                i += 1
            if i * (i + 1) > finalSum:
                res.pop()
                res.append(finalSum - (i - 1) * (i - 2))
            return res
5+5=? Converting values to a string or number in JavaScript
Tags: programming, javascript, tutorial, beginners
Published: 2022-06-11 21:24:23

In JavaScript, data can be converted automatically or using functions. In this article, we will learn how data conversion methods work in JS and why adding 5 and 5 together can get 55 instead of 10.

Let's analyze the example:

```js
var a = 5; // number
var b = "5"; // string
var c = a + b; 
alert(c); // 55
alert(typeof(c)) // string
```

When we add `5` and `5`, we expect to see the output — `10`. However, we get `55` and see that the data type is not a number, but a string.

JavaScript automatically converted the variable `a` to a string and concatenated it with the variable `b` into a single string.

To make the data type expected by the developer, use conversion functions. Let's look at them in detail.

### Converting to a string in JavaScript

To convert a number to a string, use the function `String()`.

For example:

```js
var a = 5; // number
a = String(a); // convert the variable а to string
alert(typeof(a)); //string
```

### Converting to a number in JavaScript

To convert data to a number, use the function `Number()`. Let's try converting a string value `5` to a number.

```js
var a = "5"; // string
a = Number(a); // convert the variable а to number
alert(typeof(a)); //number
```

If you use strings in mathematical expressions, JavaScript automatically converts variables to numbers.

For example:

```js
var a = "5"; // string
var b = "5"; // string
var c = a / b; 
alert(c);// print 1, that is expected by dividing 5 on 5
alert(typeof(c)); // number
```

### Logical conversion to JavaScript

For logical conversion, use the function `Boolean()`.

Types `empty string`,`NaN`, `undefined`, `null` — is converted to false.

All other data, such as numbers and strings, is converted to true.

For example:

```js
var a = "null";
alert(Boolean(a)); // false
```

    
```js        
var a = "0";
alert(Boolean(a)); //true
```

```js        
var a = " "; // space
alert(Boolean(a)); // true
```   

```js        
var a = ""; // empty, without spaces and other characters
alert(Boolean(a)); // false
```

### Let's sum up the results

JavaScript can transform data automatically:

- numbers are converted to strings if they are used in expressions with a string;
- if the strings contain numbers and mathematical operations are performed with them, they are converted to numbers.

For conversion, use the functions:

1. `String()` - converts data to numbers.
2. `Number()` - converts data to strings.
3. `Boolean()` - converts data to boolean values true or false.
Binary Search Tree to Greater Sum Tree
Tags: leetcode, dsa, theabbie
Published: 2022-06-11 20:30:40

Given the `root` of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.

As a reminder, a _binary search tree_ is a tree that satisfies these constraints:

*   The left subtree of a node contains only nodes with keys **less than** the node's key.
*   The right subtree of a node contains only nodes with keys **greater than** the node's key.
*   Both the left and right subtrees must also be binary search trees.

**Example 1:**

![](https://assets.leetcode.com/uploads/2019/05/02/tree.png)

**Input:** root = \[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8\]
**Output:** \[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8\]

**Example 2:**

**Input:** root = \[0,null,1\]
**Output:** \[1,null,1\]

**Constraints:**

*   The number of nodes in the tree is in the range `[1, 100]`.
*   `0 <= Node.val <= 100`
*   All the values in the tree are **unique**.

**Note:** This question is the same as 538: [https://leetcode.com/problems/convert-bst-to-greater-tree/](https://leetcode.com/problems/convert-bst-to-greater-tree/)

**SOLUTION:**

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def revinorder(self, root):
            if root:
                self.revinorder(root.right)
                self.curr += root.val
                root.val = self.curr
                self.revinorder(root.left)
        
        def bstToGst(self, root: TreeNode) -> TreeNode:
            self.curr = 0
            self.revinorder(root)
            return root
Token is your plastic chip card – idiomatic approach to tokens
Tags: oauth, webdev
Published: 2022-06-11 21:18:00

You can be authorized , but not to have token e.g. you can be authorized to contain a bank account, but have no access to your deposit at ATM because you do not have your plastic chip card – hereinafter – token . But what if you do, what if bank authorized you **with a token** . Say the bank did it , you get at your nearest ATM, you insert your token into , the ATM does it job, connects your token through the chip over the network , but it asked for an authentication , yes your PIN is your way to authenticate oneself & only (hopefully only) you knows that PIN !

---

<u>In the nutshell **authorization is just a consent of the user** in three parties contract composed of</u> : 
- a user, 
- a service (_service usually provide OAuth server specification to be implemented within client_), 
- a client asking user's consent to do some tasks with service on <u>behalf of (consent of)</u> the user .

---

Stay tune for more, see you in a bit !
Day 64: break time?
Published: 2022-06-11 21:16:04

Hi!
Today I realized I didn't take my usual weekend break from coding and this week I slightly overworked and I was feeling more stressed than usual so I decided to take a break for tomorrow to get prepared and refresh for the upcoming week ahead. 
today I got started with the series about Heroku and I will be adding more posts to the series in the upcoming days also the plan is to continue working on the GraphQL project adding tests and looking into frontend integration. I plan to get back to the personal project where I will be adding typescript from now on also I plan to do the APi in Graphql too 
but that may change as time goes we will see...

signing off...
Kth Distinct String in an Array
Tags: leetcode, dsa, theabbie
Published: 2022-06-11 21:00:46

A **distinct string** is a string that is present only **once** in an array.

Given an array of strings `arr`, and an integer `k`, return _the_ `kth` _**distinct string** present in_ `arr`. If there are **fewer** than `k` distinct strings, return _an **empty string**_ `""`.

Note that the strings are considered in the **order in which they appear** in the array.

**Example 1:**

**Input:** arr = \["d","b","c","b","c","a"\], k = 2
**Output:** "a"
**Explanation:**
The only distinct strings in arr are "d" and "a".
"d" appears 1st, so it is the 1st distinct string.
"a" appears 2nd, so it is the 2nd distinct string.
Since k == 2, "a" is returned. 

**Example 2:**

**Input:** arr = \["aaa","aa","a"\], k = 1
**Output:** "aaa"
**Explanation:**
All strings in arr are distinct, so the 1st string "aaa" is returned.

**Example 3:**

**Input:** arr = \["a","b","a"\], k = 3
**Output:** ""
**Explanation:**
The only distinct string is "b". Since there are fewer than 3 distinct strings, we return an empty string "".

**Constraints:**

*   `1 <= k <= arr.length <= 1000`
*   `1 <= arr[i].length <= 5`
*   `arr[i]` consists of lowercase English letters.

**SOLUTION:**

    class Solution:
        def kthDistinct(self, arr: List[str], k: int) -> str:
            i = 0
            seen = {}
            for s in arr:
                seen[s] = seen.get(s, 0) + 1
            for s in arr:
                if seen[s] == 1:
                    i += 1
                if i == k:
                    return s
            return ""
OpenPGP proof
Published: 2022-06-11 21:00:16

This is an OpenPGP proof that connects [my OpenPGP key](https://keyoxide.org/0EDF0C53F7399B5F254EB3F94B3854817E8BF5C5) to [this dev.to account](https://dev.to/rvlobato). For details check out https://docs.keyoxide.org/advanced/openpgp-proofs/

[Verifying my OpenPGP key: openpgp4fpr:0EDF0C53F7399B5F254EB3F94B3854817E8BF5C5]
Websockets Chat Sample
Tags: javascript, beginners, webdev, tutorial
Published: 2022-06-11 20:54:47


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

Hello Devs, I've written an example on how to use WebSockets using vanilla JavaScript. It's a simple webchat, the UI is inspired on the old [XChat](http://xchat.org/screenshots/).

Here is the repo: https://github.com/ionmx/websockets-chat-sample

Take a look to `server.js` and `client.js` are self explanatory.
How to add a link to an image in Phoenix
Tags: elixir, phoenix
Published: 2022-06-11 20:49:00

**Edit (2023-05-11):** This is much simpler in Phoenix 1.7+ thanks to [Verified Routes](https://hexdocs.pm/phoenix/Phoenix.VerifiedRoutes.html):

```html
<.link navigate={~p"/post/123"}>
  <img src={~p"/images/logo.png"} alt="Logo" />
</.link>
```
---

Let's say you have an image and you want to link it to another route in the Phoenix Framework. You can use [link/2](https://hexdocs.pm/phoenix_html/Phoenix.HTML.Link.html#link/2-examples) with a code block to accomplish that:

```html
<%= link to: Routes.page_path(@conn, :index) do %>
  <img src={Routes.static_path(@conn, "/images/phoenix.png")} alt="Phoenix Framework Logo"/>
<% end %>
```

In the example above, we'll link the Phoenix logo (`phoenix.png`) to the home page.
How to demo your product to developers in a fun and relaxed way?
Tags: datadog, product, tools, opensource
Published: 2022-06-11 20:42:06

Is it possible to help developers to learn about your tool in a fun and relaxed way?

Well, there is a way. Let's take Datadog. They created "an observability service for cloud-scale applications, providing monitoring of servers, databases, tools, and services, through a SaaS-based data analytics platform. "

What do they do to help developers get some fun? Well, Datadog has created a small competition, where 1 in 10 might win quite a valuable price (up to an iPhone), simply by creating a Datadog dashboard.

If you think about it, even if 1 in 100 devs realizes that Datadog's solution is good for the business of the developer's company, Datadog will (highly likely, or at least I hope so) still be positive in terms of profit, as it only spent 10 iPhones to get this specific developer aware of the product.

How did Datadog defend against timewasters, who could enter the competition from different addresses? Well, as I understand, this specific competition was for LeadDev London 2022 visitors only. A LeadDev visitor is unlikely to start exploiting Datadog's kindness.

Also, people coming to the conference are often quite proactive, so they are exactly a group new products shall talk to.

Well done, Datadog. Although I would have made the lottery a bit more challenging, still - it was quite good.

My dashboard is below, looks fun :)

By the way, Datadog does a ton of #OpenSource too. Many kudos for that ;)

667 repositories, that is crazy.
https://github.com/DataDog


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/krxn46pc88fg7nw8xo9c.png)
Loop com SCSS para sistema de grid
Tags: css, scss, html, javascript
Published: 2022-06-11 20:30:07

## **Código em SCSS**

```
.container {
  margin: 0 auto;
  width: 99%;
  @media (min-width: 700px) {
    width: 90%;
  }
}
// Cols
$grid-columns: 12;
[class*="col-"] {
  padding: 0 15px;
}
@media (min-width: 700px) {
  @for $i from 1 through $grid-columns {
    .col-#{$i} {
      width: percentage($i / $grid-columns);
    }
  }
}
// Row
.row {
  display: flex;
  align-items: center;
  flex-direction: column;
  @media (min-width: 700px) {
    flex-direction: row;
    flex-wrap: wrap;
  }
}
```

## **Código no HTML**

```
<div class="container">
    <div class="row">
        <div class="col-12">Exemplo de grid</div>
        <div class="col-6">Exemplo de grid</div>
        <div class="col-6">Exemplo de grid</div>
        <div class="col-4">Exemplo de grid</div>
        <div class="col-4">Exemplo de grid</div>
        <div class="col-4">Exemplo de grid</div>
    </div>
</div>

```