teleren/devto huggingface dataset:
Tricks To Make Your Own Smart Home With Nodejs
Tags: develope, node
Published: 2023-02-27 13:56:39

Many companies are competing to create the next trendy item you should buy for your home, making the market for smart home devices more cluttered than ever. Yet, as a consumer, it could be difficult to choose a product when determining whether it will work with your setup or other items you might wish to purchase. In addition, you may frequently locate an older, less expensive model of a product that doesn't support HomeKit, such as a TV.

**What are the types of Smart Home Applications?**
While building a smart home automation app, you should think about how many services and features it will enable. This criterion can be used to distinguish between two major categories of applications.

1. A one-purpose app
2. A multi-task app

**What are the Key Elements to Take into Account When Building Your Own Smart Home App?**

It would be most convenient in the long run to have a lot of devices connected to one network that you can control from your smartphone with the help of three essential components.

1. Sensors
2. Actuators
3. Controllers

**Why should you build your smart home system with Nodejs?**

Built on the V8 JavaScript engine used in Google Chrome, Node.js is a robust runtime framework for JavaScript. Node.js is a great option for both software developers and businesses since it makes it simple to create quick, scalable online apps. JavaScript code can be written by developers using Node.js to create more effective and secure apps that are quicker to develop, simpler to maintain, and better suited for mobile devices.

1. A lightweight platform built on JavaScript
2. Easy to create user-friendly applications
3. An open-source platform
4. Minimal load times
5. Scalability
6. Flexibility
7. No Cost
8. Security

**What are the things to keep in mind while developing a smart home system with Nodejs?**

1. Determine your objectives
2. Decide on connected devices
3. Think about security
4. Create an accompanying mobile application
5. Don’t shy away from multiple testing

For those specifically interested in personalizing their home automation experience, using Node.js to develop a personalized intelligent home system is a terrific opportunity and full of possibilities. https://www.allhomerobotics.com/tricks-make-your-own-smart-home-nodejs/
W7HW
Published: 2023-02-27 13:56:34

