teleren/devto huggingface dataset:
Hacks do Github - Incentive a contribuição para seus projetos open source
Tags: braziliandevs, github, beginners, programming
Published: 2022-06-17 00:58:05

![Open Source](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qbg7o0ztcbui8g54ct8r.png)

O Github é cheio de funcionalidades e o mais utilizado isso vocês já sabem e vamos continuar a série de "hacks" da plataforma que vão otimizar e melhorar sua experiência.

⚠️ Importante: Os prints que serão exibidos para exemplificar podem estar diferentes da interface do seu GitHub, por que sou muito adepto a extensões que melhoram a usabilidade e que ajudam no meu dia a dia. Partindo desse ponto peço que dê uma olhada [nesse artigo](https://dev.to/jhonywalkeer/extensoes-para-navegador-turbinando-sua-experiencia-no-github-538) antes.

Contribuir para projetos open source é algo que nos faz crescer muito como profissionais. Temos a oportunidade de aprender coisas novas e praticar o que muitas vezes não utilizamos comumente no nosso dia-a-dia. 

Cada pessoa que cria um projeto open source tem sua forma de escrever seus códigos, organizar a estrutura de arquivos, etc. Se o projeto é interessante, outras pessoas acabam ficando interessadas em contribuir. Mas a frustração vem quando descobrimos que cada um escreve seu código de uma forma: alguns usam `tabs`, outros espaços; uns preferem 4 espaços, outros preferem 2; colocar espaço entre o `if` e os `()` ou não, escrever o `else` em uma nova linha, ou na mesma linha do fechamento do `}` e assim por diante. Nenhuma destas formas estão erradas, São apenas diferentes modos de escrever o mesmo código! Mas se um mesmo código tiver várias dessas formas misturadas, o projeto vai acabar virando uma zona o famoso padrão sem padrão.

Então, normalmente colocamos no **README.md** do repositório uma área de como contribuir, citando os padrões que você utilizou no código, mostrando como criar uma nova feature, bugfix entre outras coisas. Mas no momento de empolgação, muitas vezes os devs nem chegam nessa parte do seu README.md (aposto que você mesmo já passou batido), e acabam enviando pull requests com seus próprios padrões.

## O arquivo CONTRIBUTING.md

Uma feature bem simples do Github, mas que pode ajudar a organizar melhor a colaboração nos seus projetos e que poucos conhecem, é a adição de um arquivo chamado **CONTRIBUTING.md**. Nesse arquivo você coloca tudo o que a pessoa que vai colaborar com o seu projeto precisa saber e quando criamos esse arquivo, sempre que alguém for criar uma nova issue ou enviar um pull request, olha o que vai aparecer pra ele:

![CONTRIBUTING](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b3b83cp8wa25hi3woem1.png)
 
O **guidelines for contributing** que aparece na mensagem acima, é linkado diretamente com o nosso arquivo **CONTRIBUTING.md**! Assim, sempre que alguém for colaborar, ele verá esse aviso, e ainda que não leia o **README.md**, verá que existem alguns padrões a serem seguidos para que ele possa contribuir.

Fontes onde pesquisei esse conteúdo:

- https://github.com/github/docs/blob/main/CONTRIBUTING.md
Hacks do Github - Imagens
Tags: braziliandevs, github, beginners, programming
Published: 2022-06-17 00:40:46

![Images](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i427zhkkoj796qzclw95.png)
 
O Github é cheio de funcionalidades e o mais utilizado isso vocês já sabem e vamos continuar a série de "hacks" da plataforma que vão otimizar e melhorar sua experiência.

⚠️ Importante: Os prints que serão exibidos para exemplificar podem estar diferentes da interface do seu GitHub, por que sou muito adepto a extensões que melhoram a usabilidade e que ajudam no meu dia a dia. Partindo desse ponto peço que dê uma olhada [nesse artigo](https://dev.to/jhonywalkeer/extensoes-para-navegador-turbinando-sua-experiencia-no-github-538) antes.

Nada como alegrar aquela mensagem de commit, o comentário de uma issue ou um pull request com os famosos os emojis, e para utiliza-los, basta você colocar o nome do emoji entre dois-pontos: `:emoji-name:`. Alguns exemplos se encontram nesse [site incrível](https://gitmoji.dev/) ou se preferir pode acessar [esse repo](https://github.com/ikatyang/emoji-cheat-sheet/blob/master/README.md) que apresenta diversos exemplos (assim acho que na verdade são todos) 

![Repo exemple](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iukclvrqplug14ii9iva.png)

## Imagens / GIFs

Podemos usar qualquer imagem ou gif em qualquer lugar que aceite markdown no Github: issues, pull requests, arquivos Markdown. Se quiser pegar a imagem de algum repositório, pode usar o seguinte formato:

```
![Alt Text](https://github.com/{user}/{repo}/raw/{branch}/path/to/image.gif)
```
Claro que o trecho acima é apenas um exemplo, será necessário trocar as informações acima pelas corretas da sua imagem. Algo bem interessante é a possibilidade de trocar a imagem com base no tema que está utilizando... sim é possível e falei como realizar essa façanha [neste artigo](https://dev.to/jhonywalkeer/github-selecionando-imagens-com-base-no-tema-3cc6).

## Upload de imagens

Quando abrir uma issue ou pull request, você pode adicionar uma local, de 3 formas:

1ª) Arrastando a imagem para área onde você digita o texto da issue / pull request;

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

2ª) Colando a imagem da sua área de transferência (`Ctrl + C` ou `Cmd + C`). Essa é clássica, pensou que o famoso comando usando por milhares de pessoas ficaria de fora da plataforma do Github?

3ª) A última, porém não menos importante é clicando no link apresentado e selecionando a imagem que deseja:
![Them](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pebdzds6se33egs231jx.png)

Fato é... as imagens e gifs são extremamente necessárias, pois melhoram ainda mais seu repo, issue e pull requests, mas claro que você não pode abusar delas ou então isso irá acabar atrapalhando mais do que ajudando.

Fontes onde pesquisei esse conteúdo:

- https://docs.github.com/pt/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax
Delete Characters to Make Fancy String
Tags: leetcode, dsa, theabbie
Published: 2022-06-17 00:30:41

A **fancy string** is a string where no **three** **consecutive** characters are equal.

Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**.

Return _the final string after the deletion_. It can be shown that the answer will always be **unique**.

**Example 1:**

**Input:** s = "leeetcode"
**Output:** "leetcode"
**Explanation:**
Remove an 'e' from the first group of 'e's to create "leetcode".
No three consecutive characters are equal, so return "leetcode".

**Example 2:**

**Input:** s = "aaabaaaa"
**Output:** "aabaa"
**Explanation:**
Remove an 'a' from the first group of 'a's to create "aabaaaa".
Remove two 'a's from the second group of 'a's to create "aabaa".
No three consecutive characters are equal, so return "aabaa".

**Example 3:**

**Input:** s = "aab"
**Output:** "aab"
**Explanation:** No three consecutive characters are equal, so return "aab".

**Constraints:**

*   `1 <= s.length <= 105`
*   `s` consists only of lowercase English letters.

**SOLUTION:**

    class Solution:
        def makeFancyString(self, s: str) -> str:
            n = len(s)
            i = 0
            dels = set()
            while i < n:
                ctr = 1
                while i < n - 1 and s[i] == s[i + 1]:
                    ctr += 1
                    if ctr > 2:
                        dels.add(i)
                    i += 1
                i += 1
            return "".join([s[i] for i in range(n) if i not in dels])
Day 69: sleepless again!
Published: 2022-06-17 00:17:34

Hi
Sleepless Thursday/Friday again demos are back and things are always done on the final minute :) actually this time is not the case there was no procrastination just a lot of tasks to do
tomorrow is expected to be the final day for the chores (mockups designs/ Trello/ project setup) and next week will be full work again.
I'm so tired/ sleep, I literally can't write I will be back...

