teleren/devto huggingface dataset:
TIL: How to use async | pipe in Angular
Tags: angular, todayilearned
Published: 2020-10-23 15:56:00

I have a service that calls the api and gets some data to use it on my `MessagePreview` component.

####message-preview.component.ts
```typescript
import { Component } from '@angular/core';
//other imports

@Component({
  selector: 'message-preview',
  templateUrl: './message-preview.component.html',
})
export class MessagePreviewComponent  {
  previews$;
  latestValue:PreviewResponse[];
  constructor(private previewService: PreviewService){}
  
  ngOnInit(){
    this.previews$ = this.previewService()
          .subscribe(value => this.latestValue = value);
  }

  ngOnDestroy(){
    this.previews$.unsubscribe();
  }
}
```
And then on the `message-preview.component.html` you would use the `latestValue`

###An effective way of using the async pipe
####message-preview.component.ts
```typescript
import { Component } from '@angular/core';
//other imports

@Component({
  selector: 'message-preview',
  templateUrl: './message-preview.component.html',
})
export class MessagePreviewComponent  {
  previews$: Observable<PreviewResponse[]>;
  latestValue:PreviewResponse[];

  constructor(private previewService: PreviewService){}
  
  ngOnInit(){
    this.previews$ = this.previewService();
  }
}
```
Notice here, I do not use the `ngOnDestroy()` hook because I am not subscribing to anything. And on my template, I will use the observable directly with the `| async` like:

####message-preview.component.html
```html
<div>
--
 <ng-container *ngFor="let preview of previews$ | async">
   {{preview.title}}
 </ng-container>
--
<div>
```
This way, I do not have to unsubscribe and can go with writing less code.
Until next time.
Easy version stamp your Angular app🦶
Tags: angular, showdev, productivity
Published: 2020-10-23 15:53:17

Did you ever create bash scripts that you've used in multiple projects to do version stamp your Angular application?

<img width="250" src="https://github.com/xlayers/version-stamp/raw/main/assets/xlayers_stamp.png?raw=true"/>


Today we are very happy to announce 🎉 __**@xlayers/version-stamp**__ 🎉 an Angular Builder that will help you to version stamp your Angular apps.


# How to use version-stamp

1.Navigate to your Angular project

2.Add @xlayers/version-stamp to your project

```sh
ng add @xlayers/version-stamp
```

The package will make some small changes to the angular.json

3.Add the following snippet (only the version property) to your environment files.

```ts
export const environment = {
    production: false,
    version: "_BUILD_HASH_"
};
```

4.Use the version that the packages has provided in your environment properties.

```ts
import { environment } from "../environment";
```

```ts
@Component({
    selector: "xlayers-root"
})
export class AppComponent {
    version = environment.version;
}
```

5.Now you can stamp your app by running

```sh
ng run <your-app>:stamp
```

or use `--version` for a specific version

```sh
ng run <your-app>:stamp --version="1.2.1"
```

6.When we navigate to our `dist` folder we can look at our code and see something that is similiar to the picture below

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

# Thank you

Thank you for reading our article, we hope this article encourages you to try xLayers products as it is fairly easy to use and provides a lot of value in the collaboration between designers and developers.

Would you like to help us with xLayers by contributing? We have issues for first-timers and we are willing to help you in all possible ways. Next to contributing you can help us by donating, this way we can develop more features that are on our roadmap.
What are the Features of Spring Boot?
Tags: career, computerscience, springboot
Published: 2020-10-23 15:53:05

Features of Spring boot-

Auto-Configuration - No need to manually configure dispatcher servlet, static resource mappings, property source loader, message converters etc.

Dependency Management - The different versions of commonly used libraries are pre-selected and grouped in different starter POMs that we can include in your project. By selecting one Spring Boot version we are implicitly selecting dozens of dependencies that we would have to otherwise select and harmonize ourself. Example-

Advanced Externalized Configuration - There is a large list of bean properties that can be configured through application.properties file without touching java or xml config.

Production support- We get health checking, application and jvm metrics, jmx via http and a few more things for free.

Runnable Jars - We can package your application as a runnable jar with embedded tomcat included so it presents a self-contained deployment unit.