What is confusing about platforms? 
Platforms can be confusing because theres a lot to change for everything on the code.
How could web components and VanillaJS standards be taught in a way that is more approachable?
I think walk through videos because theres a lot of words thrown at us and we dont know all of it
What did you find easiest to work with on 1st stab? (You don't have to say web components, this is an honest take, if it was Vue cool, but justify it)
I dont think there was anything that I found actaually easier to do. I wanted to say either web components or something that's more simpler but it's all sort of confusing to me.
Think back on the tooling. What parts were confusing? What clicked with you immediately?
I think the most confusing parts was trying to get all my buttons to work. 
What additional readings did you have to do in order to make sense of things.
I was just looking it up on google to try to make it work and chatgpt.
Quick Guide for Following TDD in Node.js TypeScript
Published: 2023-02-27 13:52:53

Suppose we are building a function that calculates the area of a rectangle. We'll start by writing a test for the function:

```
import { calculateRectangleArea } from './rectangle';

describe('calculateRectangleArea', () => {
  it('should correctly calculate the area of a rectangle', () => {
    const area = calculateRectangleArea(3, 4);
    expect(area).toBe(12);
  });
});
```

This test should fail initially, since we haven't yet written the function `calculateRectangleArea`. Next, we'll write the function to make the test pass:

```
export function calculateRectangleArea(width: number, height: number): number {
  return width * height;
}
```

Now that the test passes, we can move on to writing additional tests to ensure that the function works correctly in other cases. For example:


```
describe('calculateRectangleArea', () => {
  it('should correctly calculate the area of a rectangle', () => {
    const area = calculateRectangleArea(3, 4);
    expect(area).toBe(12);
  });

  it('should return 0 if either width or height is 0', () => {
    const area1 = calculateRectangleArea(0, 5);
    const area2 = calculateRectangleArea(3, 0);
    expect(area1).toBe(0);
    expect(area2).toBe(0);
  });

  it('should throw an error if either width or height is negative', () => {
    expect(() => calculateRectangleArea(-1, 5)).toThrow();
    expect(() => calculateRectangleArea(3, -2)).toThrow();
  });
});

```

By following the TDD process, we have ensured that our code is thoroughly tested, and that it meets the requirements specified by the tests. We can be confident that the code is correct and maintainable, and that it will work as expected in a variety of situations.
Criando Adapter para lidar com tokens JWT no CrazyStack Node.js
Tags: node, javascript, typescript, braziliandevs
Published: 2023-02-27 13:52:39

Este é um material auxiliar do bootcamp CrazyStack Node.js do DevDoido. Ele servirá como uma espécie de documentação de alguns códigos vistos durante as aulas apenas como material complementar, garanta já sua vaga no bootcamp [clicando AQUI!](https://crazystack.com.br).

```typescript
import jwt from "jsonwebtoken";
import { TokenDecrypter, TokenGenerator } from "@/application/infra/crypto/protocols";

export class JwtAdapter implements TokenDecrypter, TokenGenerator {
  constructor(private readonly secret: string, private readonly expirationTime: string) {
    this.secret = secret;
    this.expirationTime = expirationTime;
  }
  async decrypt(value: string): Promise<string> {
    return jwt.verify(value, this.secret) as any;
  }
  async generate(_id: string): Promise<string> {
    return jwt.sign({ _id }, this.secret, { expiresIn: this.expirationTime });
  }
}
``` 

Esse código apresenta a implementação de uma classe JwtAdapter que é responsável por gerar e decifrar tokens JWT (JSON Web Tokens). Essa classe implementa duas interfaces TokenDecrypter e TokenGenerator que especificam as ações que um objeto desta classe deve ser capaz de realizar.

A importância de tokens criptografados em uma API de agendamentos online é a segurança da aplicação e dos dados dos usuários. O token JWT permite identificar de forma segura um usuário e garantir que as requisições sejam autorizadas apenas para usuários autenticados. Além disso, os tokens JWT podem ser usados para transmitir informações sensíveis, como informações de perfil de usuário, de forma segura através da aplicação.

Este adapter JWT pode ser utilizado para o mecanismo de token de acesso e token de atualização da seguinte forma:

1.  Token de acesso: Quando um usuário se autentica com sucesso na API de agendamentos online, ele receberá um token de acesso gerado pelo JwtAdapter. Este token pode ser incluído nas solicitações subsequentes do usuário à API como uma forma de autenticação. A cada solicitação, o JwtAdapter pode ser usado para decifrar o token de acesso e verificar se ele é válido e se o usuário está autorizado a acessar a recurso solicitado.
    
2.  Token de atualização: Além disso, o JwtAdapter também pode ser usado para gerar tokens de atualização, que são usados para renovar o token de acesso quando ele expirar. Quando o token de acesso expirar, o usuário pode enviar seu token de atualização para a API, que o decifrará e gerará um novo token de acesso. Dessa forma, o usuário pode continuar a acessar a API sem precisar se autenticar novamente.
    

Em resumo, o JwtAdapter pode ser usado como uma camada de segurança adicional para autenticar usuários e proteger as solicitações à API de agendamentos online.

[LINK DO REPOSITÓRIO](https://github.com/gumiranda/CrazyStackNodeJs)
Test Driven Development (Uncle Bob)
Published: 2023-02-27 13:50:48

Uncle Bob (Robert C. Martin) is a well-known software engineer and author who has written extensively about software development best practices, including Test Driven Development (TDD). 

## TDD Rules

1. You are not allowed to write any production code until you have first written a failing unit test.
2. You are not allowed to write more of a unit test than is sufficient to fail, and not compiling is failing.
3. You are not allowed to write more production code than is sufficient to pass the currently failing unit test.

These three rules form the core of TDD, and they provide a clear and structured approach to writing code. By following these rules, you can ensure that your code is thoroughly tested, that it meets the requirements, and that it is written in a modular and maintainable way.

## Benefits of TDD

Following Uncle Bob's rules for TDD can offer several benefits, including:

1. Improved code quality: By writing tests before writing code, you are forced to think through the problem and ensure that your code is correct and complete. This can lead to higher quality code that is less prone to bugs and defects.
2. Better design: TDD encourages you to write code that is modular, flexible, and easy to test. This often leads to better overall software design and architecture.
3. Faster development: While writing tests can take time upfront, it can ultimately save time in the long run. By catching bugs and defects early in the development process, you can avoid spending time later on debugging and fixing issues.
4. Better collaboration: TDD can improve collaboration between team members by providing a shared understanding of the problem and ensuring that everyone is on the same page. Tests can also serve as a form of documentation, making it easier for others to understand your code.
5. More confidence: When you have a comprehensive suite of tests, you can be more confident in your code and in the changes you make to it. This can lead to more productive development and faster iteration.

Overall, following Uncle Bob's rules for TDD can lead to higher quality code, better design, faster development, improved collaboration, and increased confidence.
Criptografia com Bcrypt no CrazyStack Node.js
Tags: node, javascript, typescript, braziliandevs
Published: 2023-02-27 13:47:24

Este é um material auxiliar do bootcamp CrazyStack Node.js do DevDoido. Ele servirá como uma espécie de documentação de alguns códigos vistos durante as aulas apenas como material complementar, garanta já sua vaga no bootcamp [clicando AQUI!](https://crazystack.com.br).

## Importância da Criptografia de Senhas em uma API de Agendamentos Online

Em aplicações web, especialmente aquelas que lidam com informações sensíveis, a segurança de dados é de extrema importância. Este é o caso de uma API de agendamentos online, onde informações pessoais e financeiras dos usuários são coletadas e armazenadas.

Nesse contexto, é vital proteger as senhas dos usuários para evitar que elas caiam em mãos erradas e sejam utilizadas de forma maliciosa. E é aqui que entra a criptografia de senhas.

A criptografia é uma técnica que transforma informações legíveis em dados ilegíveis, que só podem ser decifrados com a chave certa. Quando se fala em senhas, a criptografia permite que as mesmas sejam armazenadas de forma segura, evitando que elas sejam expostas em caso de invasão de dados.

Desta forma, a criptografia de senhas é uma medida fundamental para garantir a privacidade e segurança dos usuários de uma API de agendamentos online. Além disso, a utilização de bibliotecas especializadas, como a bcrypt, garante a implementação correta e eficiente da criptografia, tornando a aplicação ainda mais segura.

```typescript
import bcrypt from "bcrypt";
import { Encrypter, HashComparer } from "@/application/infra/crypto/protocols";

export class BcryptAdapter implements Encrypter, HashComparer {
  constructor(private readonly salt: number) {
    this.salt = salt;
  }
  encrypt(value: string): Promise<string> {
    return bcrypt.hash(value, this.salt);
  }
  compare(password: string, hashedText: string): Promise<boolean> {
    return bcrypt.compare(password, hashedText);
  }
}
``` 

Este código apresenta uma classe BcryptAdapter que implementa duas interfaces: Encrypter e HashComparer. Esta classe é responsável por fornecer suporte ao uso do pacote bcrypt para a criptografia de dados e verificação de hashes.

A classe possui um construtor que recebe o número de sal como parâmetro e o atribui à propriedade "salt". Os métodos "encrypt" e "compare" são implementados com base nas funções do pacote bcrypt "hash" e "compare".

O método "encrypt" recebe uma string como parâmetro e retorna uma Promise com o hash resultante da criptografia da string com o salt especificado.

O método "compare" recebe uma string de password e uma string de hashedText como parâmetros e retorna uma Promise com um booleano indicando se a password é igual ao texto criptografado.

[LINK DO REPOSITÓRIO](https://github.com/gumiranda/CrazyStackNodeJs)
Kafka & Docker Golden Finds
Tags: kafka, tutorial, docker, articlefinds
Published: 2023-02-27 13:44:18

Hey there👋! For your attention: list of awesome Kafka & Docker-compose articles/tutorials. Hopefully, I will save someone's evening or two from the struggle🤗

1. [Docker-compose cookbook](https://lnkd.in/dWWu7Vta) 
One of the most fabulous cheat sheets I ever saw! In this repo, you will find almost every possible set-up of docker-compose for popular services, including Kafka😉

2. [Kafka Security set-ups in Kubernetes](https://github.com/confluentinc/confluent-kubernetes-examples/tree/master/security)
Great set of examples of Confluent Kafka configurations for different types of authorization

3. [Grokking Kafka Listeners with Confluent](https://www.confluent.io/blog/kafka-listeners-explained/) 
Old but good. great explanation of Kafka Listeners with real-life examples and pretty drawings (if you're a visual person -- this article will close a lot of gaps for you)

4. [Troubleshooting connection for all possible set-ups of your Kafka ](https://www.confluent.io/blog/kafka-client-cannot-connect-to-broker-on-aws-on-docker-etc/)

How to connect to the broker running in a container from the local host? From the same container? From a different machine? Anything U wish😉


P.S. Seems as if Kafka wouldn't let me go easily, so get yourself comfortable, this series has the tag "to be continued"😁 Cheers!
Repository genérico no CrazyStack Node.js
Tags: node, javascript, typescript, braziliandevs
Published: 2023-02-27 13:43:09

Este é um material auxiliar do bootcamp CrazyStack Node.js do DevDoido. Ele servirá como uma espécie de documentação de alguns códigos vistos durante as aulas apenas como material complementar, garanta já sua vaga no bootcamp [clicando AQUI!](https://crazystack.com.br).

A aula de Repository genérico trata sobre a criação de uma classe abstrata "Repository" que é utilizada como base para a criação de repositórios de dados. Esta classe define os métodos básicos que um repositório deve ter, como:

1. Adicionar um item
2. Atualizar um item
3. Incrementar valores de um item
4. Deletar um item
5. Buscar um único item
6. Buscar todos os itens
7. Buscar itens com paginação
8. Contar itens
9. Agregar dados

Essa classe abstrata ajuda a manter o padrão de programação, ajudando na criação de repositórios mais consistentes e fáceis de manter. Além disso, é possível herdar da classe Repository e implementar funcionalidades específicas, tornando a criação de repositórios mais rápida e eficiente.

```typescript
export abstract class Repository {
  abstract add(data: any): Promise<any>;
  abstract update(query: any, data: any): Promise<any>;
  abstract incrementOne(query: any, data: any): Promise<any>;
  abstract deleteOne(query: any): Promise<any>;
  abstract getOne(query: any): Promise<any>;
  abstract getAll(query: any): Promise<any>;
  abstract getPaginate(
    page: number,
    query: any,
    sort: any,
    limit: number,
    projection: any
  ): Promise<any>;
  abstract getCount(query: any): Promise<any>;
  abstract aggregate(query: any): Promise<any>;
}
``` 
Classe abstrata Repository é uma classe base para criação de repositórios de dados. Ela define os métodos básicos que um repositório deve ter, como adicionar, atualizar, incrementar, deletar, buscar por um único item, buscar todos os itens, buscar com paginação, contar itens, e agregar dados. Esses métodos são todos abstratos e devem ser implementados em classes filhas para funcionar corretamente


[LINK DO REPOSITÓRIO](https://github.com/gumiranda/CrazyStackNodeJs)
Contract LoadAvailableTimesRepository no CrazyStack Node.js
Tags: javascript, node, typescript, braziliandevs
Published: 2023-02-27 13:40:33

Este é um material auxiliar do bootcamp CrazyStack Node.js do DevDoido. Ele servirá como uma espécie de documentação de alguns códigos vistos durante as aulas apenas como material complementar, garanta já sua vaga no bootcamp [clicando AQUI!](https://crazystack.com.br).

Nesta aula, você aprenderá sobre o contrato de repositório "LoadAvailableTimesRepository". Este contrato representa a interface que deve ser implementada para fornecer a funcionalidade de carregar horários disponíveis. É uma camada intermediária entre a camada de serviço e a camada de armazenamento de dados, que define a funcionalidade que deve ser fornecida pelo repositório de dados para a camada de serviço. A implementação desse contrato fornecerá a abstração necessária para a camada de serviço para acessar os dados de horários disponíveis de maneira genérica e sem se preocupar com a fonte de dados específica.

```typescript
import {
  AvailableTimesModelRepository,
  QueryAvailableTimesRepository,
} from "@/slices/appointment/entities";

export interface LoadAvailableTimesRepository {
  loadAvailableTimes(
    query: QueryAvailableTimesRepository
  ): Promise<AvailableTimesModelRepository | null>;
}
``` 
Esse código importa dois tipos de entidades, AvailableTimesModelRepository e QueryAvailableTimesRepository, ambas de uma pasta específica dentro do projeto. Ele também define uma interface chamada LoadAvailableTimesRepository, que especifica um método chamado "loadAvailableTimes" que deve ser implementado por qualquer classe ou objeto que implemente essa interface. Esse método recebe um parâmetro chamado "query" do tipo QueryAvailableTimesRepository e retorna uma Promessa de um objeto do tipo AvailableTimesModelRepository ou null. A ideia é que essa interface seja implementada por uma classe ou objeto que se comunique com uma fonte de dados (como uma API) para carregar os horários disponíveis de algum serviço.


[LINK DO REPOSITÓRIO](https://github.com/gumiranda/CrazyStackNodeJs)
Data Generator Nuget Package
Published: 2023-02-27 12:00:13

#Objective
This is a cross platform NET Standard 2.0 generator library containing a bunch of generating codes that I needed while developing apps. I hope it will save your development time.

#About
This library is one of DEFC utilities packages that contains several types of data generating, to help the developers minify their codes in easy way with no time. Through this package can :
* Generate GUID.
* Generate Random Symbol.
* Generate Unique Code and compare it to a list.
* Generate Random String with specific length and choose if it is lowercase or uppercase or both.
* Generate Random Number between min and max.
* Generate any Random Code.

#Example
```C#
Install-Package DEFC.Util.Generator --version 1.0.0
```
```C#
using DEFC.Util;
```
```C#
public static string GeneratePassword()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(Generator.RandomString(2, true));//2 lower case random letters
            builder.Append(Generator.RandomString(3, false));//3 uppper case random letters
            builder.Append(Generator.RandomSymbol());//random symbol
            builder.Append(Generator.RandomNumber(1000, 9999));//random number between 1000 and 9999

            return builder.ToString();
        }
        public static string GenerateUser(List<string> ListToCheck)
        {
            char[] CharacterSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890".ToCharArray();
            //Generate user with 20 characters length from a set of character and check if it is already exists in a list of users    

            return Generator.UniqueCode(CharacterSet, 20, ListToCheck);   
        }         
        public static string GenerateClientID()
        {
            char[] CharacterSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890".ToCharArray();

            StringBuilder builder = new StringBuilder();
            builder.Append(Generator.RandomCode(CharacterSet,8));//8 random characters
            builder.Append("-");
            builder.Append(Generator.RandomCode(CharacterSet, 4));//4 random characters
            builder.Append("-");
            builder.Append(Generator.RandomCode(CharacterSet, 12));//12 random characters
            return builder.ToString();
        }
```
iDraw.js, a simple web drawing JavaScript library based on Canvas
Tags: canvas, 2d, javascript, typescript
Published: 2023-02-27 13:37:49

## Introduction

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

This is an open source JavaScript library, using TypeScript to develop a Web drawing framework based on Canvas.

- Website: [https://idrawjs.com/](https://idrawjs.com/)
- GitHub: [https://github.com/idrawjs/idraw](https://github.com/idrawjs/idraw)
- A JavaScript library for drawing and manipulating materials based on pure Canvas.
- You can expand and customize various visual manipulation applications based on iDraw.js, here you can refer to the case [https://idrawjs.com/studio/](https://idrawjs.com/studio/)
- It can draw text, rectangles, circles, pictures, HTML fragments and SVG files, and all of them can be used as drawing elements to generate data in specified formats.

## More information

- GitHub: [https://github.com/idrawjs/idraw](https://github.com/idrawjs/idraw)
- Document: [https://idrawjs.com/](https://idrawjs.com/)
- Playground: [https://idrawjs.com/playground/](https://idrawjs.com/playground/)
- The actual case of Studio based on iDraw.js: [https://idrawjs.com/studio/](https://idrawjs.com/studio/)



## Why I develop iDraw.js

- In order to use pure Canvas features to combine pictures, HTML and SVG as materials to do drawing work.
- In order to try to see what kind of multi-material drawing work can be done with the 2D API of Canvas alone.
- The last is to try to use Canvas as much as possible to manipulate the material.

## iDraw.js's Features

### Draw Text

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

### Draw Rectangle

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

### Draw Circle

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

### Draw Image

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

### Draw SVG Code

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ms5gcj0wqene1393ix9.gif)

### Draw HTML Code

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9yx9bck5e8xwmb1qb08w.gif)


## Next Plan

- Continue to optimize performance
- Extend more drawing element types