Signing off...
Longest Substring with At Least K Repeating Characters
Tags: leetcode, dsa, theabbie
Published: 2022-06-17 00:00:47

Given a string `s` and an integer `k`, return _the length of the longest substring of_ `s` _such that the frequency of each character in this substring is greater than or equal to_ `k`.

**Example 1:**

**Input:** s = "aaabb", k = 3
**Output:** 3
**Explanation:** The longest substring is "aaa", as 'a' is repeated 3 times.

**Example 2:**

**Input:** s = "ababbc", k = 2
**Output:** 5
**Explanation:** The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.

**Constraints:**

*   `1 <= s.length <= 104`
*   `s` consists of only lowercase English letters.
*   `1 <= k <= 105`

**SOLUTION:**

    class Solution:
        def lstr(self, s, beg, end, k):
            if end - beg < k:
                return 0
            ctr = [0] * 26
            for i in range(beg, end):
                ctr[ord(s[i]) - ord('a')] += 1
            for i in range(beg, end):
                if ctr[ord(s[i]) - ord('a')] < k:
                    return max(self.lstr(s, beg, i, k), self.lstr(s, i + 1, end, k))
            return end - beg
            
        
        def longestSubstring(self, s: str, k: int) -> int:
            return self.lstr(s, 0, len(s), k)
