teleren/devto huggingface dataset:
Coroutines, key Concepts
Tags: kotlin, android, coroutines
Published: 2020-12-18 00:10:13

Basically, a coroutine is a Thread... a lightweight one, you can run a bunch of coroutines without even notice. They help us to manages our async code and their syntax is simple and easy to understand. 

```kotlin
//Basic Example
fun main () {
	GlobalScope.launch {
		delay(2000)
		println("Hello world")
	}
	Thread.sleep(3000)
}
```

**What is Scope?**
   Scope create, run, and stop Coroutines, also provides lifecycle methods.

* **GlobalScope.launch{}**: the scope of these coroutines will be the entire application, so when the app stops the coroutine will stop.
* **runBlocking**: it will run on the main thread. Runs a new coroutine and blocks the current thread interruptible until its completion.
* **CoroutineScope**: it will create a new scope and will run until all the inner coroutines finish.

Examples:

```kotlin
fun main () {
  runBlocking {
     launch {
	 println("runBlocking ")
     }
  }
	
  GlobalScope.launch {
     println("runBlocking")
  }
	
   coroutineScope {
      launch {
	println("runBlocking")
      }
  }
}
```

**What is Context?**

 It's a set of variables and data associated with the coroutines.
* **Dispatcher**: Specify the thread in which our coroutine will run
* **Job**: Handle the coroutine lifecycle.

**What is a Suspending function?**

 It's a function that can be run in a Coroutine. So the only difference is that we need to add the 'suspended' key-word at the beginning.

```kotlin
suspend fun myFunction(){
	println("Hello, I'm suspended")
}
```

**What is a Job?**

A job is the result of  the '.launch()', so we can store this in a variable and use it. ( That way we can manipulate the lyfecycle of the corotutine).

```kotlin
   val job = GlobalScope.launch {
	  // Coroutine work...
   }
```
	
**What is a Dispatcher?**

Manage in which thread the coroutine will run. We can specify (if we want) in which thread our coroutine will run and switch between threads with the keyword: **withContext**

Common dispatchers:

```kotlin
launch(Dispatchers.Main) { // Main -- will work with main thread (UI)
    println("Main")
}
launch(Dispatchers.IO) { // IO -- will work with IO thread, network or file work
    println("IO")
}
launch(Dispatchers.Unconfined) { // not confined -- will work with main thread
    println("Unconfined")
}
launch(Dispatchers.Default) { // will get dispatched to DefaultDispatcher 
    println("Default")
}
```

withContext :
	Let us change the context of our coroutine.

```kotlin
fun main() { 
   runBlocking {
	launch(Dispatchers.Default){
		println(“Default context”)
		withContext(Dispatchers.IO){		
		   println(“IO context”)
 		}	
                println(“Default context”)
	}	
  }
}
```

**What is a Deferred?** 

A future result of a coroutine, for example, the result for an API call. So we need to wait for this value and we are going to use async.

```kotlin
fun main (){
  runBlocking {
     val myDefferred = async { suspendfun() }
  }
}

suspend fun suspendfun(): Int {
	delay(50000)
	return 10
}
```
Adding Babel presets and plugins in Next.js
Tags: nextjs, babel, blogvent
Published: 2020-12-19 06:48:56

---
title: Adding Babel presets and plugins in Next.js
published: true
date: 2020-12-18 00:08:00 UTC
tags: nextjs, babel, blogvent
canonical_url: https://www.netlify.com/blog/2020/12/18/adding-babel-presets-and-plugins-in-next.js/
---

Welcome back, for Blogvent day 18!

