teleren/devto huggingface dataset:
NestJS Microservice de Autenticação parte 1
Tags: news, node, nestjs, microservices
Published: 2021-02-05 04:37:58

Inicialmente vamos criar nosso Microservice onde sera chamado a requisição para autenticar o usuário.

Para isso vamos usar o seguinte comando nest new app-auth, essa sera nosso que sera nosso microservice onde iremos registar e autenticar os usuários configurar nosso bootstrap no main.ts.

```javascript
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Transport } from '@nestjs/microservices';

async function bootstrap() {
  const { listen } = await NestFactory.createMicroservice(AppModule, {
    transport: Transport.TCP,
  });
  await listen(() => console.log('Auth Service Up'));
}
bootstrap();
```

vamos usar o TCP mas poderia estar usando kafka ou nats-server(prefiro), vamos criar nosso service onde ficará nossos métodos a ideia é seguir o conceito da arquitetura SOLID que o NestJS nos da inicialmente deixando de forma clara que podemos usar outros padrões de arquitetura dentro do projeto.

para criar nosso service usamos o comando dessa ``` nest g service ``` forma ele ira criar o service para usarmos, é interessante ressaltar que em um microservice podemos ter vários services porem não pode fugir da ideia que um microservice como o próprio nome diz é algo especialista.

Vamos criar uma interface antes de criar os métodos em nosso service, então criaremos uma pasta interfaces e dentro dela a seguinte interface.

```javascript
export interface UserInterfaces {
  name: string;
  email: string;
  password: string;
}

```

Nosso service ficara da seguinte forma.

```javascript
import { Injectable } from '@nestjs/common';
import { UserInterfaces } from '../interfaces/user.interfaces';

@Injectable()
export class UserService {
  private readonly users: UserInterfaces[] = [];

  create(user: UserInterfaces) {
    this.users.push(user);
  }

  find(email: string, password: string): UserInterfaces {
    return this.users.find(
      (Users) => Users.email === email && Users.password === password,
    );
  }
}
```
Vamos deixar a interação com array, futuramente iremos trocar por uma interação com o mongodb, dessa forma também podemos entender que independente do banco de dados utilizado o impacto na aplicação é minimizado.

Vamos agora ao nosso controller, onde a magica tem que acontecer.

```javascript
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import { EventPattern } from '@nestjs/microservices';
import { UserInterfaces } from './interfaces/user.interfaces';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @EventPattern('register')
  register(user: UserInterfaces) {
    console.log('Users', user);
  }

  @EventPattern('login')
  login(email: string, password: string) {
    console.log('Email', email);
  }
}
```
Agora temos nosso microservice de auth estruturado na parte 2 vamos criar a interação do cliente consumindo esses métodos e vamos validar se esta tudo okay.

