teleren/devto huggingface dataset:
Buenas prácticas
Tags: argentina, desarrollador, estudiante
Published: 2021-01-25 22:28:03

##Las buenas prácticas de la programación.

En este artículo hablaremos de lo que son las buenas prácticas a la hora de trabajar en equipos con otros desarrolladores, la intención de este post **NO** es hablar sobre los principios SOLID sino, que hablaremos sobre hábitos que todo programador debe conocer para poder estandarizar y entenderse con su equipo al momento de escribir código.

Partamos de una serie de ítems que nos ayudará a organizarnos un poco.

* **Legibilidad**

Como todo desarrollador sabe, el código se escribe una vez y se lee muchas veces, es por eso que la legibilidad es muy importante a la hora de trabajar.
Sangrías, espacios, intention-revealing names, etc. Estos son algunos conceptos que hace que el código no parezca un espagueti y sea mas fácil de leer/entender a para los demás.

* **Comentarios**

Un código no necesita comentarios para que otro lo entienda si éste esta escrito correctamente y sigue los pasos del item anterior por lo que es correcto decir que escribí de manera que _el código hable solo..._

* **No sorprender** 

En el mundo de la programación la simpleza es lo mejor que puede haber a la hora de escribir software por lo que evitar sorprender con algoritmos complejos para problemas simples es lo ideal.

* **Idiomas** 

Este tema es complicado pero a la hora de escribir funciones, nombres y clases evitemos utilizar mezclas de lenguajes ya que genera malentendidos en la lectura del código. En lo personal me gusta nombrar a los getters y setters en español ya que facilita muchísimo a la hora de leer.

* **Índices** 

Los índices tradicionalmente y globalmente son i,j,k por lo que evitemos cambiarlos si es que vamos a compartir nuestro trabajo a otras personas.

* **Variables booleanas** 

A la hora de utilizar variables booleanas es convenientes pensarlas en positivo, por ejemplo _encontrado_, _terminado_,etc.


_Estos son las buenas prácticas que yo aprendí. 
Me encantaria saber cuales son las que ustedes aprendieron y saben asique sus comentarios y opiniones son bienvenidas._

Saludos!
Day 25 - Check If All 1's Are at Least Length K Places Away
Tags: leetcode, python, challenge
Published: 2021-01-25 22:27:46

## The Problem

> Given an array `nums` of 0s and 1s and an integer `k`, return `True` if all 1's are at least `k` places away from each other, otherwise return `False`.

__Example 1:__

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/v854ig0b4p8csqulay2s.png)

```
Input: nums = [1,0,0,0,1,0,0,1], k = 2
Output: true
Explanation: Each of the 1s are at least 2 places away from each other.
```

__Example 2:__

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/jr141b7img1v4m8wjfnc.png)

```
Input: nums = [1,0,0,1,0,1], k = 2
Output: false
Explanation: The second 1 and third 1 are only one apart from each other.
```

__Example 3:__

```
Input: nums = [1,1,1,1,1], k = 0
Output: true
```

__Example 4:__

```
Input: nums = [0,1,0,1], k = 1
Output: true
```

__Constraints:__

* `1 <= nums.length <= 10^5`
* `0 <= k <= nums.length`
* `nums[i]` is `0` or `1`


## Tests

```python 
import pytest
from .Day25_CheckIfAll1sAreAtLeastLengthKPlacesAway import Solution

s = Solution()


@pytest.mark.parametrize(
    "nums,k,expected",
    [
        ([1,0,0,0,1,0,0,1], 2, True),
        ([1,0,0,1,0,1], 2, False),
        ([1,1,1,1,1], 0, True),
        ([0,1,0,1], 1, True)
    ],
)
def test_k_length_apart(nums, k, expected):
    assert s.kLengthApart(nums, k) == expected
```

## Solution

```python
from typing import List


class Solution:
    def kLengthApart(self, nums: List[int], k: int) -> bool:
        current_dist = k
        for n in nums:
            if n == 1:
                if current_dist < k:
                    return False
                current_dist = 0
            else:
                current_dist += 1

        return True
```

## Analysis

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/gey99w8slcnel5yp3qk0.png)

## Commentary

That one was easy. A little too easy....

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mgwsbu4sazihriqgp59v.gif)
Organizando o código com funções
Tags: powershell, beginners, tutorial
Published: 2021-01-25 22:23:33

Podem existir cenários onde precisemos utilizar em nosso código varias vezes um mesmo trecho, para esses cenários a melhor solução é a criação de uma função, mas o que é uma? 