Meet The Experts : https://nareshit.com/spring-online-training/
How to create an EC2 Auto Scaling Group with Load Balancing
Tags: tutorial, aws, cloud
Published: 2020-10-23 15:44:14

---
title: How to create an EC2 Auto Scaling Group with Load Balancing
published: true
description: In this video, I walk through the Pluralsight "Cloud Labs" feature and show how to set up EC2 Auto Scaling Groups
tags: beginners, tutorial, aws, cloud
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/nugmiqbxn33c81mbghk6.jpg
---

You can set up EC2 Auto Scaling groups in minutes if you know how. I recently did a live stream showing off Pluralsights new Cloud Labs feature, and we walked through this lab. 

In this video, I walk through creating an EC2 Auto Scaling group on AWS. We will: 

- Create a Launch Configuration
- Create an Auto Scaling Group with a Launch Configuration
- Create a Launch Template
- Edit an Auto Scaling Group to Use a Launch Template
- Configure a Load Balancer Using an Auto Scaling Group

{% youtube 9NY7AO4LHbw %}

No login or membership is required, just push play!

What do you think? Let me know in the comments.
Refactoring code - git rebase
Tags: opensource
Published: 2020-10-23 15:19:41

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

To practice `git rebase` and Refactoring my code, I worked on my [goURL]() repo.

I planned to do three commits with three different refactors.

- extract functions to reuse.
- improve variable names.
- split the util functions to a new file `utils.go`

Extract functions and improving variables go smoothly. However, when I split the util functions, all my code is broken. all my imported library is still on main.go,
I checked all the libraries needed by the new file and deleted the old imports from `main.go`. Then, everything works.

The process of refactoring:

```bash
git checkout -b refactoring master
// refactoring 1
git add .
git commit -m "Extract functions to reuse"

// refactoring 2
git add .
git commit -m "Improve variable names"

// refactoring 3
git add .
git commit -m "split the util functions to a new file utils.go"

// git log to check the commit history
git rebase master -i
// change commits message.
git commit --amend


// merging
git checkout master
git merge refactoring
git push origin master
```

`git rebase` is a way to clean our commit history. we also use `git rebase` to
update our working branch to fetch the latest commit from the remote repo.
TTY::Prompt, TTY not!
Tags: cli, flatiron, tty, ruby
Published: 2020-10-23 15:16:01

I am just finishing up building my first project for Flatiron School this week and of all the new things I learned - which there were A LOT! - I think TTY::Prompt was the most useful and absolutely wonderful!  Now, I want to also take a second to give props to Colorize, Lolize and Rainbow because life is better more colorful!  These gems are also excellent and I recommend each of them.

But TTY::Prompt has been a life-changer for me.  I used this in so many places throughout my project, in many different forms.  This project would have never been the same without it.  And it is so easy to use!  There are tons of options but I will show you a few of the ones I found most useful.

##Prompt.select

Prompt.select was my go to and so versatile.  I used this in so many different ways.  My absolute favorite thing about it was that I could pull in an array from my program to use as the selection options - amazing!  This kept my program fluid and was so easy to write.  
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/de1n1tbuyad25x6swqas.png)

##Prompt.ask

Probably the most straightforward and often needed use would be the Prompt.ask function.  It's simple but it has a ton of additional options if you need them.  You can simply take input from the user, but you can also use this to validate the information given or capitalize it.  Again, it was so easy to use and allows so much flexibility.

###So much more
There were so many other options available that I didn't have reason to use with this program but I can assure you, I will be using TTY::Prompt again.  I can't wait to have reason to use TTY::Mask and change the image used to mask the input!  What an exciting and fun idea for the right website.

Be sure to check it out.  https://github.com/piotrmurach/tty-prompt#ttyprompt

If anyone has any other suggestions of gems I should try out, let me know.  I am always excited to learn new things and keep expanding my grab bag of fun tricks and treats!
Automatically Run Build Script When Switching Branchs Using Git Hooks
Tags: git, gulp
Published: 2020-10-23 15:11:00

