teleren/devto huggingface dataset:
Instalar FreeBSD en raspberry pi 3 b+
Published: 2021-10-29 19:05:50

**FreeBSD** es un sistema operativo multiusuario, capaz de efectuar multitarea con apropiación y multiproceso, esta instalación la vamos hacer desde un sistema operativo GNU/Linux.



## Instalación de **FreeBSD 13** en raspberry Pi.
```
requisitos para instalar FreeBSD 13
1) MicroSD 8 gb o superior
2) raspberry pi 3b+ o superior para obtener (tier 1)
```
`Explicación de Tier en Freebsd` [Link](https://www.freebsd.org/platforms/).

#####Nos dirigimos a su página y descargamos la iso para raspberry pi.

link página FreeBSD: [Link] (https://www.freebsd.org/where/)

!["ímagen de la página de freebsd"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0xjq32cnt0xml42wylcr.png)

Seleccionamos la opción que dice **RPI(3/4)**.

#####buscamos la iso para la raspberry pi 3b+ y su respectivo checksum [Link](https://download.freebsd.org/ftp/releases/arm64/aarch64/ISO-IMAGES/13.0/)

!["foto de lo que tenemos que descargar"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i7t3gr25ybi57jqh0jkx.png)

una vez descargado nos dirigimos a la carpeta ~/Downloads y verificamos el checksum

!["verificamos CheckSum"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zaygmxsyzs4k0h64hz7w.png)

#####procedemos a montar la iso a la microSD:

```
Herramientas para bootear la iso a la microSD:
1) balena-etcher
2) gnome-disk-utility
3) dd
```
en este caso usaremos **dd**.

Agregamos la MicroSD y localizamos el name usaremos el comando: `lsblk`

!["salida de lsblk"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1x5tgyrmcyvuztl9f2g0.png)

como podemos observar la microSD tiene name `sdb`.

Aplicamos el comando **dd**:
dd SYNOPSIS: 
`# dd if="ruta del .iso" of="ruta de la microSD" bs=1M status=progress`
```
# -> root
$ -> user
```
ejecutamos el comando **dd** ahora conociendo como funciona.
`# dd if=~/Download/FreeBSD-13.0-RELEASE-arm64-aarch64-RPI.img of=/dev/sdb bs=1M status=progress`

Cuando termine de instalarse en la microSD la retiramos y la agregamos a la raspberry pi, luego la conectamos a la corriente. El sistema comenzará a instalarse y configurarse automáticamente luego pedira un login:
```
login: root
```
no tiene password así que toca crearle uno con el comando `passwd`

!["agragando password a root"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5bhiv6j8it53awsxtnh1.png)

Configuramos la fecha y la hora:
con el comando `ntpd` de ntp
`ntpd -qg`
luego montamos el servicio de ntpd, pero antes debemos habilitarlo en /etc/rc.conf
`# sysrc ntpd_enable=YES`
`# sysrc ntpd_sync_on_start=YES`
ahora si procedemos a montar el servicio
`# service ntpd start`
hacemos un enlace simbólico de tu zona horaria
`# ln -s /usr/share/zoneinfo/America/Bogota /etc/localtime`
Una vez terminada la config de la hora y la fecha vamos a actualizar el sistema.
`# pkg update`
`# pkg upgrade -f`

####con estos pasos tendriamos instalado FreeBSD 13 en la raspberry pi 3b+
Multi-Tenancy with Nodejs and mongoDb
Tags: node, javascript, mongodb, multitenancy
Published: 2021-10-29 19:04:55

The main concept of multi-tenancy is privacy and data segregation, With MongoDB architecture ( Database and collections ). It’s easy to allocate collection for tenants database 

![Erb diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lvbl5wkcok8k6en3dmzo.png)


You should have a simple npm application setup and install `mongoose` by running;

```javascript
npm install mongoose --save
```

Implement a logic to handle MongoDB database connection and switching. In this scenario I will use two different approaches, switching between database's using `useDb` and `disconnect` and `reconnect` ( this is useful for test cases only )

**Connect and disconnect approach**

```javascript

// mongoose import 
const Mongoose = require('mongoose')

// a function that takes database name and database url as import and return a mongoose connection
const connectDb = async (dbName, dbUrl) => {

if (dbName === Mongoose.connection?.db?.databaseName) return Mongoose

  try {
    Mongoose.connection.close()
    const mongoose = await Mongoose.connect(dbUrl, { useNewUrlParser: true })
    mongoose.connection.once('open', () =>
      log.info(`mongodb connected to ${dbUrl}`)
    )
    return mongoose
  } catch (error) {
    log.error(error)
  }
}
module.exports = { connectDb }
```
with the above usage, all we need is the database name and database URL, We check the database name to see if it's already open, if open we just return mongoose object else we close all open connections and reconnect to the database using the URL we passed in. 

**useDb(recommended) approach**

```javascript

// mongoose import 
const Mongoose = require('mongoose')

// a function that takes database name and database url as import and return a mongoose connection
const connectDb = async (dbName, dbUrl) => {

if (dbName === Mongoose.connection?.db?.databaseName) return Mongoose

  try {
    if( Mongoose.readyState == 1 ) {
        return Mongoose.useDb(dbName)
    } else {
    const mongoose = await Mongoose.connect(dbUrl, { 
                           useNewUrlParser: true })
    mongoose.connection.once('open', () =>
      log.info(`mongodb connected to ${dbUrl}`)
    )
    return mongoose.useDb(dbName)
}

  } catch (error) {
    log.error(error)
  }
}
module.exports = { connectDb }
```
A very simple approach, with `useDb` all we need is an open connection or create a new connection then return a new instance of MongoDB by passing the database name to the `useDb` function from an open MongoDB connection. In other cases you might have separate models(schema) for tenants, Here is an example. 

```javascript
// connect to mongodb
const mongoose = await Mongoose.connect(dbUrl, { 
                           useNewUrlParser: true })

// connect to prefer database
const db =  mongoose.useDb(databaseName)

// use model(schema) preferred
db.model(modelName, schema)

```
Keep tenants locked up!!

[twitter: code salley](https://twitter.com/codesalley)
Why and How to setup Storybooks with TypeScript
Tags: react, typescript, storybook, webdev
Published: 2021-10-29 19:01:26

## Introduction
In this blog, we are going to look at, How to set up Storybooks with React and my all-time favourite language(TypeScript). 
First of all, if you don't know what is Storybook.

### Storybook
Storybook is a UI development tool that lets you preview your components in a very rich library design that will help you to change all props for the component and test out your component in different scenarios. 

### Why use Storybook?
Maybe you should only use storybook if you're creating a component library(Open Source or for organisation). As for me, I created a component library for my organisation which is supposed to be used across multiple react projects. There I implemented Storybook(in component library project) so that everyone can have a preview of all components provided by the internal-component-library and use it according to the (kind of) storybook generated docs based on props.

## React Prerequisite
Make sure you have installed or created a new react project with
```shell
npx create-react-app storybook-ts-blog
```

## Storybook Setup
Now storybook can handle the setup part, just run the below command.
```shell
npx sb init
```
It will install storybook and add the necessary files for you to work with storybook.


## Test
Run storybook using below command
```shell
npm run storybook
```

# Wait, one more thing
Maybe you should also host the component library even if it's an internal project as it will help anyone other than devs(designers, managers) to have a look at your mess🤪(just kidding, I mean your components), just add basic authentication(username+password) before showing the hosted website.

To generate HTML files to host, run the below command
```shell
npm run build-storybook -- -o ./path/to/build
```

To run the build locally, use this command
```shell
npx http-server ./path/to/build
```
Docker and Kubernetes Made Relatable - II
Tags: devops, docker, kubernetes, devlive
Published: 2021-10-29 18:57:44

Welcome back to the second part of this series. 
Last time we discussed about Containers and Images and how they can be related with a workspace kit and a blueprint, respectively. In this post, we will see Docker images in action!
Now that we're here, let's get on with it!

## Getting Started With Docker Images and Containers
Docker is a well-known runtime environment for creating and building applications within containers. It deploys containerized applications or software in different environments, from development to testing and production, using Docker images.

### Creating a sample Go application
Let’s create a basic Go application that we will use to deploy on our minikube cluster.
Create a directory my-app which contains the below main.go file. From the command line, run the following:

```
go mod init 
go mod tidy
```
{% gist https://gist.github.com/Sampriti-Mitra/8b91e711912504f99a1e1a3d84992f9e %}

### Creating a Dockerfile for the Go application
To create the dockerfile for our application, we will refer to this:
{% gist https://gist.github.com/Sampriti-Mitra/b048bb6849909484fe4773236c034f9c %}

### Building the docker image and running the container
For building the docker image, run the following command in the terminal:
```
docker build --tag myapp .
docker images
```
You should be able to see the newly created myapp image in the list.
Now let us try running the image as a container. Since containers run in isolation, we need to expose the port inside our container to our host port.

> To publish a port for our container, we’ll use the --publish flag (-p for short) on the docker run command. The format of the --publish command is [host_port]:[container_port]. So if we wanted to expose port 8080 inside the container to port 3000 outside the container, we would pass 3000:8080 to the --publish flag.
```
docker run -d -p 8080:10000 myapp
```
Open `localhost:8080` in the terminal; it should say
Welcome to myapp!
Now that we have an idea about docker containers and the templates from which they are generated, i.e., images. Let’s have a look at container schedulers, which is what K8s is.

## Why Do We Require Container Schedulers? Why K8s Over Containers/Docker?
We saw how useful containers can be for running applications in an isolated way, on any environment. However, in production, hundreds to thousands of different containers may be required.
Container runtime systems like Docker benefit from the usage of additional technologies to orchestrate or manage all of the containers in use.
This orchestration is handled by Kubernetes.
In the next part, we will explore what Kubernetes is and how it works.
Thanks for reading!
Applied design part
Tags: design
Published: 2021-10-28 08:40:43

Github Repo: [Project](https://github.com/watson-hex/frontend-collabamigo)
Issue: [Issue](https://github.com/watson-hex/frontend-collabamigo/issues/78)
Pull-Request: [Pull-Request](https://github.com/watson-hex/frontend-collabamigo/pull/88)

#Overview
This 3rd project also snooped around a lot of projects in search of parts that I could touch, and it was an endless battle with the constant mass of projects. In fact, the 3rd week [project](https://github.com/watson-hex/frontend-collabamigo) and the preparation period for the midterm exam overlapped, so I wanted to choose a project that was not too difficult. So, this time, I looked for a design part project that I had not touched before. I was able to find a project with a reasonable level of difficulty, and in this [issue](https://github.com/watson-hex/frontend-collabamigo/issues/78), I asked to make a logo. So, I immediately tried to fix this issue.

#In the progress
In the case of design, I did not spend much time, but fortunately, there were basic images of the API or representative banner photos, so I immediately started creating a logo that could express the API by combining the images. Since it is a program where users can have a conversation at any time while taking a break, a steaming coffee cup meaning rest and a coding or dialogue bar meaning conversation or work are properly arranged and decorated using complementary colors.

#So at the End
After, done the project I immediately just [submitted](https://github.com/watson-hex/frontend-collabamigo/pull/88) and start to do other work because I didn't have enough time to do all!!! :(
Angular: The power of Async Pipe + Observables.
Tags: angular, observables, rxjs, async
Published: 2021-10-29 18:42:39

One of the most powerful features when creating Angular components is the Async Pipe. The greatest thing about it is that it allows you to take advantage of asynchronous rendering in your template without having to worry about subscribing and unsubscribing from Observables.   

```typescript
import { Component, OnInit, OnDestroy } from '@angular/core';
import { of, Subject } from 'rxjs';
import { delay, startWith, takeUntil } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  template: `
    <h1>Async example</h1> 
    <h2>Items</h2> 
    <ul>
      <li *ngFor="let item of items | async">{{item}}</li>
    </ul>
    <h2>Other Items</h2> 
    <ul>
      <li *ngFor="let other of otherItems">{{other}}</li>
    </ul>
  `,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit, OnDestroy  {
  
  items = of([1, 2, 3])
    .pipe(
      delay(2000), 
      startWith(['...'])
    );

  // vs 

  otherItems: any[];
  private destroy$ = new Subject();
  ngOnInit() {
    of([1, 2, 3])
      .pipe(
        delay(2000),
        startWith(['...']),
        takeUntil(this.destroy$)
      )
      .subscribe(other  => this.otherItems = other)
  }
  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
}

```
[Check it out on Stackblitz.](https://stackblitz.com/edit/angular-async-pipe-vs-subscribe-lphz5b?file=src/app/app.component.ts
)

As you can see, in the first example, we are rendering a list (items) using the `async` pipe in the HTML template. There is no need for the additional handling after the component is destroyed, which you can see is not the case for the other list `otherItems`.   That is simply because the `async` pipe is going to take care of that for you.
Função de validação de email em PHP
Tags: php, webdev, programming, tutorial
Published: 2021-10-29 18:17:51

Simples, rápido e sem enrolação: validando email em php com expressões regulares.

Validar email é uma das funções mais básicas no dia a dia de um programador. Fazer isso em PHP é simples, utilizando o método preg_match().

Deixo o link do método na documentação oficial do PHP:

* [preg_match()](https://www.php.net/manual/pt_BR/function.preg-match.php)

O bacana é que você pode usar esta expessão regular em qualquer linguagem, basta adaptar.

```php
/* chamaremos nossa função de validaEmail, e passaremos a variáve $email por parâmetro*/
function validaEmail($email) {}
```

Vamos trabalhar nosso código de validação dentro da função validaEmail.

Você pode separar o email em três partes: uma para a conta, outra para o domínio e outra para a extensão. Apenas para deixar o código mais legível.

```php
$conta = "/^[a-zA-Z0-9\._-]+@";
$domino = "[a-zA-Z0-9\._-]+.";
$extensao = "([a-zA-Z]{2,4})$/";

// vamos concatenar as variáveis
$pattern = $conta.$domino.$extensao;
```

Por fim utilizamos o método preg_match(). Ele aceita alguns parâmetros, então passaremos a expressão regular (salva na variável $pattern), o email que será inserido (passado como parâmetro da nossa função validaEmail), e a variável de checagem.

Segundo a documentação do PHP, o método preg_match() Pesquisa em $pattern uma correspondência para a expressão regular fornecida em $email. Se a variável $check for fornecida, ela será preenchido com os resultados da pesquisa. 

```php
if (preg_match($pattern, $email, $check))
    return true;
  else
    return false;
```

Agora podemos usar a função para validar emails de um site, sistema ou aplicação. Na prática seria algo assim:

```php
function validaEmail($email) {
  $conta = "/^[a-zA-Z0-9\._-]+@";
  $domino = "[a-zA-Z0-9\._-]+.";
  $extensao = "([a-zA-Z]{2,4})$/";
  $pattern = $conta.$domino.$extensao;
  if (preg_match($pattern, $email, $check))
    return true;
  else
    return false;
}

// Define uma variável para testar o validador
$input = "meuemail@dominio.com.br";

// Faz a verificação usando a função validaEmail
if (validaEmail($input)) {
  echo "O e-mail inserido é valido!";
} else {
  echo "O e-mail inserido é invalido!";
}
```

Se preferir visualizar a imagem da função:

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

Espero que tenham curtido. Dúvidas e sugestões, só usar o form de comentários :D
:strong_migrations for Elixir - catch unsafe migrations easily
Tags: elixir, opensource
Published: 2021-10-29 17:56:20

Hey, hey! I just published my next small open-source library (actually, it's a "port" from Ruby). Thanks to `:strong_migrations` you can catch all unsafe things that happening in your application's migrations like:

- remove column
- rename column
- drop table
- add index non-concurrently
- add index concurrently in a transaction
- drop index concurrently in a transaction

... and soon much more like migrations that are adding NOT NULL, etc. There are also a few configuration possibilities, so you can prepare everything to meet your application's requirements.



Any feedback or feedback is welcome. That is my first time when I was working on the AST - that's also why I've opened an issue with the "help wanted" label. It's related to refactoring possibilities of the AST parser.



https://github.com/patrykwozinski/strong_migrations
What are micro frontends anyway?
Tags: watercooler, javascript
Published: 2021-10-29 17:37:48

I have a good bit of experience as a developer, and I still honestly don't understand what micro frontends _are_.

{% twitter 1454114581173899269 %}

Specifically, it seems like they are either just standalone SPAs with links between them, or they are essentially Web Components that are plugged into some site.

Can you all help me out? What are micro frontends? Do you use them? Do you like them?
Let's chat about functional programming...
Tags: functional
Published: 2021-10-29 17:32:58

Let's talk about functional programming, `map`/`reduce`/`filter` and a little bit of a hack to using it's benefits that forms part of it's appeal.

Software Engineers often want to expand their repertoire into learning new languages.  When they do, it takes time, there is often a learning curve, the core libraries may take years to become familiar with, and even getting to a point of basic competence absorbs a lot of time.

`Map`/`Reduce`/`Filter` are a powerful set of tools within a functional approach that can be used in a lot of languages.  Indeed, there are some languages where `map-reduce`(and filter too I suppose) are the main tools that you are expected to use to manipulate data.

## So can we actually use map/reduce/filter as a way to get started quickly in a new programming language?

*Maybe.*

- [ ] If the language supports clean map/reduce/filter at all.
- [ ] If the map/reduce/filter paradigm of the language is clean enough to simply memorize.  I have run across some Inconsistent APIs for map/reduce/filter that make it harder.
- [x] Then maybe you can get to a workable level of effectiveness with map/reduce/filter way, and learn the rest of the language more gradually.

Have you tried getting started with just these parts of a language first?
What was your win this week?
Tags: discuss, weeklyretro
Published: 2021-10-29 17:31:38

---
title: What was your win this 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 there! 


Looking back on this past 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 recipe... or whatever else might spark joy ❤️ 

---

Congrats on your wins! I hope you all have a great day! 

![Dog with sunglasses saying happy friday](https://media.giphy.com/media/Ote7fuZrFEV12yjvs5/giphy.gif)
JavaScript Internal Property`[[]]` 
Tags: javascript, beginners
Published: 2021-10-29 17:20:57

Photo by <a href="https://unsplash.com/@dtopkin1?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Dayne Topkin</a> on <a href="https://unsplash.com/s/photos/private?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
  

Maybe one day you were playing in the dev browser in Chrome, and one day come across something that seemed a bit different. 

You've printed things out to the console, and something odd appears. 

```
function foo() { 
    console.log("Hello")
}
```

```
foo.prototype
{constructor: ƒ}
```

Clicking on the arrow for the constructor, will return an object. 

```
{constructor: ƒ}
constructor: ƒ foo()
arguments: null
caller: null
length: 0
name: "foo"
prototype: {constructor: ƒ}
[[FunctionLocation]]: VM572:1
[[Prototype]]: ƒ ()
[[Scopes]]: Scopes[2]
[[Prototype]]: Object
```

What on earth are those double brackets `[[]]`? 

It's the internal property. In JavaScript, objects have an internal property known as `Prototype`. You can also see that there is a `Scopes` inside of these double brackets as well once clicking inside an object. 

Whenever there are `[[]]` that appear, it's an internal property that can't be accessed by our code. Both `Scopes` and `Prototype` are internal properties of the `foo` object. 

What's pretty cool, and also very helpful when clicking on the `Scopes` internal property, is that when working with some concepts, say, a closure, clicking on the scopes property will show the closure itself. 

```
let f;

const g = function() {
    const a = 23;
    f = function() {
        console.log(a * 2);
    };
};

g();
f();

console.dir(f)

// Returns
ƒ f()
arguments: null
caller: null
length: 0
name: "f"
prototype: {constructor: ƒ}
[[FunctionLocation]]: VM495:3
[[Prototype]]: ƒ ()
[[Scopes]]: Scopes[3]
```

Clicking on the `Scopes` internal property, we can see where the closure lives. 

```
[[Scopes]]: Scopes[3]
0: Closure (g) {a: 23}
1: Script {f: ƒ, g: ƒ}
2: Global {0: Window, window: Window, self: Window, docum...
```

It's pretty cool, isn't it? 

## Further Reading
[StackOverFlow](https://stackoverflow.com/questions/11003021/what-internal-property-in-ecmascript-is-defined-for)

[JavaScript Info - Private Protected Properties](https://javascript.info/private-protected-properties-methods)
Set Python3 as a default on MacOS
Tags: python, macos
Published: 2021-10-29 17:14:15

---
title: Set Python3 as a default on MacOS
published: true
tags: python, macos
---

Download the and install the latest stable release from [python.org](https://www.python.org/downloads/macos/)

To set the release as default -

```bash
sudo ln -s -f /Library/Frameworks/Python.framework/Versions/3.10/bin/python3 /usr/local/bin/python
```

To check it worked, open a **new** terminal window and run

```bash
python --version
```

You'll get -

```bash
Python 3.10.0
```

Happy coding! 🚀