Long Overdue Update - New Years Resolution - Dev Log 34
Tags: webdev, beginners, programming, startup
Published: 2022-06-16 23:58:18

I have not posted a blog for a good while now, but not without good reason. If you are keeping up with this blog you will know that recently I have been doing interviews to make a living wage, which is difficult these days. Luckily, of the companies I was interviewing with I landed the position with my first pick. Which surprised me because I felt like I flopped on the technical.

The good news is that I now have a great position with what seems to be a great company. They were transparent about the budget for the position and do not seem to mind training me on how to contribute to a team since most of my projects have been built entirely by myself. This is cool because I will learn a ton with this company and hopefully "level up" my development skills. I start on the 27th of this month and am excited about the opportunity. Until I start I have been trying to refresh some of the skills that they informed me were to be used on the job. I sent an email asking if there was anything else I could do to prepare. I got an email back that said "yeah", "enjoy your time off before you start work". This only made me feel better about going with this company.

As for the New Year's resolution, I have one more shot before the year is up. I figure it will take a couple of months to build another piece of software I am proud of and I can market. Then it will take even more time to market it effectively and make it profitable. So, essentially I got one more try to make this work. I have a few ideas but have not cemented which I will go with; honestly, with the interviews and the new job about to start, I have not been thinking too hard about it. That will all change soon though. I committed to this resolution and I am anything but a quitter. So even if I fail (which is much more likely than succeeding, lol) I will see it through and give it my best.
Data Stream as Disjoint Intervals
Tags: leetcode, dsa, theabbie
Published: 2022-06-16 23:30:36

Given a data stream input of non-negative integers `a1, a2, ..., an`, summarize the numbers seen so far as a list of disjoint intervals.

Implement the `SummaryRanges` class:

*   `SummaryRanges()` Initializes the object with an empty stream.
*   `void addNum(int val)` Adds the integer `val` to the stream.
*   `int[][] getIntervals()` Returns a summary of the integers in the stream currently as a list of disjoint intervals `[starti, endi]`.

**Example 1:**

**Input**
\["SummaryRanges", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals", "addNum", "getIntervals"\]
\[\[\], \[1\], \[\], \[3\], \[\], \[7\], \[\], \[2\], \[\], \[6\], \[\]\]
**Output**
\[null, null, \[\[1, 1\]\], null, \[\[1, 1\], \[3, 3\]\], null, \[\[1, 1\], \[3, 3\], \[7, 7\]\], null, \[\[1, 3\], \[7, 7\]\], null, \[\[1, 3\], \[6, 7\]\]\]

**Explanation**
SummaryRanges summaryRanges = new SummaryRanges();
summaryRanges.addNum(1);      // arr = \[1\]
summaryRanges.getIntervals(); // return \[\[1, 1\]\]
summaryRanges.addNum(3);      // arr = \[1, 3\]
summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\]\]
summaryRanges.addNum(7);      // arr = \[1, 3, 7\]
summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\], \[7, 7\]\]
summaryRanges.addNum(2);      // arr = \[1, 2, 3, 7\]
summaryRanges.getIntervals(); // return \[\[1, 3\], \[7, 7\]\]
summaryRanges.addNum(6);      // arr = \[1, 2, 3, 6, 7\]
summaryRanges.getIntervals(); // return \[\[1, 3\], \[6, 7\]\]

**Constraints:**

*   `0 <= val <= 104`
*   At most `3 * 104` calls will be made to `addNum` and `getIntervals`.