Não vamos aqui nos prender tanto a teoria ou a explicar especificamente todos os termos, uma vez que a ideia é ser um conteúdo mais simples e direto, permitindo utilizar a linguagem com um entendimento razoável, por isso vou recomendar que sempre expanda o conhecimento que obter aqui com pesquisas focadas nos temas conceituais, que lhe gerarem duvida ou que achar interessante. 

Seguindo, vou definir aqui como função, uma conjunto de código que podemos reutilizar e que vão fazer uma transformação especifica de dados, sem necessariamente nos dar um retorno formal. 

Ok, isso pode ter ficado um pouco complicado, mas vou tentar explicar de uma outra forma. 
Para exemplificar o que é uma função e como fazer ela, vamos escrever uma para validar se uma pasta existe ou não, seguindo um pouco a ideia do que vimos nos tutoriais anteriores. 

Mas qual transformação vai ser feita?
Basicamente, indicaremos nela o caminho que queremos validar e com essa informação, ela fara não só a analise da existência, como vai fazer a criação caso seja necessário, ou seja, vamos criar uma função para representar o processo que desenvolvemos até aqui.

Qual a diferença entre fazer a função ou copiar o código? 
Com a função, não precisaremos copiar todo aquele código para fazer esse processo, sendo preciso apenas utilizar a palavra chave dela para utilizarmos. Uma outra vantagem, é que qualquer atualização feita nela, vai refletir nos locais onde nos referimos a ela, facilitando a manutenção.

Vamos começar a escreve-la,
Para isso, precisamos entender sua estrutura, basicamente, temos um novo conceito chamado parâmetros. Nos já utilizamos ele mas não criamos algo que utilize ele. 
Acredito que seja mais fácil mostrar com um código explicado, então traduzindo tudo isso em código, teremos: 

