teleren/devto huggingface dataset:
Create a Fastify server
Tags: javascript, webdev, node, fastify
Published: 2021-08-23 23:51:00

## Introduction

[Fastify](https://www.fastify.io/) is a **web server framework** like ExpressJS but with _better performances_. 

[![Benchmark on the website Fastify.io](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dh58y5oa54arc78g0ok4.png)](https://www.fastify.io/benchmarks/)

The ecosystem is pretty cool, he [adds multiple plugins](https://www.fastify.io/ecosystem/). But in this first test, I only add **fastify-static** for getting .html files. 

## Let's code !

At the first time, create a void folder and install Fastify and fastify-static.

```bash
npm i fastify fastify-static
```

Create an **app.js**, it's your root file. 


## Into the app.js

You can write the basis of this file for creating a new Fastify server. 

```js
const path = require("path")
const f = require('fastify')({logger: false})

f.register(require('fastify-static'), {
    root: path.join(__dirname, 'public'),
    prefix: '/public/',
})

// In this example, when you get localhost:3000, ou have the time
f.get('/', (request, reply) => {
    reply.header('Content-Type', 'application/json')
    reply.send({hello: new Date()})
})
f.get('/about', (request, reply) => {
    reply.sendFile('about.html' )
})


const start = async () => {
    try {
        await f.listen(3000)
    } catch (err) {
        f.log.error(err)
        process.exit(1)
    }
}
start().then(r => r)
```

## Public HTML pages

Create a **/public** folder and a **about.html** file.

![Create your public folder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aqf234ealz2lmr2bxihs.png)



## End 

It's a very short post, but I demonstrate how to simply start a server with **Fastify**. As this is the first time I use it, there might be some errors. Don't hesitate to give me feedback in the comments ! 👍🏼

[Getting Started with Fastify](https://www.fastify.io/docs/latest/Getting-Started/)

___

|☕|Check my [Twitter account](https://twitter.com/thomasbnt_). You can see many projects and updates. You can also [support me on Buy Me a Coffee, Stripe or GitHub Sponsors](https://thomasbnt.dev/donate). Thanks for read my post ! 🤩|
|---|---|
How I learned react native in 1 day?
Published: 2021-08-05 14:25:52

---
title: How I learned react native in 1 day?
published: true
description: 
tags: 
//cover_image: https://direct_url_to_image.jpg
---
Excited, Umm!!

OK. As a frontend web developer, switching to the mobile platform is a bit nervous and uncomfortable initially, but in my case. it is even worse. Suddenly I got a call from one of my connections and they ask me to build a couple of screens in react native with some basic functionality. I think twice and finally said OK, Because I haven't touched react native before.

BTW, I do plain react all day... every day!

I heard from many people that react on web and react in mobile is more or less the same. A little confidence was gained for 2 min. But I know it takes a little effort to finish the task.

I jumped straight into the code editor and started coding react native. 
What do you think, did I succeed? 

Hell Nooooo!!!!

I got stuck at the beginning itself even positioning things properly. It took me  2 hours to debug the code for simple navigation.

Later I realized, Probably the syntax might same in both, But implementation is a bit different.

## React web

```
 function Mock(){
  return (
     <div>
        <p>React web</p>
     </div>
   )
 }
```
## React native

```
 function Mock(){
  return (
     <View>
        <Text>React web</Text>
     </View>
   )
 }
```

The above code snippets will tell you the similarity between react and react-native.

Then the most exciting part begins. I opened react-native documentation without giving it another thought. But Setting up react native in our local system is time-consuming. Thanks to my connection, I was supposed to work on a remote system where the project is already created. 

In the documentation, I only search 2 topics

- Navigation 
- Flexbox

All the styling part is pretty normal and easy to do. As you can see in the above code snippets.
Even a non-react web developer can play with **CSS** styling.
Once I have gone through topics, I have got a good understanding and even create some mockup screens in the **stack. expo.dev**  tool. It is really helpful when practicing react-native. It is an online editor specially made for react-native.

A confident me.. going back and connect to the remote system.
This time.. you know what happens!

Happy connection and happy me :)
Happy coding!!

## Moral

> “If somebody offers you an amazing opportunity but you are not sure you can do it, say yes – then learn how to do it later!”
How to Handle Errors in Go
Tags: go, handleerrors, debugging
Published: 2021-08-23 23:30:09

Error handling is a mechanism added to many modern programming languages which typically defines how the code is going to react under unexpected circumstances. Some syntactic and semantic errors are directly dealt with by the compiler, who reports them as they are detected by the static checker. But there are some that need special handling. Many languages use specialized syntax to deal with errors that are a bit complex in their syntactical structure. Go is more simplistic and uses values to denote the type of error returned from functions like any other value. The article introduces the error handling mechanism of Go with some examples.

If you are unfamiliar with working with functions, you may want to read our article on the subject: Understanding Functions in Go.

Go Error Handling using the errors.New Functions

Read More: https://hitechnoloy.ca/how-to-handle-errors-in-go/
Loading Initial Data with Spring Boot
Tags: springboot, java, hibernate, jpa
Published: 2021-08-23 23:08:30

With SpringBoot + Hibernate we can easily manage our database. By default, all classes marked with the `@Entity` annotation in our packages are used to create tables automatically.

Well, there are times we need more fine-grained control over the database alterations according to our requirements.
In this post I'll be sharing lights on one of those scenarios: **Auto-populating or loading initial values into our tables**.

SpringBoot has some reservations for situations as this. We make use of the `data.sql` file in Spring to actualise this.

> This file should be saved in the directory:
`src/main/resources/` 

*Hint: Same location as `application.properties` file.*

When we run the project with this file on the resources directory, Spring will pick it up and use it for populating the database.

As an example, we can decide to load initial values for the `Role` entity as follows:

```
INSERT INTO Role (name) VALUES ('USER');
INSERT INTO Role (name) VALUES ('ADMIN');
```
When you start your application, spring will attempt to load these data into the `Role` table which at this time does not exist which will cause the program to fail, so we need to add the following config to `application.properties` file

```
spring.jpa.defer-datasource-initialization=true
```

This tells spring to delay the data initialisation process. Now start your spring application, and you should be able to see the values 'USER' & 'ADMIN' in the Role table.

Hope you find this helpful. You can leave a comment to contribute. Thanks!
Day 436 : Elements
Tags: hiphop, code, coding, lifelongdev
Published: 2021-08-23 22:09:46

_liner notes_:
- Saturday : Got up early to finish up the radio show. When that was done, I did some research into another possible side project. Decided against it because one of the APIs I would use is a pain in the butt to use. Had a good time doing the show. The recording of this week's show is at https://kNOwBETTERHIPHOP.com

![Radio show episode image of a photo of Sonny Chiba wearing a tuxedo standing in front of a yellow wall looking directly into the camera with the words Aug 21st 2021 HTML CSS JS (RIP Sonny Chiba)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ris4hv3ade0v2635nh6.jpg)

- Sunday : Did my new show at https://untilit.works I added the ability to add the links mentioned in the video to the archive page after the broadcast is over. I was able to code it up and get it deployed between the two shows. During the show is also when I get all the post radio show promo stuff done. I even tested the camera I plan on using for my side project to stream to the media server I set up. I wanted to check to see if there would be any audio video sync issues. I streamed to the server for about 2 hours and there were no issues. I was super happy about that. After the show, I watched "The Walking Dead" and an old episode of "Rick and Morty". During the commercials, I answered some quizzes after watching some videos on some crypto coins and made about $40 in coins.

- Professional : Even though I had a bunch of meetings today, I got some stuff done. I was able to review a newer version of a tutorial that will be coming out soon. Gave some feedback on a new tool. Did a little work on the styling of my Web Components I made. Not a bad day.

- Personal : Over the weekend, I did some research on an opportunity that I'd really like to get into in the new year. I even told some of my team members and they seemed pretty excited about it as well. I just need this transfer to clear so I can start to put plans into motion.

![Looking up at a snow covered, gray, pointy, and jagged mountain range in Geislergruppe, Italy with a forest of orange and green trees at sunset](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jx99g4451a3thfuzphrm.jpg)

Now that the server is performing well, I can get on to working on the dashboard for my current side project. From there, I can hopefully generate the data needed for the front end. Again, I'm super happy that the camera worked with the server. As a backup, I researched using a service to get things working, but that would have cost much more that what I wanted to spend especially in the beginning stages. With that working, I feel like all the other elements will fall into place. Going to eat dinner and watch an anime. Not sure which one. The work on my side project a little.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube sO6HKH2t1gg %}
Spotify Front
Tags: webdev, html, css, spanish
Published: 2021-08-23 21:35:59

Buenas !

Llevo un par de semanas pensando en hacerme mi propio portafolio con ideas personales sin seguir ningún tutorial, y así fue cómo nació el primer proyecto que voy a agregar a mi portafolio.

Spotify Front es un intento de replicar una vista aleatoria de la aplicación de spotify en el navegador.

La vista a replicar es la siguiente: 

![Official-Spotify](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pf1gyjxsmk6pu1237des.png)

El resultado:

![Spotify-Front](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/az3xn4maqun309god4i7.png)

El proyecto estaba enfocado en poner a prueba mis habilidades en maquetación sin usar ningún tipo de librería ni framework. También se dejó de lado el tema de las animaciones y los hovers, ya que el propósito de este proyecto era aprender/mejorar el manejo de distintas propiedades en CSS y realizar un buen nombramiento de clases para que se entienda mas o menos la estructura del proyecto.


Les dejo el enlace por aquí por si quieren visitar el repositorio en donde lo tengo todo guardado y commiteado por si me quieren dar cualquier tipo de feedback: https://github.com/blueC4P/spotify-front

Saludos ! ✌
What was your win LAST week?
Tags: discuss, weeklyretro
Published: 2021-08-23 21:00:43

---
title: What was your win LAST week?
published: true
description: Got to all your meetings on time? Started a new project? Fixed a tricky bug?
tags: discuss, weeklyretro
cover_image: https://cl.ly/188e843c2985/download/Image%202019-02-15%20at%202.36.37%20PM.png
---

Hey folks! 

Quick confession: **I FORGOT TO ASK ABOUT WEEKLY WINS LAST FRIDAY** 😱  

![box of shame](https://media.giphy.com/media/eP1fobjusSbu/giphy.gif?cid=ecf05e47ytbhhi4xuqilgyz1jueco7k7rtipwg8q6eebhc6d&rid=giphy.gif&ct=g)

Sorry about that! Let's get to it — just a few days late 😆 


**Looking back on** **<mark>last<mark>** **week, what was something you were proud of accomplishing?**

All wins count — big or small 🎉

Examples of 'wins' include:

- Starting a new project
- Fixing a tricky bug
- Trying out a new form of exercise... or whatever else might spark joy ❤️ 

---

Thanks for bearing with me. Can't wait to read about your wins from last week!

![Excited baby](https://media.giphy.com/media/j0vs5H7Kcz3Pm9LRDa/giphy.gif?cid=ecf05e479gcxfwipuqumnogvk0pkqd95yr5zyadetiw7m249&rid=giphy.gif&ct=g)

I'll be back at the end of the week (promise) with the normal Friday wins thread. 👋
Terraform datasources: external
Published: 2021-08-23 20:57:51

Continuando o assunto de datasource que falei no post anterior, dessa vez vou falar um pouco sobre outro tipo especial de datasource do Terraform: o `external`.

> Antes de continuar, é importante comentar que na documentação esse recurso é chamado de *escape hatch* (saída de emergência), e dever ser usado apenas em situações excepcionais onde um outro datasource de um provider não atenda.

## Provider: `external`

Esse datasource faz parte do provider *external*, que não requer nenhuma configuração, basicamente é usado para prover uma interface entre o Terraform e aplicações externas, para ser usado em casos onde outros providers não atendem.

## Datasource: `external`
O datasource external permite que uma aplicação externa (usando um protocolo específico) seja usada como entrada de dados, expondo uma saída para ser usada no código.

Ex: imagine que você por algum motivo (e em algum cenário muito específico) precisa criar algum recurso com base na saída de um script com uma determinada entrada.

Nesse caso, o datasource vai ficar assim:
```
data "external" "external_data" {
  # chamada do script/aplicação
  program = ["go", "run", "${path.module}/external_datasource.go"]

  # parâmetros de entrada, nesse caso é o 'sound'
  query = {
    sound = "honk"
  }
}

output "response" {
    value = data.external.external_data.result
}

```

Onde o script [`external_datasource.go`](https://github.com/edsoncelio/terraform-datasources/blob/main/external/external_datasource.go) é:
```
package main

import (
	"encoding/json"
	"log"
	"os"
)

type InputQuery struct {
	Query string `json:"sound"`
}

type OutputQuery struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

func main() {
	var inputQuery InputQuery
	var outputQuery OutputQuery

	err := json.NewDecoder(os.Stdin).Decode(&inputQuery)
	if err != nil {
		log.Fatal(err)
	}

	if inputQuery.Query == "honk" {
		outputQuery.Code = "200"
		outputQuery.Message = "successful honk"
	} else {
		outputQuery.Code = "400"
		outputQuery.Message = "failed honk"
	}

	if err := json.NewEncoder(os.Stdout).Encode(outputQuery); err != nil {
		log.Fatal(err)
	}

}
```

Nesse caso, a saída vai ser:
```
$ terraform output
response = tomap({
  "code" = "200"
  "message" = "successful honk"
})
```

Importante falar também sobre os requisitos do script para ser usado:
* A aplicação deve ler a entrada via `stdin` e parsear como um objeto JSON, esse objeto vai conter o valor de `query`, que vai ser sempre `string`;
* A saída deve ser também um objeto JSON válido via `stdout`, esse objeto vai popular o atributo `result` no output do Terraform, e os valores também precisam ser todos `string`;
* Qualquer erro na aplicação deve ser retornado no `stderr` com um código de saída diferente de zero.


Caso alguém queira brincar um pouco mais com isso, deixo os códigos usados nas referências.

## Referências
* https://registry.terraform.io/providers/hashicorp/external/latest/docs
* https://registry.terraform.io/providers/hashicorp/external/latest/docs/data-sources/data_source
* https://github.com/edsoncelio/terraform-datasources/tree/main/external
Is VDom still faster?
Tags: javascript, webdev
Published: 2021-08-23 20:56:47

The idea behind a **virtual DOM** is clear: *Build an in-memory representation of the dom and just apply the differences to the "real" DOM.* This makes perfect sense on a machine, that is relatively slow. But is this still true today?

I entered the scene relatively late, just a few years ago. Before I was using compiled languages like C++, which are amazingly fast - most of the time. But - many people use mobile devices today, and a web browser may serve well to make your application platform independent. So, we checked out what is possible today.

**We where amazed**: Even though javascript is an interpreted language, running on chrome or firefox was exceptionally fast. Even memory intens applications seemd to perform very similar to what we whrere used to. The most amazing part is the HTML5 canvas element, that is very capable and creates high peformance antialiazed graphics in no time. 

Another amazing part of the browser performance was the increadible well performing double buffering of screen content: Even rebuilding the greatest part of the screen did not even cause a flickering of the screen. It seems, the guys at google did an exceptional good job designing the chromium engine (Which is the same for other current browsers like firefox or opera too). In any case: there are strong tools in modern browser to hide unnecessary screen updates and present a smooth experience, even if the programming was not that good.

We did a lot of direct DOM programming and where always happy with the performance: It just seems that the world has changed today. 

There is a simple question: Maybe it was right in 2012 to create a virtual DOM. But times have changed. A virtual DOM means: additional calculations are to be performed. Specially the diffing may cause tremendous load. And we know: There is a second machine behind (implemented in the browser), that also performs similary well to hide unnecessary screen updates. 

My questions is: Do we still need a virtual DOM? **IF** the browser is hiding unwanted screen updates, what happens with the virtual DOM? Does it just create additional processor load. Is it possible that both systems may interfere in and unexpected way that makes things even worse?
Free CBD (code behavior diagrams) for developers
Tags: webdev, humor, ruby, python
Published: 2021-08-23 20:54:28

It’s thrilling to see our free and open source interactive code analysis tools continue to gain traction. 

Some of our ideas have actually been repeated on other blogs and with other products.  Imitation is flattering, so we just want to keep on rolling and keep things positive. No bummer vibes here, it's all good.  

But it can be challenging to continue shipping dope visualizations and fresh ideas...

We’ve been thinking a lot about how to differentiate our interactive code analysis product from other tools in the market, particularly static code analysis tools for codebases.  

Because it’s so important that our projects aren’t confused with other tools that do very different things.  If you’re a developer, the last thing we want to do is cause you any more pain or stress around tooling!  

So, here’s the gist on [what AppMap is](https://appland.com/docs/appmap-overview.html) and how it differs from other dev tools in the ecosystem:

1. It’s free, open source and community-driven.
2. It shows both code organization and runtime traces.
3. It’s built on an open data format, so you can extend it with your own code and ideas. 
4. No signup or subscription required! You can use AppMap 100% client-side. 

Or think of it this way: AppMaps are Code Behavior Diagrams. They’re CBD! FreeCBD for Ruby, Python and Java developers! Get your FreeCBD from AppMap today!   

[FreeCBD for devs](https://appland.com/products/appmap) records code execution at runtime and presents this data in a variety of useful diagrams and analyses. 

Unlike with static code analysis, which inspects only source code and only against a given set of rules or standards, FreeCBD analyzes an entire application (including the code in your dev environment). Also unlike static analysis, FreeCBD observes the code’s interaction with all system components and records code behavior during the execution of any business logic scenarios.

We’re really proud of what we’re building, and we couldn’t do it without the support and participation of our wonderful community. Take a cue from some of our community members and start [understanding new codebases](https://appland.com/blog/2021/05/04/appland-community-profile-marcus-sanchez/), [getting familiar with code you didn’t write](https://appland.com/blog/2021/06/21/laurent-christophe-community-profile/) and [debugging complex apps](https://appland.com/blog/2021/08/10/comminuty-profile-noe-de-la-mora/) -- all while staying super stress-free and happy. 

And please help us spread the word! Our dank FreeCBD is here to make developers’ most vibe-crushing work a whole lot more chill. 😉
Thiết kế phòng net cùng Rula Esports
Published: 2021-08-23 20:41:34

Thiết kế phòng net là tiêu chí quan trọng hàng đầu thể hiện cá tính, mang lại trải nghiệm cũng như không gian thư giãn cho game thủ.

Địa chỉ: Số 119 Nguyễn Ngọc Nại, Khương Mai, TP Hà Nội

Số điện thoại: 0944.229.938

Website: https://rulaesports.vn/thiet-ke-phong-net/

#thiet_ke_phong_net 
#thiet_ke_phong_net_dep 
#rulaesports
Modern Ways to Center an Element with CSS
Tags: challenge, css, tutorial
Published: 2021-08-23 20:39:17

---
title: Modern Ways to Center an Element with CSS
published: true
description: Center an html element with CSS
tags: challenge, css, tutorial 
cover_image: https://www.aritsltd.com/blog/wp-content/uploads/2020/02/div-center.png
series: Job Interview Preparation Materials
---

CSS has come a long way on how to center 🎯 an html element. I can still remember some ways using tables and floats. Not pretty but it works during that time. 😃😎 Fast-forward, it is easy and can be done with few lines of code.

Feel free to bookmark 🔖 even if you don't need this for now. You may need to refresh/review down the road when it is time for you to look for a new role.

#### CSS translate/transform
```css
// maybe best to support old browser
.container {
    position: relative;
}

.child {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
```

#### CSS flexbox (3-liner code)
https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox
```css
// most popular because of current browser support
.container {
  display: flex;
  justify-content: center;
  align-items: center;
}
```

#### CSS grid (2-liner code)
https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Grids
```css
// the future
.container {
  display: grid;
  place-items: center;
}
```

In case you want to play and see this code in action:
Codepen: https://codepen.io/angelo_jin/pen/qBmwyzr

If you want a video version:
{% youtube QPr8uBohiBM %}

If you want to support me - [Buy Me A Coffee](https://www.buymeacoffee.com/letscode77)