!["Funcionando"](https://miro.medium.com/max/2400/1*qSw1jauaSBE3v8q3W0IDVg.png)
Mobile App Development Company In UK
Tags: mobileappdevelopment
Published: 2021-02-05 04:36:18

If you are planning to develop mobile apps, you can stop looking further because Tecocraft is the Best Mobile App Development Company In UK. Creating robust Android applications that help your business to grow exponentially and improve revenues. They provide expandable and high performing Android apps that conform to your enterprise and meet all your requirements. If there is any requirement of transferring your app to a different platform or updating the existing one, their team can accomplish the task with utmost proficiency.

Over Website - https://www.tecocraft.co.uk/
*Need Help* - Feedback on my newly created youtube video (Array Map)
Tags: youtubechannel, javascript, tutorial
Published: 2021-02-05 04:05:30

---
title: *Need Help* - Feedback on my newly created youtube video (Array Map)
published: true
description: 
tags: youtubeChannel, js, tutorial
---

My fellow devs/engineers,

Good day! I created my youtube channel about 3 months ago and still trying to put in some effort to create vids when I have spare time. I believe that I can still improve. With that being said, could you please watch my latest video and let me know what am I doing good and what to improve on.

Thank you for your time. (Watch in youtube if possible)

{% youtube ag4UYNKAK8c %}
Taught myself to code 1y ago & recently released my first solo product. My biggest tip for learning...🧠
Tags: beginners, webdev, react, productivity
Published: 2021-02-05 03:57:21

I spent 10yrs in a career of branding/advertising and went from knowing no programming to launching my first product in a year. 

Super proud to share I just hit a personal milestone of 150 paying customers. 

It's been quite an emotional ride but wanted to say if you're just starting out, keep going, it's totally worth it, whether you want to build your own business or switch to a career as a software engineer. 

The biggest tip I can provide is to figure out your learning style. I tried first with books, but I'm terrible with reading and originally gave up telling myself I didn't have time. Then I moved on to watching videos and something magical just clicked.

I learned by doing a short course on Udemy and then just watching a ton of YouTube.

For context, here's what I built: https://llamalife.co

(It's a productivity application which helps provide structure and focus to get work done).

Feel free to ask anything about the journey. 

Not going to lie, it was a hard slog, but extremely happy I did it. And the feeling you get from knowing you built something, by yourself, is amazing :)
February 4th, 2021: What did you learn this week?
Tags: weeklylearn, discuss, weeklyretro
Published: 2021-02-05 03:47:11

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

<center>

![Information flowing through your brain](https://media.giphy.com/media/qKltgF7Aw515K/giphy.gif)

</center>

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

{%tag todayilearned %}

<center>

<!--

And remember, if something you learnt was a big win for you, then you know where to drop it as well.👇👇🏻👇🏼👇🏽👇🏾👇🏿

{%link https://dev.to/devteam/what-was-your-win-this-week-391j %}

![Someone feeling like "Yaaas!"](https://media.giphy.com/media/zBhZiVNNQjfTG/giphy.gif)
</center>

-->
Why I'm using Magic Link for my website login flow.
Tags: magiclink, html, webdev
Published: 2021-02-05 02:33:39

Magic Link is a new upcoming authentication flow that allows user to login using only their email. It is kinda like Facebook login but with email instead. 

You might have seen it when using Slack.

The flow is that you submit your email to the website and it will send a link to your email. Click on it and you are logged in. Just like magic!

I recently started a new project https://www.logname.dev and needed to decide on how I am going to let user register and login.

The easiest way is the normal email and password flow but as a user I hate remembering password for each website I visit.

Another way is using social login and that is by far the easiest method for the user because it only require 1 click.

However, after the recent fiasco from Facebook, as a user I am no longer comfortable on using social login anymore. Who knows what data they can get from it.

So to get the best of both world, I decide to use Magic Link. It is a lot easier than email/password flow and you don't rely on 3rd party service to do it. You also have the added benefit of verifying the user email as they need to use it to login. 

The downside that I can see is that if your email fall under spam, your user might not be aware of it and may think that your login is broken. 

In the next post I'm going to explain more technically on how to implement Magic Link.

Stay Tuned!
Use about:blank to open an empty page with a clean console in the browser
Tags: javascript, productivity, browser, console
Published: 2021-02-05 03:05:00

I happen to use the console in the browser occasionally for trying out some JavaScript code.  But when opening it (Command + Option + J on Mac) on any website, I usually encounter it cluttered, especially as I'm using an ad-blocker.
![Browser Console Cluttered](https://dev-to-uploads.s3.amazonaws.com/i/vo64yptgx4mywdmazq1k.png)
I could type `clear()` to remove all the warnings, but instead I prefer to open a new tab (Command + T) and enter about:blank in the address bar which returns an empty page with a clean console that you can use as a JavaScript playground.
![Browser Console Clean](https://dev-to-uploads.s3.amazonaws.com/i/zsof21gqu0u8o5az9nf2.png)
Glassmorphism Calculator Using HTML CSS & JavaScript
Tags: glassmorphismcalculator, htmlcssjavascript, calculatordesign, csscalculator
Published: 2021-02-05 03:03:39

Hello Readers, welcome to my new blog, today in this blog I'm going to make a calculator using HTML CSS & JavaScript. Earlier I have shared, <a href="https://www.codinglabweb.com/2021/01/responsive-website-with-html-css-glass.html">How To Make a Responsive Website With HTML & CSS</a>, that website was in glassmorphism UI, and now this calculator design also in glass morphism UI.

As we know, a Calculator is a mechanical device that is used to calculate numerical numbers. There are various types and designs of calculators that we can found but the main motive of the calculator is calculation.

As you can see on the given image of this program [Glasss Morphism Calculator], on the webpage. There is one calculator design in glassmorphism UI. All essential buttons are available there like addition, subtraction, multiplication, divide, and so on. These all buttons worked perfectly. Those different sizes of small boxes around that calculator make this glassmorphism design of calculator really awesome. These all small boxes move upward direction continuously.

You Might Like This:
<a href="https://www.codinglabweb.com/2020/12/animated-login-form-using-html-css.html">CSS Animated Login Form</a>
<a href="https://www.codinglabweb.com/2020/11/responsive-login-form-using-only-html.html">Responsive Login Form Form</a>
<a href="https://www.codinglabweb.com/2021/01/responsive-registration-form-in-html-css.html">Responsive Registration Form</a>
<a href="https://www.codinglabweb.com/2020/12/login-form-with-icons-using-only-html.html">Login Form WIth Social Media Icon</a>

Glassmorphism Calculator [Source Code]
You can download all source code from the given link. <a href="https://www.codinglabweb.com/2021/02/how-to-make-calculator-using-html-css.html">Click Here To Download All Source Code</a>
Why Redux-thunk? 
Tags: redux, react
Published: 2021-02-05 02:55:13



_Note: I am writing this to organize my thought and keep some records. Please let me know if something is wrong or have a  better explanation. Thank you!_

---

If you are app does not interact with a server or use API call, you wouldn't need redux-thunk because you don't need async actions. 
Problems come when any server-side(REST API) is involved.

---

#### Why problems?

Redux store only supports synchronous. See Redux documentation below.
*By itself, a Redux store doesn't know anything about async logic. It only knows how to synchronously dispatch actions, update the state... ([https://redux.js.org/tutorials/fundamentals/part-6-async-logic])*

---

#### Can I use API call in a reducer?

No. Reducer is a pure function. It should not cause side effects and it should not directly mutate the state. Anyway, mutating state is an ah oh… in React. 
Redux uses action and reducer to update your app's state. By using these two, people can easily tell how data flow and when your state is changing.
Reducer should copy the state first, then overwrite the value you want to change in the state. 
```
return {
  ...state,
  zip: M0R0O0
}
```

---

#### The solution is here!

Simply saying Redux-thunk is a middleware that allows users to use asynchronous functions when API calls are necessary.
As the document said dispatching action happens immediately, but redux-thunk can make a delay or apply a condition.

'Action' is an object, so 'action creator' should return the action object. Redux-thunk allows an action creator to return a function! Now we can do any asynchronous work.

Let's see how thunk works in code.

```
export const addToMyBar = (cocktail, id) => async (dispatch) => {
    await fetch('http://localhost:5000/', {
    })
    .then((res)=>res.json())
    .then((data)=> {
        dispatch({type: 'ADD_TO_MY_BAR', data});
    })
    .catch(err => console.log(err))
}
```

---

#### How to use?

Install the package

```
npm install --save redux-thunk
```

Import.

```
import { createStore, combineReducers, applyMiddleware, compose  } from "redux";
import thunk from 'redux-thunk';

```
Example )

```
export default () => {
  const store = createStore(
    combineReducers({
      cocktails: cocktailsReducers,
      myBar: myBarReducer,
    }),
    compose(
      applyMiddleware(thunk),
      window.__REDUX_DEVTOOLS_EXTENSION__ && 
      window.__REDUX_DEVTOOLS_EXTENSION__()
    )
  );
  return store;
};
```
Thank you. 
I know this is not well unorganized...
What does a Doctype do?
Tags: programming, html, webdev
Published: 2021-02-05 02:50:05

**Doctype** is the abbreviation for the "Document type". The very first line in every web document should contain a `<!DOCTYPE html>` declaration.

###why do we have to declare the **Doctype**?

The **Doctype** declaration informs the web browser about the type and version of HTML used in building the web document (e.g. HTML5, HTML4.0, XHTML1.0)

###Do all versions of HTML have the same `doctype`?

In the previous version, the **Doctype** refers to **(DTD)** **Document** **Type** **Declaration**. The **DTD** defines the structure and legacy elements of an XML document. Due to the fact that they are based on **(SGML)** **Standard** **Generalised** **Markup** **Language**

* Doctype HTML4.01
 ```<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">```

**Doctypes** for the previous versions require the statement `strict`, `transitional`, `frameset` DTD.

* **DTD** **strict**: contains all HTML elements and attributes, but does **not** **include** presentational or deprecated elements (like font). Frameset are not allowed.
* **DTD** **transitional**: contains all HTML elements and attributes, **including** presentational and deprecated elements (like fonts). Frameser are not allowed.
* **DTD** **frameset**: is equal to HTML4.01 transitional,but allows the use of frameset content.

DTDs tell the parser how to translate the code into what you see on the screen so that the look is uniform across different browsers.

> **Note**: HTML5 is based on its own standard and not SGML, that's why the HTML5 doctype does not require a DTD.

Using the **doctype** declaration is a requirement placed upon us by **(W3C)** **World** **Wide** **Web** **Consortium**; without it, the HTML validators won't work (because they won't know what standard to check your code against) and the browser might render the document in a quirks mode.
NodeJS, ExpressJS,  MongoDB - Paginate - series #04
Tags: node, mongodb, javascript, database
Published: 2021-02-05 02:49:50


## Intro

A quick example on actually a very important feature: "paginate"

Always paginate your resultsets. This protects your system from accidental or malicious oversized resultsets being retrieved.

Pagination is very easy in MongoDB. See the notes section below.


```js
app.post(apiEnum.api_find_artists__songRegex, async (req, res) => {
  let { searchTerm, page } = req.body;

  //#guard 1
  if (isNotBetween(page, 1, 500)) {
    page = 1; //defaultVal
  }

  //#guard 2
  if (isEmptyStrOrNil(searchTerm)) {
    return res.status(400).json([{ error: "the search term was empty" }]);
  }

  const regex = new RegExp(`${searchTerm}`, "i");
  res.json(await mgArr(dbEnum.nlpdb, collEnum.songsColl,
    copyField("searchResult", "albums"),
    unwindArr("searchResult"),
    unwindArr("searchResult.albumSongs"),
    matchRegex("searchResult.albumSongs.song", regex), //54
    paginate(50, page)
  ));
});
```

## Notes

* See series #03 for an explanation of some of these stages like "copyField" and "unwindArr". Here we'll concentrate on the one database query stage, "paginate".

* The above Node.js Express router endpoint returns the paged results of a user search for a string of characters in a song.

* The paginate wrapper func wraps the skip and limit funcs

```js
/**
@func
limit a resultset to a particular requested page of results

@param {number} lim - page size
@param {number} page - page number to retrieve
@return {object[]}
*/
export const paginate = (lim, page) => {
  return [
    skip(lim * (page - 1)), // 50 * 2 gets results 51 to 100
    limit(lim),
  ];
};
```

* The skip and limit funcs both wrap the MongoDB $skip and $limit pipeline stage operators
```js
export const limit = lim => ({ $limit: lim });
```
```js
export const skip = n => ({ $skip: n });
```

* So paginate returns an arr of two stages because it uses two staging operators. You don't have think about that though.
You only have to call paginate and pass in two numbers.

* An example of the resultset in the UI:

![song matches](https://dev-to-uploads.s3.amazonaws.com/i/tkck2mos5831enmwxav7.JPG)



# What's Next

* If you have any questions let me know

* We'll keep moving the needle forward with more enterprise patterns in the subsequent articles in this series
Resolver un problema es solo un inicio
Tags: retos, javascript, programming, spanish
Published: 2021-02-05 02:26:56

Estas últimas semanas he estado resolviendo algunos retos de **[HackerRank](https://www.hackerrank.com/)**, comenzando con lo básico, en teoría no necesito resolverlos porque son básicos y no representan una dificultad significativa y tengo razón, pero **tengo razon por las razones equivocadas**.

No se trata solo de solucionar el problema y que pase las pruebas, también importa el cómo lo solucionas. Algunos de estos sencillos ejercicios, podrían tener una complejidad oculta dependiendo de la solución que pienses.

Por ejemplo el reto de **[Find Digits](https://www.hackerrank.com/challenges/find-digits/problem)**, si te interesa tomate unos minutos en revisarlo e intenta resolverlo, estoy aseguro que no te tomara más de 10 minutos, básicamente son puntos gratis en la plataforma.

Si intentaste resolverlo y tu solución fue convertir el número en algún tipo de objeto iterable, para después iterarlo y evaluar cada uno de los dígitos, es correcto, es una solución viable e incluso optima en la mayoría de los casos.

Pero seguramente es la solución más común que te vas a encontrar, otra solución menos común o ligeramente más complicada, es la que tiene un acercamiento matemático, por ejemplo:

```javascript
function findDigits(n) {
  let result = 0;
  const copyN = n;
  while(n != 0) {
    if(n%10 != 0 && (copyN%(n%10) === 0)) result++
    n = parseInt(n/10);
  }
  return result;
}
```

Soluciona el mismo problema, con algunas ventajas extras como mayor portabilidad entre lenguajes y mejor rendimiento.

A esto me refería al inicio cuando dije **'tengo razón por las razones equivocadas'**, existen muchas manera de solucionar un problema y todas pueden funcionar, pero hay mejores soluciones y en ocasiones ni siquiera las buscamos porque no sabemos que existen.

Como desarrollador de software considero importante el incomodarme a mí mismo cuando algo funciona y creo dominarlo, debería de intentar mejorarlo, al menos por hobby.

Si llevas un par de años como desarrollador y **no pudiste resolver el reto**, deberías de comenzar inmediatamente con algunos más sencillos, esto es bueno para mejorar la lógica y muy común en entrevistas laborales, puede marcar una diferencia en obtener ese puesto que deseas o poder negociar tu salario.
Talk to Ionic about building mobile apps with web tech using native nav controls
Tags: bootstrap, tailwindcss, material, javascript
Published: 2021-02-05 01:07:49

Hello webdevs! I recently joined Ionic to lead our product team.  Are you interested in building iOS and Android apps with seamless navigation using your favorite web frameworks? 

We've been working on a new concept to make building mobile apps simple.  It blends native navigation components with a Capacitor-driven web view. We'd love to get your feedback on it.  If you're interested, please complete this brief survey: https://forms.gle/4UmQZMaGJ45VMWFj6

Thanks and looking forward to speaking with you soon!
echoAR selected as NYC Top 50
Tags: augmentedreality, startup, news, showdev
Published: 2021-02-05 00:52:47

[New York VC Network](https://www.vcnet.nyc/) released it first public NYC Top 50 ranking of startups and echoAR is on the list. Honored to have echoAR featured on this list of amazing NYC-based startups.


New York VC Network is a network of 700+ VCs, LPs, and family offices operating in NYC that share the  ambition to find and support the next world-changing founders in New York.


New York VC Network has compiled its first public NYC Top 50 list of companies that are raising their Seed/Series A right now. The rating New York VC Network committee consists of current and former VCs, angel investors, exited entrepreneurs, and Fortune 500 employees in M&A roles. Companies were rated based on team, traction, and scalability and a Top 50 company had already raised $1.5M on average, compared to $0.8M in the Top 100. 


Read the full NYC Top 50 list  [here](https://www.vcnet.nyc/nyc-top-50/january-2021).


Like/share/retweet the  [@NYVCNet tweet](https://twitter.com/nyvcnet/status/1349006438128115722).



![XXX.jpeg](https://cdn.hashnode.com/res/hashnode/image/upload/v1611283753111/kK8p9qfLf.jpeg)
Dictionaries in Python
Tags: beginners, python
Published: 2021-02-05 00:29:01

**Intro**

In my previous blog I went over 3 of the built in data sets in Python: lists, tuples, and sets. In this blog we will go over another built in Python data set, dictionaries.

**What are Dictionaries?**

Dictionaries are used to store value in a key:value pairs. Dictionaries are unordered, do not allow duplicates, and can be changed.

**Create a Dictionary**

To create a dictionary we use the follow syntax:
```
variable_name = {key:value}

# example
friend_ages = {
    "Rolf": 24,
    "Adam": 30,
    "Anne": 27
}

```

**Access a dictionary item**

To access a dictionary item we use the following syntax:

```
friend_ages = {
    "Rolf": 24,
    "Adam": 30,
    "Anne": 27
}

print(friend_ages["Adam"])  # 30
```

If you need to print the entire dictionary you just use print and the dictionary like this:

```
friend_ages = {
    "Rolf": 24,
    "Adam": 30,
    "Anne": 27
}

print(friend_ages)  # {"Rolf": 24,"Adam": 30,"Anne": 27}
``` 
**Change an Item in a Dictionary**

To change an item in a dictionary we use a similar syntax as accessing an item:

```
friend_ages = {
    "Rolf": 24,
    "Adam": 30,
    "Anne": 27
}

friend_ages["Rolf"] = 21

print(friend_ages["Rolf"]) # 21
```
**Add an Item to a Dictionary**

To add an item to a dictionary we use the following syntax:

```
friend_ages = {
    "Rolf": 24,
    "Adam": 30,
    "Anne": 27
}

friend_ages["Danny"] = 38

print(friends_ages) # {"Rolf": 24,"Adam": 30,"Anne": 27,"Danny":38}
``` 

**Delete an Item**

To delete an item in a dictionary we use the `pop()` method:

```
friend_ages = {
    "Rolf": 24,
    "Adam": 30,
    "Anne": 27
}

friend_ages.pop("Adam")

print(friends_ages) # {"Rolf": 24,"Anne": 27}
``` 

**Loop Through a Dictionary**

Finally to loop through a dictionary we use a for loop:

```
student_attendance = {"Rolf": 96, "Bob": 80, "Anne": 100}

for student in student_attendance:
    print(student)  # Rolf, Bob, Anne

# print every key value pair

for student in student_attendance:
    print(f"{student}: {student_attendance[student]}")
# Rolf: 96
# Bob: 80
# Anne: 100

```