{% gist https://gist.github.com/IGDEXE/d6a138926e0f25073797d01ba9c96c6f %}

Basicamente o que fizemos foi aproveitar nossa estrutura de validação e criação de pastas antigas e adiciona-la dentro do padrão de declaração de uma função. Essa é a estrutura, definimos o nome depois da palavra chave **function** e depois definimos os parâmetros que queremos que ela utilize. Fora isso, uma função lembra muito o que já fizemos até aqui. 

Certo, criamos a função, mas como utilizamos ela? 
É bem simples, e na verdade, já utilizamos varias funções até aqui, e até escrevemos ela com outras funções, ou seja, podemos criar um "ciclo" de reaproveitamento de código, deixando nossa solução muito modular. 

Nosso novo script de criação de pastas, incluindo nossa função, agora fica assim: 

{% gist https://gist.github.com/IGDEXE/6c045c616e85984b4211feda585a0e03 %}

Como o exemplo é algo bem simples, pode parecer que nosso código ficou gigante sem motivo, mas para projetos maiores isso vai nos ajudar a ter um código mais limpo, de manutenção fácil e pratico de ser utilizado.
Nativefier
Tags: cooltools, tech, macos
Published: 2021-02-09 22:52:44

---
title: Nativefier
published: true
date: '2021-01-25 22:19:41 UTC'
tags:
  - cooltools
  - tech
  - macos
canonical_url: 'https://www.sheldonhull.com/microblog/nativefier/'
---

Ran across this app, and thought was kinda cool. I've had some issues with Chrome apps showing up correctly in certain macOS windows managers to switch context quickly.

Using this tool, you can generate a standalone electron app bundle to run a webpage in as it's own dedicated window.

It's cross-platform.

For a site like Azure DevOps, you can run:

```powershell
$MYORG = 'foo'
$MYPROJECT = 'bar'
$BOARDNAME = 'bored'
nativefier https://dev.azure.com/$MYORG/$MYPROJECT/_boards/board/t/$BOARDNAME/Backlog%20items/?fullScreen=true ~/$BOARDNAME
```

If redirects for permissions occur due to external links opening, you might have to open the application bundle and edit the url mapping. [GitHub Issue #706](https://github.com/jiahaog/nativefier/issues/706)

```text
/Users/$(whoami)/$BOARDNAME/APP-darwin-x64/$BOARDNAME.app/Contents/Resources/app/nativefier.json
```

Ensure your external urls match the redirect paths that you need such as below. I included the standard oauth redirect locations that Google, Azure DevOps, and Microsoft uses. Add your own such as github to this to have those links open inside the app and not in a new window that fails to recieve the postback.

```json
"internalUrls": "(._?contacts\.google\.com._?|._?dev.azure.com_?|._?microsoft.com_?|._?login.microsoftonline.com_?|._?azure.com_?|._?vssps.visualstudio.com._?)",
```
Sailboat
Tags: showdev, python, news, linux
Published: 2021-01-25 22:16:37

Hello! Today I am happy to announce that I am releasing Sailboat (https://github.com/cole-wilson/sailboat) for the first time! Sailboat is a Python developer’s best friend. It’s a Python build tool that can do anything you need it to! It supports a countless number of plugins — you can even make your own. Sailboat is made for anyone, whether you are a beginner on your very first project, or a senior software engineer with years of experience.

Let’s say that that you have created a basic game, Guess My Number, and you want to send it to all of your friends. There are a lot of different ways you can do this, but using Sailboat is the easiest. All you have to do is type three commands: `sail quickstart`, `sail build`, and `sail release`, and you can have a Homebrew file, a pip installable package, and a PyInstaller desktop app in less than 5 minutes. So easy!

You can check it out at https://github.com/cole-wilson/sailboat and https://sailboat.colewilson.xyz

Please let me know what what you think, and if you find any bugs let me know, or submit an issue.

![Sailboat Screenshot](https://dev-to-uploads.s3.amazonaws.com/i/0u1sllxma5bqcff554t1.PNG)
Express with Typescript starter explained (fast)
Tags: typescript, node, javascript, npm
Published: 2021-01-25 22:14:44

If you are reading this, I think you should know Typescript & Express, so let's go through this, and build something from scratch !

## Before start

Let's start by checking if node is currently installed

```
node -v
```

Install typescript (globally) if not installed 

```
npm install -g typescript
```

## Initialization

So let's begin ! First of all, use `npm init` in order to create package.json !

So basically what are we needing ? We need to install `express`, install and configure `typescript` packages, and install `@types` package linked to the previous packages. We also need to install `ts-node` in order to build typescript file in nodejs

So let's do this

```
npm i express
```

```
npm i -D typescript ts-node @types/node @types/express
```

Init config typescript

```
tsc --init
```

Create two folders:

- `src/` (will contains all ts files)

- `dist/` (will contains all builded files (js files))

## Start

In order to start our project, we will use `nodemon` in order to watch any changes in `*.ts` files and re-build it automatically.

```
npm i -D nodemon
```

Create command to execute code

```
  "scripts": {
    "dev": "nodemon src/app.ts"
  },
```

Create `app.ts` file in `src/` like bellow :

```typescript
import express, { Application, Request, Response } from 'express'

const app: Application = express()

const port: number = 3001

app.get('/toto', (req: Request, res: Response) => {
    res.send('Hello toto')
})

app.listen(port, function () {
    console.log(`App is listening on port ${port} !`)
})
```

## Run server

```
npm run dev
```

Yeah it's working ! You can now create your beautiful project in Express supporting Typescript !

Link to repo -> https://github.com/Code-Oz/basic-express-typescript

---

I hope you like this reading!

🎁 You can get my new book `Underrated skills in javascript, make the difference` for FREE if you follow me on [Twitter](https://twitter.com/code__oz) and MP me 😁

Or get it [HERE](https://codeoz.gumroad.com/l/RXLYp)

🎁 [MY NEWSLETTER](https://www.getrevue.co/profile/code__oz)

☕️ You can [SUPPORT MY WORKS](https://www.buymeacoffee.com/CodeoZ) 🙏

🏃‍♂️ You can follow me on 👇

🕊 Twitter : [https://twitter.com/code__oz](https://twitter.com/code__oz)

👨‍💻 Github: https://github.com/Code-Oz

And you can mark 🔖 this article!
Destructuring Deeply Nested Objects and Arrays with ES6
Tags: javascript
Published: 2021-01-25 22:12:04

## Intro
I was working on a project that was receiving data from an external API that I wanted to use for an app. The data coming from the API was exactly what I needed but the way that it was being returned was difficult to work with. It was returning an object of objects of arrays of objects and the data that I needed was buried down several levels. I knew that it was possible to destructure an object or an array at one level but I was unaware that it could be used to dig down deep into a nested structure. Thanks to Paige Niedringhaus for her article [*Using ES6 To Destructure Deeply Nested Objects in JavaScript & Avoid Undefined Errors that Break Your Code*]
(https://itnext.io/using-es6-to-destructure-nested-objects-in-javascript-avoid-undefined-errors-that-break-your-code-612ae67913e9) that showed me how this can be done. 

## Issue: My Data

```javascript
nlmSearchResult: {
    term: ["Sinusitis"]
    file: ["viv_j2Dfzc"]
    server: ["pvlb7srch16"]
    count: ["11"]
    retstart: ["0"]
    retmax: ["1"]  
    list: [
        {
        document: [
            {
            content: []//Array of data that I want,
            },
        ],
        },
    ];
}
```

This is the structure of the data that was being returned from my API call. The data that I needed was located inside of an array that was buried down deep as the value for `content` key. There was all this extra information that I didn't really need. At first I thought I could just chain together a bunch of object calls to get what I wanted but I think that chaining tends to get a little messy so I looked into nested destructuring and found that it was possible and super easy. I just had to set it up like a normal destructuring but continue further down like so. 

```javascript
const {
  nlmSearchResult: {
    list: [
      {
        document: [{ content }],
      },
    ],
  },
} = resultFromApiCall
```

This code was destructuring the `resultFromApiCall` and giving me the data I wanted, now assigned to the constant `content`.

```javascript
console.log(content) //Data that I needed to display in my app
```

Now I could take that data and manipulate it however I wanted and not have to carry around all of that extraneous info that was in the api response. Super Cool. 

Thank you for reading. If you have any questions about this article or anything JavaScript or TypeScript related, please shoot me a message. I always love to talk tech.
NMT -> No More TLAS -> No More Three-Letter-Acronyms
Tags: opinion, salty, saywhatyoumean
Published: 2021-01-25 22:11:42

---
title: NMT -> No More TLAS -> No More Three-Letter-Acronyms
published: true
description: A less than one minute post to remind us all that TLAs in correspondence can exclude people from the conversation.
tags: opinion, salty, saywhatyoumean
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/6o95otiiykahvq4e6fc5.png
---

This is just my humble opinion...

Please do not use three-letter acronyms.
The LOE to write out "level-of-effort" is minimal.

When messages become full of three-letter acronyms it starts to exclude people who are not "in the know" and if anything, the inquisitive will ask "what does XYZ mean?" which in my humble opinion defeats the purpose.

Others may not feel they're welcomed to ask the question as they may appear not knowledgable or able to "sit at the table".

Let's make the table welcoming in all the ways we can.

I may be a tad salty but I share my perspective from a person who will ask what every three-letter acronym means.

Forever.
Working with Date and Time in Python
Tags: python, tutorial, beginners, datetime
Published: 2021-01-25 21:58:47

---
title: "Working with Date and Time in Python"
published: true
description: "In python we have the datetime module that provides various date and time manipulation objects, such as date, time, datetime, timedelta, tzinfo and timezone. In this post we will talk about datetime and timedelta."
tags: python,tutorial,beginners,datetime
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/n7ubl3uunndb8hgrkot5.png
---

Say dev, how are you?

In the last week, I took a job where I needed to calculate days and hours with Python. With some Google searches I came up with several results, some really good and others like "WTF .-.".

I soon thought to myself, and I said, "I will research how Python works with hours and develop its own algorithm for that", with some research in the [python documentation](https://docs.python.org/3/) I found that it is easier than I imagined to be working with date and time.

## Introduction
Primeiro criamos nosso arquivo date-hour.py
In python we have the datetime module that provides various date and time manipulation objects, such as `date`, `time`, `datetime`, `timedelta`, `tzinfo` and `timezone`. In this post we will talk about `datetime` and `timedelta`.

### Datetime

Combining all the date and time attributes, it returns a tuple like the one below:
```
datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
```

For example, returning a current date:
```
2021-01-24 17:04:18.329567
```

Its default format is:
- **Year**: 4 Digits
- **Month**: 2 Digits
- **Day**: 2 Digits
- **Hour**: 2 Digits
- **Minute**: 2 Digits
- **Seconds**:  2 Digits + 6 Digits (to differentiate microseconds) 

### Timedelta
Represents the duration or the difference between two dates or times. It can be represented as follows:
```
timedelta (days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
```
For example, returning a difference of 2 hours:
```
2:00:00
```

## Putting hands in the dough

After presenting the objects we are going to work on, we will start to do some tests. I will comment line by line on what is happening, and in the end, post the result of everything.

First we create our [date-hour.py](https://gist.github.com/zerossB/2f816d6eaf53cdd79611acfa72716ee4) file:

{% gist https://gist.github.com/zerossB/2f816d6eaf53cdd79611acfa72716ee4 %}

- **Line 1**: I import datetime and timedelta from the datetime module
- **Line 3**: I take the current datetime, saving it in the variable now
- **Line 5**: Black the tuple generated on the screen
- **Line 7**: I generated a 2-hour timedelta and saved it in the td variable
- **Line 10**: I entered the current time
- **Line 11**: I printed the sum of the current time and the timedelta
- **Line 12**: I subtracted the current time with the timedelta

Output of the above commands:
```
Datetime tuple: 2021-01-24 17:39:28.446383
Timedelta: 2:00:00

Current Time 2021-01-24 17:39:28.446383
+2 hours 2021-01-24 19:39:28.446383
-2 hours 2021-01-24 15:39:28.446383
```

Until the next post <3
The Correct Way of Adding Tailwind to Your Next.js App
Tags: nextjs, react, css, webdev
Published: 2021-01-25 21:56:54

> I list steps to add Tailwind to a Next.js app and highlight what some are doing wrong.

### TL;DR
The correct way of adding Tailwind to a Next.js app is by following the steps mentioned in the [Tailwind Docs](https://tailwindcss.com/docs/guides/nextjs).

### Steps
Navigate into the Next.js app directory and follow these steps:

1. **Install Tailwind dependencies**:
`npm install tailwindcss@latest postcss@latest autoprefixer@latest`

2. **Generate `tailwind.config.js` and `postcss.config.js`**:
`npx tailwindcss init -p`

3. **Configure Tailwind to remove unused styles from production builds**:

```javascript
// ./tailwind.config.js 
module.exports = {
  purge: ['./pages/**/*.jsx'],
  ...
} 
```

- Besides `./pages`, ensure all paths of components that use Tailwind are also added; e.g. `purge: ['./pages/**/*.jsx', './components/**/*.jsx'],`

- Ensure the extension is appropriate; e.g. your file extension may be different if you’re writing TypeScript: `purge: ['./pages/**/*.tsx', './components/**/*.tsx'],`

4. **Include Tailwind styles along with your own in the global stylesheet**:

```css
// ./styles/global.css
@tailwind base;
@tailwind components;
// Add Tailwind's @apply styles here
@tailwind utilities;
// Add other global styles below
html {
  ...
}
body {
  ...
}
```

5. **Add the global stylesheet to all your pages via `./pages/_app.jsx`**:

```jsx
// ./pages/_app.jsx
import '../styles/global.css';

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp;
```

### What Some Are Doing Wrong
Besides referring to an older, outdated article, you could be doing the following mistakes:

1. **Saving Tailwind dependencies as `devDependency`**:
Tailwind is a collection of classes that go into your production app. They are not used for developing the app, but are a part of one. In an ideal scenario, you would want to skip installing `devDependency` in a CI/CD process to save bandwidth and time. Your app won’t build then.

2. **Adding additional dependencies**:
Tailwind doesn’t need any other dependency like `postcss-preset-env`, `@fullhuman/postcss-purgecss` or others.

3. **Adding a CSS reset along with Tailwind**:
Tailwind already uses [Preflight](https://tailwindcss.com/docs/preflight) as the base, which resets browser styles to ensure consistent look across all browsers. However, if you prefer to use your own reset, you should first turn Preflight off:

```javascript
// tailwind.config.js
module.exports = {
  corePlugins: {
    preflight: false,
  },
  ...
}
```
---
Cheers!
Migração NodeJS por .Net Core (Considerações)
Tags: dotnet, node, learn
Published: 2021-01-25 21:44:47

Bom, em dezembro de 2020 fiz uma mudança em minha vida mudança qual inclui uma nova stack de trabalho. Eu sempre vi linguagens de programação como ferramentas onde todas seguem uma ideia parecida e você tem que aprender somente a sintaxe, ao sair de um ambiente 100% Javascript a primeira boa impressão é a organização que o framework .net traz para o c# e segundo a produtividade que é alcançada com o VisualStudio. Não faz muito tempo que estou nessa stack logo não tenho muito o que comentar. Mais para o meio do ano pretendo fazer outro post mais estruturado e contendo mais considerações.

Nesse meio tempo para quem está disposto a seguir com .net core eu vou deixar alguns cursos que estou fazendo e já acabei:

* [C# Basics for Beginners: Learn C# Fundamentals by Coding](https://www.udemy.com/course/csharp-tutorial-for-beginners/)
* [C# Intermediate: Classes, Interfaces and OOP](https://www.udemy.com/course/csharp-intermediate-classes-interfaces-and-oop/)
* [C# Advanced Topics: Prepare for Technical Interviews](https://www.udemy.com/course/csharp-advanced/)
* Cursos da Alura:
  * [C# e orientação a objetos](https://cursos.alura.com.br/formacao-c-sharp-orientacao-objetos)
  * [ASP.NET Core parte 1: Um e-Commerce com MVC e EF Core](https://cursos.alura.com.br/course/webapp-com-aspnet-core-2)
  * [ASP.NET Core REST APIs](https://cursos.alura.com.br/formacao-dotnet)