**Follow up:** What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?

**SOLUTION:**

    import bisect
    
    class SummaryRanges:
    
        def __init__(self):
            self.nums = []
            self.dup = set()
    
        def addNum(self, val: int) -> None:
            if val not in self.dup:
                bisect.insort(self.nums, val)
                self.dup.add(val)
    
        def getIntervals(self) -> List[List[int]]:
            nums = self.nums
            n = len(nums)
            if n == 0:
                return []
            ranges = [[nums[0]]]
            for i in range(1, n):
                if nums[i] == ranges[-1][-1] or nums[i] == ranges[-1][-1] + 1:
                    ranges[-1].append(nums[i])
                else:
                    ranges.append([nums[i]])
            return [[r[0], r[-1]] for r in ranges]
    
    
    # Your SummaryRanges object will be instantiated and called as such:
    # obj = SummaryRanges()
    # obj.addNum(val)
    # param_2 = obj.getIntervals()
Quick beginner Intro to Data Structures & Algorithm
Tags: algorithms, data, datastructure
Published: 2022-06-16 23:18:00

## Data structure:
A data structure basically refers to a format of organizing, processing, storing and retrieving data. 
We can perceive a data structure as a shelf and the mode/method you place your books is the 'data structure'.  
examples of data structures include:
_Linear Data Structures:_ 
- Arrays
- Stacks
- Linked Lists
- Queues

_non-linear data Structures:_
- Trees
- Graphs
- Map

**NB:** Some data structures such as **_Hash-tables_** can be implemented linearly or non-linearly


## Algorithm:
An algorithm refers to a set of instructions to a computer system defining how to procedurally solve a problem. 
You can take an algorithm as a recipe. for attaining the end meal/product correctly one has to get the ingredients (inputs) correctly and the steps (flow / procedure) right, otherwise the meal will taste different (invalid output / semantically incorrect )or fail all the same. 


## Determining a good algorithm
A good algorithm should have the following key features :