Next.js comes with [several Babel presets built in](https://github.com/vercel/next.js/blob/canary/packages/next/build/babel/preset.ts), and chances are, it will cover most of what you’d like to use in your projects. But, it’s nice and simple to add custom presets and plugins, if you so desire!

First, make a file at the root of your project called `.babelrc`. You will want to include the `next/babel` preset to keep the ones that are built in to the framework:

```json
{
  "presets": ["next/babel"],
  "plugins": []
}
```

If you want to add more presets than the `next/babel` one, you can add them to that array in an object, for example:

```json
{
  "presets": [
    ["next/babel", {
      "preset-env": {
        "loose": true,
        "modules": false
      },
    }]
  ],
  "plugins": []
}
```

If you’d like to add plugins, it’s the same thing! If you don’t want to custom configure them or anything, you can name them in the file:

```json
{
  "presets": ["next/babel"],
  "plugins": ["@babel/plugin-proposal-logical-assignment-operators"]
}
```

So if I had my `.babelrc` like this, I would be able to use [this plugin](https://babeljs.io/docs/en/babel-plugin-proposal-logical-assignment-operators) without any extra steps. Neat!

## I want to use this!

Of course you do! Here’s a starter application to try this out yourself:

[![Deploy to Netlify](https://www.netlify.com/img/deploy/button.svg)](https://app.netlify.com/start/deploy?repository=https://github.com/cassidoo/next-netlify-starter&utm_source=blog&utm_medium=nextstarterbabel-cs&utm_campaign=devex)

(Clicking this button will deploy a Next.js starter project to Netlify, and clone it to your chosen Git provider)

Also, if you’d like to explore your plugin options, [check out this page](https://babeljs.io/docs/en/plugins) on the Babel Plugins website!
What Travis CI New Billing Means for OSS
Tags: opensource, github, ci
Published: 2020-12-17 23:36:24

---
title: What Travis CI New Billing Means for OSS
published: true
date: 2020-12-17 23:33:28 UTC
tags: OpenSource,GitHub,ci
canonical_url: https://h.shadowtime2000.com/what-travis-ci-new-billing-means-for-oss
---

# What Travis CI New Billing Means for OSS

Recently, when I was checking my Travis CI build statuses, I found out that they are transferring their services to `travis-ci.com` from `travis-ci.org`. I looked more into it, and it turns out there is a plan to change the billing system.

## What are they doing?

For OSS repositories, you are given a 10K credit allotment which is around 1k Linux build minutes. Once that is up, they are hoping that you will consider on of their payed plans. But, for OSS projects, you can also submit a request to get more credits for your project.

## But why?

They are doing this because they have seen increased abuse of the platform which increases the queue time for users that use it well.
Javascript: Cleaner Objects with ES6's Object Property Shorthand
Tags: javascript, es6, tips, webdev
Published: 2020-12-17 22:58:05

With the introduction of ES6, developers were blessed with a handful of extremely powerful Javascript features — one being [Object Property Shorthand](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer)

![https://media.giphy.com/media/xT3i0OK7FxeLZoJMNG/giphy.gif](https://media.giphy.com/media/xT3i0OK7FxeLZoJMNG/giphy.gif)

You've probably been there before — you're creating an object and it starts looking something like this:

```jsx
let name = "Tony"
let age = 55
let occupation = "Plumber"

let person = {
	name: name,
	age: age,
	occupation: occupation
}

console.log(person) // {name: "Tony", age: 55, occupation: "Plumber"}
```

We can all agree that writing an object like that seems a little ridiculous — and at the very least.. repetitive. So now what?

![https://media.giphy.com/media/xT1Ra5UDyrlykT3gAM/giphy.gif](https://media.giphy.com/media/xT1Ra5UDyrlykT3gAM/giphy.gif)

In comes the Object Property Shorthand feature. We can create the same exact object by doing the following:

```jsx
let name = "Tony"
let age = 55
let occupation = "Plumber"

let person = {
	name,
	age,
	occupation
}

console.log(person) // {name: "Tony", age: 55, occupation: "Plumber"}
```

![https://media.giphy.com/media/oit9mu0v5LqzC/giphy.gif](https://media.giphy.com/media/oit9mu0v5LqzC/giphy.gif)

**Note:** At the time of writing this, Internet Explorer does not support this feature.

That's pretty much all there is to this ES6 feature. Check out some of my other blogs covering some of the a few of the other ES6 features:

[JS: VAR, LET, and CONST feat. Hoisting](https://dev.to/antdp425/var-let-and-const-feat-hoisting-3o28)
[Javascript: How to Use Arrow Functions](https://dev.to/antdp425/javascript-how-to-use-arrow-functions-455a)
[Javascript: How to Use the Spread Operator and Rest Parameter](https://dev.to/antdp425/javascript-how-to-use-the-spread-operator-and-rest-parameter-5e27)
[Javascript: Destructure Objects and Arrays for Cleaner Code](https://dev.to/antdp425/javascript-destructure-objects-and-arrays-for-cleaner-code-10a5)

Feel free to reach out on any of my socials for questions, feedback (good and bad), or just to connect / say hello 👋.
Year in review – running
Tags: 100daystooffload
Published: 2020-12-17 22:35:24

Strava has published its year in sport app and my stats are in:

* 2506 km travelled
* 334 hours of activity
* 14650 m of elevation gain
* 271 days active

There are some considerable gains for me compared to last year. I covered 600 km more than last year, spent 125 hours more time doing 150 more activities. I only really had one goal for the year and that was to run over 2000 km, so I can be pleased with that achievement.

As for the rest of the stats, I'm pleased overall, but probably not _hugely_ surprised given my routine of running most days of the week. I suppose the extent of climbing and distance covered is the biggest surprise, since the way I have been running has seen the most change.

Sunday has been my "long run" of the week for a long time now. Until this year, it also used to be more of an adventure, and in my fitter periods I would hope to cover between 20 and 25 km off road. Much of this was jogging or walking of course, but it was certainly the big distance of the week. I'd also achieve one or two running workouts a week, with the other days being easy. 

This year, Sunday has still been my long run but it has been much shorter, not often more than 16 km or 10 miles. However, I've also changed to running 5 or 6 days a week, the vast majority of which were reasonable distance easy or moderate efforts. Occasionally I did some speed work but really the importance of running this year was for my mental health rather than anything else. I could even go as far as saying that I was commuting via my morning runs.

Right now I am not going to set any goals for next year, except that I will keep running and try to do so whilst remaining healthy and free from injury.

_I'm publishing this as part of 100 Days to Offload. You can join in yourself by visiting [https://100daystooffload.com.](https://100daystooffload.com)_
Guía - Base Node.js + Express.js con sintaxis moderna (Español)
Tags: spanish, node, javascript, babel
Published: 2020-12-17 22:31:22

En mi primer post en Dev.to! Voy a explicar como empezar una api de cero con node.js mas Express.js para usar la sintaxis moderna de JavaScript.

Para lograr esto vamos a usar Babel, para escribir código moderno y lo convierte a un código que lo entienda la mayoría de los navegadores.

**Empecemos...**

* Iniciando una Api
`npm init –-y`	

* Instalamos Express.js
`npm i express`	

* Instalamos Babel como "devDependencies"
`npm i @babel/core @babel/cli @babel/node @babel/preset-env @babel/plugin-transform-runtime -D`	

**Que es cada cosa...**
**Core:** Modulo principal de babel.
**Cli:** Para utilizar babel desde consola.
**Node:** Para usar babel adentro de node.
**Preset-env:** Para configurar Babel.
**Plugin-transform-runtime:** Para no tener problema con códigos async/await.

* Crear un archivo llamado “.babelrc” en la raíz de la api, para escribir las configuraciones.
```javascript
{
    "presets": [
        "@babel/env"
    ],
    "plugins": [
        "@babel/transform-runtime"
    ]
}
```
* Creamos el típico index.js en /src

```javascript
import express from "express";

const app = express();

app.set("port", 3000);

app.listen(app.get("port"));

console.log("Servidor Encendido, en el puerto:", app.get("port"));
```
Usando la sintaxis moderna de “import”

* Para ejecutar la api con babel, hay q modificar el siguiente comando en Scripts del package.json.

```javascript
  "scripts": {
    "start": "babel-node src/index.js"
  },
```

* Ejecutamos
`npm run start`


**Bonus Track:**

* Ya de paso para dejar una buena base, para trabajar con la api y que se actualice automáticamente cada vez que guardamos el código, vamos a agregarle “Nodemon”

`npm install --save-dev nodemon`

* Como ultimo paso tenemos que modificar los comandos de ejecucion en scripts de package.json

```javascript
  "scripts": {
    "babel-node": "babel-node",
    "dev": "nodemon --exec npm run babel-node -- src/index.js",
    "build": "babel src --out-dir dist",
    "start": "node dist/index.js"
  },
```

**Dev:** Para ejecutar con babel-node el src/index.js con nodemon.
**Build:** Para hacer un build en la carpeta dist de la api para prod.
**Start:** Ejecuta la api en prod ya con su build en la carpeta dist.

Con este último punto, finalizamos la guía.

#### [Repo de la guía en Github](https://github.com/venezia-dev/nodejs-expressjs-sintaxis-moderna-base)

#### [Mi Twitter](https://twitter.com/Lea_Venezia)	

## A Codear...!
Day 279 : All The Work
Tags: hiphop, code, coding, lifelongdev
Published: 2020-12-17 22:30:34

_liner notes_:
- Professional : Today was the demo day of the internal hackathon at work. I put together a quick presentation to explain what I was working on. Everyone built some cool things. Then it was my turn. Went through my slides, demoed the applications and it went through with not too many problems. The site I was using to host the applications took a minute to boot up, but the projects worked with no issues. All the work put in the past couple of days was worth it.

- Personal : Attended a JavaScript meetup in London during the day. Some good talks. Last night, I did a lot of research in trying to figure out how to get this YouTube API to work the way I want to. Everything I'm reading is like nope! Got to be a way. I'm going to see if I can get the node example working in a project by itself and build up from there to where I need it. We'll see.

![Overhead view of the beach at The Dead Sea, Israel with green tinted water](https://dev-to-uploads.s3.amazonaws.com/i/ahesk9pkjvkkul64pak6.jpg)

Just found out that the final season of "Attack on Titan" starte airing. I new it was coming up, but time has been flying by. Definitely want to start watching it again. I may do a binge watching session of the previous seasons before watching this final one to get caught up. Before that, I want to see if I can get this Node example of how to upload to YouTube working. We'll see how far I can go. Also want to listen to some tracks for this week's radio show.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube vEbzs9ekyT4 %}
What awesome tools did you discover recently?
Tags: watercooler, productivity, inspiration
Published: 2020-12-17 22:22:37

---
title: What awesome tools did you discover recently?
published: true
description: 
tags: watercooler, productivity, inspiration
cover_image: https://static.vecteezy.com/system/resources/previews/000/362/929/non_2x/vector-person-worker-digging-and-mining-for-gold-in-an-underground-tunnel.jpg
---
Could you share some amazing apps, tools, or services that you have come across recently and thought deserve more spotlight?

Some of my recent discoveries would include:
 
[FontJoy](https://fontjoy.com/) - an online tool for exploring different font combinations.

[Neumorphism](https://neumorphism.io/) -an online tool for generating CSS shadows.

[VantaJS](https://www.vantajs.com/) - animated website backgrounds  with a built-in customization.

Share your hidden online gems you just dug out!
Nest.js에서 Pipe의 필요성
Tags: nest, pipe, node
Published: 2020-12-17 22:09:26

Nest.js의 Pipe는 굳이 비교하자면 Spring의 Converter 또는 Formatter의 그것과 같다.

하지만 *Middleware*나 *helper*가 있는데 왜 *Pipe*라는 개념까지 도입한 것일까라는 의문이 생긴다.

공식문서의 개념에서 [Pipe](https://docs.nestjs.com/pipes)는 `@injectable` decorator을 사용하는 JS class 라고 설명하고 있다. 즉, Provider과 기본 개념이 동일하다.

그렇다면 먼저 `injectable`이 무엇인지 알아보자.

<center><br></center>

## Injectables

A모 프레임웍에서 에서 파생된 `injectable`은 간단히 말해 [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection) 패턴을 적용시키겠다는 말이다.

Nest는 Provider 패턴으로 쉽게 dependency를 관리 및 공유할 수 있는데,
한 번의 주입으로 만들어진 의존성 인스턴스를 하위 모듈에서 쉽게 접근할 수 있다는 장점이 있다.

> React Context Provider ∝ Nest Module Provider
> 하위 객체에게 의존성을 주입하는 것은 비슷하다.

이는 인스턴스 한 개만 관리하기 때문에 디버깅을 간단하게 해줄뿐만 아니라 메모리 누수를 막을 수 있다는 매우 큰 이점을 가져다 준다.

다음과 같은 예를 보자.

```ts
@Injectable()
export class ExampleService {
  constructor(private memoryLeak = new ArrayBuffer(10000)) {}
}
// ExampleService 인스턴스가 생성될 때마다 10000byte 메모리 누수를 일으킨다.

@Module({
  providers: [ExampleService],
})
export class ExampleModule {}
// 이를 `Injectable`화 하여 주입하면 Nest는 인스턴스를 재사용하게 된다.
```

이같이 한 번의 Provider 주입만으로 `injectable`을 하위 모듈간 쉽게 위임하고 재활용할 수 있다.

<center>
![Dependency Injection](https://dev-to-uploads.s3.amazonaws.com/i/n6h5pdmubkfvp5noxmug.png)
\<Dependency Injection\>
<br>
</center>

명시적 `injectable`을 통한 DI패턴은 유용하지만, 여기까지만 보면 그냥 필요에 따라 Provider에 헬퍼나 팩토리 따위를 담아 사용하는 방법이 떠오른다.

그렇다면 다시 처음으로 돌아가 Pipe는 타 헬퍼과 다른 점이 무엇일까?

<center><br></center>

## Pipe vs. the World

공식문서를 인용하자면 Pipe는 컨트롤러 handler의 매개변수 전처리를 도와주는 특수한 helper라고 정의할 수 있다. 다시 말해 input으로 들어오는 데이터를 지정된 파이프를 거쳐 들어오게끔 하는 것이다.

이는 Middleware의 역할이 아닌가라고 볼 수 있지만 Middleware은 Request에 _항상_ 관여한다면, Pipe는 특정 route handler에 붙어 _필요한_ 데이터값만 선별해 다룬다는 점에 차이가 있다.

이렇게 Pipe를 거친 input을 handler에 전달할 경우 각 단일책임원칙을 위배하지 않음과 동시에 알맞게 정제된 반환값을 받을 수 있다.

또한, Pipe 역시 재사용 가능한 `injectable`이므로 어느 라우터에 갖다 붙여도 된다는 장점이 있다.

<center>
![Request flow](https://dev-to-uploads.s3.amazonaws.com/i/mpskj7cxj195cchgx9x0.png)
\<Request flow - Pipe는 모두 재사용 가능하다\>
<br>
</center>

> Pipe 또한 당연하게도 exception filter의 혜택을 누릴 수 있다. 특정 매개변수의 에러를 이곳에서 처리하자.

<center><br></center>

## Pipe use-case

Pipe 역할은 이제 알디시피 '맞춤형' 필터라고 볼 수 있으며 평소 middleware이 하는 역할들을 pipe에게도 맡길 수 있을 것이다.

태생이 이렇다 보니, Nest 프레임웍은 자주 쓰이는 [기본 Pipe](https://docs.nestjs.com/pipes#built-in-pipes)들을 제공한다.

실전으로 들어가 REST API에서 `/person/3` endpoint에 요청을 받았다고 생각해보자.

```ts
@Controller('person')
export class PersonController {
  @Get(':id')
  async getPerson(@Param('id') id: number) {
    // return a matching person
  }
}
```

이 때, `id`가 항상 `number`로만 들어오면 괜찮지만 만약 `3a`가 들어올 경우 Pipe를 제공해 변환해주어야 한다.

```ts
// ParseIntPipe에 변환 과정을 위임한다.
@Get(':id')
async getPerson(@Param('id', ParseIntPipe) id: number) {
  // return a matching person
}
```

이처럼 Pipe를 사용해 아주 간단히 `getPerson` handler의 관심사 분리를 할 수 있다.

> Pipe용으로 사용할 수 있는 매개변수는 `@Param`, `@Body`, `@Query`가 있다. 

위 예시는 기본적인 Pipe 사용 방법을 제시했지만, 유효성 검증 및 입맛에 따라 커스텀 Pipe도 얼마든지 만들 수 있다.
Advent of Code 2020 Solution Megathread - Day 17: Conway Cubes
Tags: adventofcode, challenge
Published: 2020-12-17 22:04:41

---
title: Advent of Code 2020 Solution Megathread - Day 17: Conway Cubes
published: true
description: It's Conway!  In 3 dimensions!
tags: adventofcode, challenge
series: Advent of Code 2020
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/9rzqnlfcr5hggo5ddb35.png
---

Yesterday was a big one!  I ended up just writing and writing and writing and looping and looping and looping.  And, if I'm being totally honest and transparent, my original solution before refactoring had a `goto` in it.  Not great.  But it came out pretty good after some refactoring and pulling logic out into functions.

## The Puzzle

In [today’s puzzle](https://adventofcode.com/2020/day/17), we're back to Conway.  This time in the **third dimension**.  We've got cubes that turn on and off depending on how many of their *26* neighbors are also active.  And the rules for transition are pretty low, so I think this is going to be one blinky cube!

## The Leaderboards

As always, this is the spot where I’ll plug any leaderboard codes shared from the community.

```
Ryan's Leaderboard: 224198-25048a19
```

If you want to generate your own leaderboard and signal boost it a little bit, send it to me either in a DEV message or in a comment on one of these posts and I'll add it to the list above.

## Yesterday’s Languages

Updated 02:04PM 12/17/2020 PST.

| Language   | Count |
|------------|-------|
| Haskell    |     2 |
| JavaScript |     2 |
| Rust       |     2 |
| C          |     1 |
| Ruby       |     1 |

Merry Coding!
Short Intro to Unbundled Development With Snowpack | Part 1
Tags: javascript, snowpack, react, npm
Published: 2020-12-17 21:55:54

###**Introduction to Snowpack**

   Snowpack is a modern, lightweight, and fast Javascript build tool like Webpack and Parcel. The difference between Snowpack and other tools is that Snowpack instead of a rebuild and rebundling entire chunks of your application every time you save a single file, which causes a lag between saving any single file and seeing changes in the browser( Complexity of *O(n)* ), Snowpack serves the application unbundled during development. 
   Each file needs to be built only once and then is cached forever, and when you save a file Snowpack builds that single file (Complexity of *O(1)* ). In this way, Snowpack saves your time.

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


###**Install Snowpack**
 ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/oic15ayw9we8y0k40e2m.png)


###**Run thw Snowpack CLI**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/hxsad5882gz5uw41m2ps.png)
 

###**How to use Snowpack?**
The best way to configure Snowpack is with `package.json` script.

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


###**Serve your project**
By default, this serves your current working directory to the browser, and it will lock for /index.html file to start.


###**Build your project**
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/tyaekcyqmfqvbzmk7bc2.png)

This will generate a static folder `/build` that you can deploy.


#####**Part 2**
*Getting Started With React and Snowpack*
What's makes Good pixel art game
Tags: gamedev, design, unity3d
Published: 2020-12-17 21:54:47

Hello! In this post i Will tell you what's makes Good pixel art game.

1. Resolution of cannvas. Every character need Be as big as the others character.

2. Good color palete. Before you start drawing choose first Color palette you want to use. 

3. Shades are very important because it looks much better Shaded as purely one color.

4. Focus on good lighting especially when the game takes place in a confined environment. 

5. Good Boss. Making a good and difficult boss is difficult, It is more attractive for a player when the boss has more attacks. Then it's not repetitive. 

Thnaks for reading.
DevAnalytics at DOHackathon: ng-bootstrap and...
Tags: dohackathon, angular, ngbootstrap, devanalytics
Published: 2020-12-17 21:08:31

My idea is to work on this Hackathon every single day and even though I cannot put in a lot of time, it should bring progress.

Today I installed [ng-bootstrap](https://ng-bootstrap.github.io/#/home) on the frontend side and I also started to process the data a bit that is returned from the backend.

![Table with bootstrap](https://dev-to-uploads.s3.amazonaws.com/i/vg0dm48crq3w7mk8z9ry.png)

Tomorrow I will come with a way to visualize nice names for the different stats.