This was originally published over on [frankcorso.dev](https://frankcorso.dev/automatically-run-build-scripts-switching-branches-git-hooks.html).

I have recently been working on a project where we had multiple different JavaScript-heavy features being developed. So, there were many times where I switched branches to test out features.

But, I would constantly spend countless time figuring out why the feature wasn't working until I realized I had once again forgotten to build the assets.

So, I started looking into git hooks to see what my options were.

## What are git hooks?
Within git, there are [17 events that fire upon different actions](https://www.git-scm.com/docs/githooks#_post_checkout) being taken. During each event, there is a "hook" that anyone can hook scripts into.

Some of these hooks include:
* post-checkout: Ran after checking out a branch
* post-merge: Ran after a `git pull` is run
* pre-commit: Ran prior to a commit being created
* post-commit: Ran after the commit is created

Each git repo has a `.git/hooks` directory that can contain scripts to be hooked into any of the hooks. You can drop a script that matches a hook's name into this folder.

Since this was a simple gulp command, I used a bash script. But, you could also use other languages, including Ruby or Python.

## Hooking into post-checkout
In order to run code upon switching branches, we need the `post-checkout` hook. This hook fires after you checkout a branch or a file.

Inside the `.git/hooks` directory, I added a new file named `post-checkout`.

The post-checkout script gets called with three parameters:

1. The previous HEAD
2. The new HEAD
3. A flag for if it's a branch that is being checked out. 1 for branch and 0 for not.

Since this also gets called when you check out a file, such as rolling back a file, this can cause a cycle where you roll back a built file, and then it autogenerates the file again. To get around this, I check for the third parameter to make sure it's a `'1'`.

Inside my `if`, I then added our gulp task, which builds all of our assets, `gulp prebuild`.

```
#!/bin/sh
#
# Builds our assets upon checkout
#
# Args passed to this are:
# $1 - Previous HEAD
# $2 - New HEAD
# $3 - 1 if checking out a branch, 0 if checking out something else, such as a file (rollbacks)
#
if [ '1' == $3 ]
then
    echo 'Branch checkout detected. Building assets...'
    gulp prebuild
fi
```

## Next Steps
Now that I have a rough idea of how git hooks work, I could see having scripts for validating commit messages, creating notifications, or automating other build tasks. I also came across articles on automating simple deployments [using the post-receive hook](https://www.digitalocean.com/community/tutorials/how-to-use-git-hooks-to-automate-development-and-deployment-tasks), which I could see one used to build simple websites or even docker containers automatically.
I'm trying to display all products from a category and it's all sub-categories

Tags: laravel, php
Published: 2020-10-23 14:59:02


Here's my categories table structure :

| id | parent_id | name        |
|----|-----------|-------------|
| 1  | NULL      | Vehicles    |
| 2  | 1         | Cars        |
| 3  | 2         | Motorcycles |

but i only get parent and its sub data. i want to get parent sub and subsub data.

here is my category model

public function subproducts()
{
    return $this->hasManyThrough(Product::class, self::class, 'parent_id', 'category_id');
}

public function products() {
    return $this->hasMany(Product::class);
}

}

here is my product

public function categories() { return $this->belongsTo(Category::class, 'category_id'); }

and this is the controller

    $category = Category::with(['products', 'subproducts'])->where('slug', $slug)->first();
    $allProducts = $category->products->merge($category->subproducts);

    dd($allProducts);
Learning JavaScript II 
Published: 2020-10-23 14:53:14

I'm learning JavaScript 30 minutes at a time...

I posted my program from last night on Gitlab [in this new repo](https://gitlab.com/bachmeil/learning-javascript).

My program doesn't do much, and it's obviously not useful to anyone else. It shows you what I learned in the bit of time I put into it last night.

It (sort of) lets you move between two divs, with a box around the active div, using the up and down arrows. You can indent the active div (when it works) with the right arrow. That's it. As I said, it's definitely not anything useful at this point.

It's interesting to me the way you can manipulate the dom. My end goal is going to be an outliner type of notes app with these features:

- Do quick outlining.
- Add and edit text entries.
- Indent/outdent text trees (a text entry box and all of its children) using the keyboard.
- Rearrange text trees using the keyboard.
- Markdown support for text entries, including math.
- Save the current state to a file manually as a new html file.
- Optionally, run a local web server, which would make the saving and loading more convenient.
- Use a version system to determine if the current version in localStorage is newer than the version I'm loading from file. I think timestamps will work for this.

I want to be able to add a quick outline to a repo without a lot of ceremony. With everything in one html file, all I'll have to do is load that file into the browser and start typing. As I said earlier, I probably won't actually use this for anything, but I will learn a lot by implementing these features.
The biggest open-source event is ending soon!
Tags: opensource, react, mongodb, node
Published: 2020-10-23 14:48:48

Hacktoberfest is held on every October (yes, once a year) to celebrate open-source software and allow passionate coders to collaborate & have fun together.

This year, I didn't have a lot of time to really enjoy it because I'd been super busy. As you could see, I had to write 20-50 letters a day before I got a job. After that, I still have to hustle 2 jobs (or more) for my dream.

So I thought, instead of seeking fun alone, why don't I create an opportunity for more developers to enjoy the open-source experience together? Therefore, I launched TrackerBase as an open-source project.

Link: https://github.com/yewyewXD/React-Amazon-Price-Tracker

Now, I officially invite YOU to come and have fun with us. You can make ANY changes or suggest ANYTHING you want, just fork it and make a pull request, the point is to learn not to be afraid of making mistakes!

Wanna become a moderator? Sure! I'd be so happy about that! Just shoot me a DM on Twitter or Insta (@yewyewXD).

Twitter Link: https://twitter.com/yewyewXD

Stay safe, happy weekend!
Cheap and safe webcam cover for MacBook Pro
Tags: security, todayilearned, tips, remote
Published: 2020-10-23 14:48:42

I'm searching to improve my security covering the webcam from malicious intruders and I've searched for alternatives and found a lot of articles showing these little [plastic webcam covers cause serious display damages](https://klgadgetguy.com/2020/07/13/macbook-webcam-cover-damage/) on MacBook Pro.

![Cover Damage](https://dev-to-uploads.s3.amazonaws.com/i/3z2f0c35ynjtbexy1ao9.jpg)

Apple reminds users that the camera is only in use when the green light indicator next to the webcam is turned on and reassures that the camera is engineered in a way that it cannot be activated without the light coming on.

But malicious hackers are not only the problem. If you are working from home, you also want to prevent those awkward mistakes during the conference calls. 

{% youtube 48KjeTeWe7Y %}

Apple, says to use something with the thickness of a printer paper, which is around 0.1mm. You also shouldn’t use a cover that leaves an adhesive residue, and should you use something thick, always remove it before closing the laptop’s lid.  

The answer isn't 42, is an apple, a real apple fruit.

![Appple Sticker](https://dev-to-uploads.s3.amazonaws.com/i/l5pft7aix5ec2b9hsrgb.jpg)

Yes, those little and tiny stickers can be made of various products, though vinyl and plastic, but the most important thing is that don't leave an adhesive residue.

So I've decided to use it as a webcam cover and works perfectly. Can be easily removed to use the webcam on conferences and stick again multiple times.

![Fruit Sticker](https://dev-to-uploads.s3.amazonaws.com/i/u3r2rb1t8b3jzevp3nrv.jpg)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/5wsroe8xa2wed0xp2er1.jpg)

I know that it's not glamorous, but it's another way to reuse those none biodegradable stickers and not throw them directly into the garbage. 

They Aren't exclusively for Mac, can be used in computers and mobiles from all brands.

___

**That’s All Folks!**
**Happy Coding** 🖖

[![beer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mkgsx4aw6qn9i9ax6as9.png)](https://github.com/sponsors/deinsoftware)
Code Smell 04 - String Abusers
Tags: codenewbie, tutorial, codequality, learning
Published: 2020-10-23 14:46:07

*Too many parsing, exploding, regex, strcomp, strpos and string manipulation functions.*

> TL;DR: Use real abstractions and real objects instead of string accidental manipulation.

# Problems

- Complexity
- Readability
- Maintainability
- Lack of Abstractions

# Solutions

1) Work with objects instead.

2) Replace strings with data structures dealing with object relations.

3) Go back to Perl :) 

4) Find [Bijection](https://dev.to/mcsee/the-one-and-only-software-design-principle-3086) problems between real objects and the strings.

# Examples

-Serializers

-Parsers

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/19b5965879d11e6c185d4591add24042)
```php
<?

$schoolDescription = 'College of Springfield';

preg_match('/[^ ]*$/', $schoolDescription, $results);
$location = $results[0]; // $location = 'Springfield'.

$school = preg_split('/[\s,]+/', $schoolDescription, 3)[0]; //'College'
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/9aea4a3d401b7e3c2e80101ff348dfa6)
```php
<?

class School {

    private $name;
    private $location;

    function description() {
        return $this->name . ' of ' . $this->location->name;
    }

}
```

# Detection
Automated detection is not easy. If code uses too many string functions, it can trigger a warning.

# Relations

- Primitive Obsession

# More info

# Tags

- Mapping

# Conclusion

Don't abuse strings. Favor real objects. Find absent protocol to distinguish them from strings.

# Credits

Photo by <a href="https://unsplash.com/@nshuman1291">Nathaniel Shuman</a> on <a href="https://unsplash.com/">Unsplash</a>

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}

*Last update: 2021/06/03*
Que tal aprender AKS com este curso GRATUITO?
Tags: azure, containers, kubernetes, video
Published: 2020-10-30 17:15:06

---
title: Que tal aprender AKS com este curso GRATUITO?
published: true
date: 2020-10-23 14:34:51 UTC
tags: azure,containers,kubernetes,video
canonical_url: https://blog.lsantos.dev/que-tal-aprender-aks-com-este-curso-gratuito/
cover_image: https://raw.githubusercontent.com/khaosdoctor/blog-assets/master/images/2020/10/EkjeIGqWAAA9kHe.jpeg
---

Na semana passada divulguei em meu Twitter que tinha acabado de lançar um curso **gratuito** de Kubernetes com AKS como vocês podem ver no tweet aqui a seguir

> Estou super feliz de anunciar que hoje acabou de ser lançado meu curso sobre [#Kubernetes](https://twitter.com/hashtag/Kubernetes?src=hash&ref_src=twsrc%5Etfw) usando [#AKS](https://twitter.com/hashtag/AKS?src=hash&ref_src=twsrc%5Etfw). Esse é um curso GRATUITO pra você que quer aprender a usar essa excelente ferramenta e dar mais escalabilidade para suas aplicações! [https://t.co/OrTgUJzKLa](https://t.co/OrTgUJzKLa) [pic.twitter.com/bPWToHdJ1d](https://t.co/bPWToHdJ1d)
> 
> — Lucas Santos (@\_StaticVoid) [October 19, 2020](https://twitter.com/_StaticVoid/status/1318175063116451841?ref_src=twsrc%5Etfw)

<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

Não poderia estar mais feliz de divulgar este curso porque, além de ele ser gratuito, ele também é super completo. A grade que criei para o desenvolvimento dele cobre desde Docker até o seu primeiro deploy com Kubernetes passando por quase todos os workloads mais importantes!

Além disso, estou super feliz de que ele tenha sido publicado em um canal tão sensacional como o **Channel9**! O canal de cursos e vídeos da própria Microsoft!

[

Maratona AKS: Tudo sobre Kubernetes de A a Z | Channel 9

Neste bootcamp, aprenderemos os conceitos básicos de contêineres, Docker, Kubernetes, Helm e outras ferramentas para permitir que você assuma o controle de seus aplicativos criando, gerenciando e mant

 ![Que tal aprender AKS com este curso GRATUITO?](https://channel9.msdn.com/favicon-129x129.png)Lucas SantosChannel 9

 ![Que tal aprender AKS com este curso GRATUITO?](https://sec.ch9.ms/ch9/661b/9a6c6d1c-36cd-40ca-a8a6-c88aef8b661b/AKSBootcampPr%C3%A9M%C3%B3duloIntrodu%C3%A7%C3%A3odocursoeapresenta%C3%A7%C3%A3_960.jpg)
](https://channel9.msdn.com/Series/AKS-Bootcamp-From-zero-to-container-hero?WT.mc_id=containers-9948-ludossan)

Se você quiser ir lá aprender mais sobre Kubernetes, aproveita e já assiste este curso e me dê os feedbacks através dos comentários deste artigo ou então nas minhas redes sociais (você pode encontrar todas elas no topo do blog ou então no [meu site](https://lsantos.dev)) eu vou ficar super feliz em saber o que está certo e o que posso mudar para continuar produzindo um conteúdo de cada vez mais qualidade para todos!

Muito obrigado pessoal!