- **Input :** an algorithm should have 0 or more inputs
- **Output :** an algorithm needs to produce an output after computation
- **Definiteness :** each step of the algorithm should be well defined
- **Finiteness :** the algorithm needs to terminate after a given number of steps (it shouldn't run forever)
- **Correctness :** an algorithm should provide the correct output given a certain set of inputs. 

## Effectiveness of an algorithm
the  effectiveness of an algorithm can be determined by calculating it's **time and space complexities**. 
_**time complexity**_ entails calculating the amount of time it takes to run an algorithm. the rule of thumb is that an effective algorithm should take the shortest time possible given a set of inputs. 
_**Space Complexity**_ on the other hand calculates the amount of memory an algorithm requires to run given a certain set of inputs. the rule of thumb here is that an algorithm should use the minimum amount of memory space possible.
De Morgan's law and the importance of truth table
Tags: coding, python, booleanalgebra, math
Published: 2022-06-16 23:12:57

I've been studying **Python** for a few weeks and I came across an interesting video on programming fundamentals that explains De Morgan’s law. The law comes from a field of Math called **Boolean algebra**.
Although that's not something you'll face on a daily basis in programming - at least not with the theorem itself, having the understanding of these concepts can be super helpful when coding, specifically when compounding conditions. Which is something we do a lot as developers.

Basically the law says according to Wikipedia that “The negation of a disjunction is the conjunction of the negations” and “The negation of a conjunction is the disjunction of the negations”.
Which we can summarize in Python expressions like that:

`not (x or y) == not x and not y
not (x and y) == not x or not y`

**Note one:** like in math, when we multiply a set of factors between parentheses by a single factor (e.g. 2(x + 3)) we kinda distribute the factor by multiplying it by all elements inside the parentheses. This case is not different.

**Note two:** once we distribute the "not" to the operators (and/or) is the simple operation of negating it and transforming it into the opposite operator (what is "and" becomes "or" and vice versa).

And why can understanding these simple expressions be useful?
Because once you do it you also understand the importance of **truth tables**. Truth tables can be used to represent all the possible values of conditional statements and its possible results. Which means we get all the possible scenarios for if statements and check if the statement we create expresses what we need.

**Example:**
So we can go through a simple example for better understanding. Let's consider the following expression:
`x and y or z`
If we create a truth table containing all possible values for x, y and z we'll have something like this:

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

We got eight combinations where five of them evaluate to `True`.
Easy, right? And for a simple example might be obvious. But conditionals can become a more complex scenario depending on the context and it's important to create these validations to make sure the condition you've created evaluates exactly what you expect.
Laravel Migration Add Column After
Tags: laravel, eloquent
Published: 2022-06-16 22:55:57

`php artisan make:migration update_users_table --table=users`

If update file already exist
`php artisan make:migration add_phone_number_to_users_table --table=users`

```
/**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->text('phone_number')->nullable()->after('address');
        });
    }
 
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('phone_number');
        });
    }
```
June 16th, 2022: What did you learn this week?
Tags: weeklyretro, weeklylearn, discuss
Published: 2022-06-16 22:34:09

It's that time of the week again. So wonderful devs, what did you learn this week? It could be programming tips, career advice etc.

<center>

![Image of the brain](https://media.giphy.com/media/ojmB7lOn3VUU8/giphy.gif)
</center>

Feel free to comment with what you learnt and/or reference your TIL post to give it some more exposure.

{%tag todayilearned %}
Smallest String Starting From Leaf
Tags: leetcode, dsa, theabbie
Published: 2022-06-16 22:30:37

You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`.

Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_.

As a reminder, any shorter prefix of a string is **lexicographically smaller**.

*   For example, `"ab"` is lexicographically smaller than `"aba"`.

A leaf of a node is a node that has no children.

**Example 1:**

![](https://assets.leetcode.com/uploads/2019/01/30/tree1.png)

**Input:** root = \[0,1,2,3,4,3,4\]
**Output:** "dba"

**Example 2:**

![](https://assets.leetcode.com/uploads/2019/01/30/tree2.png)

**Input:** root = \[25,1,3,1,3,0,2\]
**Output:** "adz"

**Example 3:**

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

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

**Constraints:**

*   The number of nodes in the tree is in the range `[1, 8500]`.
*   `0 <= Node.val <= 25`

**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 smallestFromLeaf(self, root: Optional[TreeNode]) -> str:
            paths = [(root, [root.val] if root else [])]
            i = 0
            smallest = None
            while i < len(paths):
                curr, val = paths[i]
                if curr:
                    if not curr.left and not curr.right:
                        n = len(val)
                        currval = "".join(["abcdefghijklmnopqrstuvwxyz"[val[i]] for i in range(n - 1, -1, -1)])
                        if smallest:
                            if currval < smallest:
                                smallest = currval
                        else:
                            smallest = currval
                    if curr.left:
                        paths.append((curr.left, val + [curr.left.val]))
                    if curr.right:
                        paths.append((curr.right, val + [curr.right.val]))
                i += 1
            return smallest
WTF is CORS
Tags: javascript, webdev
Published: 2022-06-16 22:28:06

Often I find people scratching their head around the definitive meaning to CORS. 

![How many times have you seen this error in the console?](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xpaepmays0gyigif40h1.png)

> Cross-Origin Resource Sharing (CORS)

Let's try to explain CORS by first talking about what is the ooposite of CORS i.e. same-origin policy.

In same-origin policy websites are restricted to accessing resources from the **same origin** through what is known as same-origin policy

> But why do we need same origin policy in the first place? 

Let’s say you browse to a malicious website https://stealbankbalance.com while logged into https://mysweetbank.com, stealbankbalance can essentially make AUTHENTICATED requests if the same origin policy was not in place. 

> What is the need for a cross-origin policy? 
As web developers we know that working on a website we will make cross-origin requests to other domains too.

Let's talk about how do we fix the error.

CORS is controlled by Access-Control-Allow-Origin header.

CORS is a browser feature and checks for the response headers having the domain name or else rejects the request. 

If you have control over the server you are responding from, you need to add the clients domain name in the response headers

Example: Access-Control-Allow-Origin: https://www.mydomain.com

> NOTE: A server that responds Access-Control-Allow-Origin: * allows all origins which can be a large security risk.
> Only use * if your application absolutely requires it such as creating an open/public API.

If you do not have access to the server response headers then need to proxy the request from your frontend server, since cors is a browser feature it will not complain if the request is passed through a server.