teleren/devto huggingface dataset:
TIL: How to use form builder to create groups in Angular
Tags: angular, todayilearned
Published: 2020-10-30 14:40:56

We can use the `formBuilder` service to group all the form fields. I start with injecting `FormBuilder` from `angular/forms` and inject in my `contactComponent`
```typescript
import { FormBuilder } from '@angular/forms';

@Component({
  selector: "contact",
  templateUrl: "./contact.component.html",
  styleUrls: ["./contact.component.css"]
})
export class ContactComponent implements OnInit {
  constructor(private fb: FormBuilder) { }
 ...
}
``` 
Since it is a contact form, I have name, email, and message as the form fields. So I create a form group as
```typescript
 contactForm = this.fb.group({
    name: [''],
    email: [''],
    message: ['']
  });
```
I then can eventually add validation for each of the fields
```typescript
contactForm = this.fb.group({
    name: ['', Validators.required],
    email: ['', Validators.required],
    message: ['', Validators.required]
  });
``` 
Then you would basically use it in the input as 
```typescript
<input type="text" formControlName="name">
```
And that's it. There seems to be a lot of things that you can do with the form, but that will be a post for another day.
How to encode and decode URL with Javascript
Tags: javascript, webdev
Published: 2020-10-31 02:18:11

---
title: How to encode and decode URL with Javascript
published: true
date: 2020-10-30 14:40:43 UTC
tags: javascript, webdev
canonical_url: https://phongduong.dev/blog/how-to-encode-and-decode-url-with-javascript/
---
When you request a third-party API, you may pass parameters that contain special characters. This may cause errors for your request. To avoid this situation, you need to encode the URL before sending the request. 

## Encode URL

Javascript has 2 functions that help you encode a URL:

* `encodeURI()`: encode a full URL. It doesn't encode `~!@#$&*()=:/,;?+'` 
* `encodeURIComponent()`: encode a part of the URL. It doesn't encode `-_.!~*'()` 

## Examples

### Encode URL

```javascript
const URL = "https://phongduong.dev/blog/kiểm tra tiếng Việt"

console.log(encodeURI(URL)) // https://phongduong.dev/blog/ki%E1%BB%83m%20tra%20ti%E1%BA%BFng%20Vi%E1%BB%87t
console.log(encodeURIComponent(URL)) // https%3A%2F%2Fphongduong.dev%2Fblog%2Fki%E1%BB%83m%20tra%20ti%E1%BA%BFng%20Vi%E1%BB%87t
```

### Encode parameters

```javascript
const URL = "https://phongduong.dev"
const URLParam = "https://example.com"
const queryParam = "Đây là tiếng Việt"

console.log(`${URL}?url=${encodeURIComponent(URLParam)}`) // https://phongduong.dev?url=https%3A%2F%2Fexample.com
console.log(`${URL}?q=${encodeURIComponent(queryParam)}`) // https://phongduong.dev?q=%C4%90%C3%A2y%20l%C3%A0%20ti%E1%BA%BFng%20Vi%E1%BB%87t
```

## Decode URL

Javascript provides `decodeURI()` and `decodeURIComponent()`to decode a URL. You can use them to decode the corresponding encoding function's result

```javascript
console.log(decodeURI("https://phongduong.dev/blog/ki%E1%BB%83m%20tra%20ti%E1%BA%BFng%20Vi%E1%BB%87t")) // https://phongduong.dev/blog/kiểm tra tiếng Việt
console.log(decodeURIComponent("https%3A%2F%2Fphongduong.dev%2Fblog%2Fki%E1%BB%83m%20tra%20ti%E1%BA%BFng%20Vi%E1%BB%87t")) // https://phongduong.dev/blog/kiểm tra tiếng Việt
```

## Summary

If you want to encode a full URL, use `encodeURI()`. 

If you want to encode a part of the URL, use `encodeURIComponent()`. 

To decode, use the corresponding function.
Code Smell 11 - Subclassification for Code Reuse
Tags: oop, codenewbie, tutorial
Published: 2020-10-30 14:28:07

*Code reuse is good. But subclassing generates a static coupling.*

TL;DR: Favor composition over inheritance. Always. Period.

# Problems

- Coupling

- Maintainability

# Solutions

- Favor composition.

# Exceptions

- If hierarchy follows the principle *behaves like* then it is safe.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/4f53d085c8b566936c04483064e25ed9)
```java
public class Rectangle {
    
    int length;
    int width;
    
    public Rectangle(int length, int width){
        length = length;
        width = width;
    }
   
    public int area(){
        return length * width;
    }
}

public class Square extends Rectangle {
     
     public Square(int size){
        super(size, size); 
    }
   
    public int area(){
        return length * length;
    }
}

public class Box extends Rectangle{    
      
}
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/9f0082db40c2ab590b2b6ea9702bbb22)
```java
abstract public class Shape{
    
    abstract public int area();
}

public final class Rectangle extends Shape {
    
    int length;
    int width;
    
    public Rectangle(int length, int width){
        length = length;
        width = width;
    }
   
    public int area(){
        return length * width;
    }
}

public final class Square extends Shape {
     
     int size;
      
     public Square(int size){
        size = size; 
    }
   
    public int area(){
        return size * size;
    }
}

public final class Box {
    
    Square shape;
    
    public Box(int size){
        shape = new Square(size); 
    }
    
    public int area(){
        return shape.area();
    }
}
```

# Detection

- Overriding can issue warnings when subclassing concrete methods.
- Deep Hierarchies (more than 3 levels) are also a clue of bad subclassing.

# Tags

- Composition

# Conclusion

In legacy systems is very common to have *Deep Hierarchies* and *method overriding*, we need to refactor them and subclass by *essential* reasons and not implementative ones.

# Relations

{% post https://dev.to/mcsee/code-smell-58-yo-yo-problem-ej9 %}

# More info

- [Liskov Substitution](https://en.wikipedia.org/wiki/Liskov_substitution_principle)

# Credits

Photo by <a href="https://unsplash.com/@brandgreen">Brandon Green</a> on <a href="https://unsplash.com/s/photos/tree">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/15*
GraphQL Code Generator in a monorepo
Tags: graphql, monorepo, devops
Published: 2020-10-30 14:20:47

> Disclaimer: this post assumes you have knowledge of how to setup a monorepo

Recently, I decided to use [graphql-code-generator](https://graphql-code-generator.com/) because I was tired of manually writing my schema definition and then writing the typescript types _every single time_.

With graphql-code-generator, I only have to write out the schema and the rest is, you probably guessed it, generated.

Using it within a monorepo allows you to make it so there's a single source of truth for all your API!

It will look a little something like this:

![Diagram showing relation between the API and the monorepo packages](https://dev-to-uploads.s3.amazonaws.com/i/1jyzo7n1mjod6d0hltzl.png)

Let's map out our (basic) monorepo structure:

 ```
monorepo
 ┣ packages
 ┃ ┣ api 
 ┃ ┃ ┣ src
 ┃ ┃ ┃ ┣ index.ts 
 ┃ ┃ ┃ ┗ schema.gen.ts
 ┃ ┃ ┗ codegen.yml
 ┃ ┣ client
 ┃ ┣ server
```

Here's how the api `codegen.yml` file will look

```yaml
schema: http://localhost:4000/graphql
generates:
  ./src/schema.gen.ts:
    plugins:
      - typescript

```

> I add `.gen.` to all generated files to make it easy to add in `.gitignore`

The really cool part is when our server is running, any changes to the schema will automatically be tracked when running `graphql-codegen --w` inside the api package.

Now all you have to do is import `@monorepo/api` from your client or server and you'll have access to all the typescript types.
Refactoring: Change Working Code?
Tags: typescript, javascript
Published: 2020-10-30 13:59:32

Assume we have a "Thing" type, with a constructor that already works, it is considered "Done" in Agile. A new change comes in whereby another field needs to be added. Do we change the constructor to include the new field?

Answer: Maybe, but we don't have to do that.



```typescript
/** Creates a new Thing 
* @returns a Thing */
function getThing(
person,
address,
delivery,
account):Thing {
   let thing = new Thing(
      person,
      address,
      delivery,
      account     
   );
 return thing;
}
   
```
Thing has been integrated for 2 years into existing production code. A new requirement comes along to create a "Delinquent Delivery Thing" due to a production delay.

**Scenario 1**
Relies on creating a new Class named Delinquency, which will contain Thing (our already working code). If we were to add a new property to the Thing constructor it would have to be optional to stop compile errors in existing code. This is not optimal.

```typescript

function getDelinquentThing(
  // Assumes we have a Class named Delinquency
  person,
  address,
  delivery,
  account, 
  delinquency
) : Delinquency {
    let thing = getThing(
  person,
  address,
  delivery,
  account
);
 let containedDelinquency = 
   new Delinquency(
     thing, 
     delinquency
   );    
}
```

**Scenario 2**

Appends a runtime property to the Thing class.
```typescript

function getDelinquentThing(
  // We append the property
  person,
  address,
  delivery,
  account, 
  delinquency
){
    let thing = getThing(
  person,
  address,
  delivery,
  account);
    thing.delinquency = delinquency

    
}
```
Scenario 2 has future liabilities. There's a property attached to a Type that is not discoverable.  This means that developers, down the road only know about the Thing type.  For experienced developers, this is not a problem, for new folks this can be a major tripping point. ***Finding properties in JavaScript is not a problem, it's just knowing when to look for them***.

**Don't Change Working Code**

Example of a change to working code.

```typescript
class Thing{
 person:Person;
 address:Address;
 delivery:Delivery;
 account:Account;
 // This is a change to working code
 delinquency: Delinquency;
}
```
Many will say; this is not a problem to do this. Indeed it's typically not an issue, due to separation of concerns, we simply added a new property in the Thing object. Code that doesn't know about the new property will continue to work as it did.

This is only true ***after we fix all the compile errors, which forces a lot of changes to working areas that may not care about delinquency at all***.

In keeping with "Open/Closed" principle, we should favor Scenario 1. 

JWP2020 Don't Change Working Code
Free Ask Me Anything Session with the speakers of Code Mesh
Tags: conferences, meetups, learning
Published: 2020-10-30 14:17:37

---
title: Free Ask Me Anything Session with the speakers of Code Mesh
published: true
description: Join speakers from a variety of technologies for an ask me anything session. 
tags: conferences,meetups,learning
//cover_image: https://direct_url_to_image.jpg
---

Hey All,

On Monday 2 November we will be hosting a free Ask Me Anything session with a number of the speakers for Code Mesh. Including Ron Pressler, who is the technical lead for Project Loom, which aims to add delimited continuations, fibers and tail-calls to the JVM.

The event will be hosted by Francesco Cesarini, Found of Erlang Solutions and O’Reilly published author of Designing for Scalability with Erlang/OTP and Erlang Programming

Register for free at https://www2.codesync.global/code-mesh-v-ask-me-anything-registration
React Ref to add className
Tags: react, beginners, webdev, javascript
Published: 2020-10-30 14:17:12

![React](https://dev-to-uploads.s3.amazonaws.com/i/loqu9gk3snppy74fchny.png)

Hey there React developers! Wanna Know how to add className dynamically with some really cool example? Then you are in right place. Go through the post to understand in-depth.  

### What is **React**?  
   React is a JavaScript library for building user interfaces.
Click [here](https://reactjs.org/) to know more.

### What is **React Ref**?
   Refs provide a way to access DOM nodes or React elements created in the render method.
Click [here](https://reactjs.org/docs/refs-and-the-dom.html#gatsby-focus-wrapper) to know more.

Let's consider an example where you create a list of buttons using the map function.

```javascript
const buttonsArray = ['Button 1', 'Button 2' , 'Button 3']
buttonsArray.map((button)=>{
      return(
   <button>{button}</button>
   )
 }
)
```
Now let's create *ref* to list of buttons. I have created refs as “callback refs”  

```javascript
const buttonsArray = ['Button 1', 'Button 2' , 'Button 3']
buttonsArray.map((button,index)=>{
    return(
    <button ref={a => this.buttonElement[index] = a} >{button}</button>
  )
 }
)
```

Along with this, you need to declare "this.buttonElement" inside the constructor.  

```javascript
 constructor(props) {
    super(props);
    this.buttonElement = [];
  };
```

Now starts the magic, let's consider you have written all the necessary CSS. From the list of buttons, you want the first button to be active on page loading. How to make it? Check the below code... 
*considering "active" is the CSS className*

```javascript
   componentDidMount() {
    this.buttonElement[0].className = this.buttonElement[0].className+"active";
  }
```

You can also add different styles for all 3 buttons... 

```javascript
   componentDidMount() {
    this.buttonElement[0].className = this.buttonElement[0].className+"active";
    this.buttonElement[1].className = this.buttonElement[1].className+"foo";
    this.buttonElement[2].className = this.buttonElement[2].className+"bar";
  }
```

####Explaination:  
   'this.buttonElement' is a list of buttons so in order to make the first element to be active we added 'active' className to index=0 element. 

####Extra: 
   You can also make a click event to the first button. 
```javascript
   componentDidMount() {
    this.buttonElement.click();
  }
```
If you have need of the above code, then you don't need to add className, because the click event in-turn make the button to active and CSS will take care of that condition.

Here just to make the code snippet understandable, I have implemented using a button. You can make use of any HTML element or any event.

Thank You,
Hacktoberfest 2020 - a mini overview
Tags: hacktoberfest, opensource
Published: 2020-10-30 14:12:01

---
title: Hacktoberfest 2020 - a mini overview
published: true
tags: hacktoberfest, opensource 
---

As October comes to its end, it's time look back to do some reflection.
### Hack-tober 💻

One of the most interesting things that happened this month is my first participation in contributing to open-source software, thanks to [Digital ocean](https://www.digitalocean.com/) and their (now famous) event - Hacktober fest.
Open source always seemed so interesting to me. First, because of the concept itself, but also because the community around this software seemed very strong, very connected and... very *open* (pun intended).🙈 You could always find a bunch of resources and guides on how to start contributing. The only thing I wasn't able to find was - courage!

### Everybody can do it!

I somehow felt like open source was reserved for super productive developers and amazing computer scientists that can find additional time during their busy days and devote themselves to making the world a better place. Last year I also wanted to participate in Hacktoberfest, but wasn't sure if I'd fit in, or how to even start.

But, in this short yet insightful journey I learned that everybody can participate, if they want to. There are so many different repos you can work on. Hacktoberfest even compiled a [comprehensive list of websites](https://hacktoberfest.digitalocean.com/details) that offer easier tasks, which are just right if you are a beginner!

### Starting off 🚀

I wanted to make it easy on myself because I have a busy schedule and I didn't want to commit to something I knew I wouldn't get done. So I picked some easier tasks that I was sure I could get done in time, and my main goal was only to become more familiar with the whole **fork-work-commit** process.
Also, if you are not a web developer, you might find it more difficult to find tasks in your language of choice. There probably are tasks you can do in any language, it's just that the majority of them is oriented towards web development.
For example, I found some tasks for Swift, but they were a bit obscure and would have taken me a lot of time to get familiar with the whole project and think of a solution. Luckily, there are always some *neutral* projects you can work on, you just have to dig deeper. 🤑


### Reflections
Participating in this edition of Hactoberfest was my first step into the world of open source contributing, and I will for sure continue this journey. 
My main goal was to become more familiar with the process, to brush up on my Git skills and just explore and see what Hacktoberfest is all about. And I enjoyed it, so I recommend it to everyone who has the slightest wish to try open source, to give it a chance next year... Even if you have no experience with coding.
Remember: It might be organized in 🎃 Spooktober 🎃 but you **really** have nothing to be scared of!!!

P.S. Did you know that this year, as your reward you could pick planting a tree (instead of a T-shirt)? 🌳
Boo! Pure CSS Halloween card 🎃
Tags: css, github, html, beginners
Published: 2020-10-30 13:57:12

It's Halloween eve now and here's my pure HTML&CSS card on GitHub profile README.md

![GitHub Profile README.md](https://dev-to-uploads.s3.amazonaws.com/i/4ydpg4tcujh4g1cjz0p2.png)

## How to insert full HTML to markdown?
use foreignObject in SVG
```
<svg fill="none" viewBox="0 0 400 400" width="400" height="300" xmlns="http://www.w3.org/2000/svg">
  <foreignObject width="100%" height="100%">
    <div xmlns="http://www.w3.org/1999/xhtml">
      <style>
      .cat {
        position: relative;
        padding-left: 50px;
        height: 300px;
        width: 300px;
      }
     </style>
     <div class="cat" />
   </div>
  </foreignObject>
</svg>
```
use SVG file in markdown as usual image
```
![](./halloween.svg)
```



[live demo](https://github.com/nastassiadanilova)
Injecting meta tags on static HTML doesn't work on dynamically created pages
Tags: gatsby
Published: 2020-10-30 13:55:04

Hi,
I've been researching this problem for a week now and still stumped. I have a website that uses Gatsby with Prismic, and i've got 2 different types of pages: static and dynamically created pages.
Static can include pages like homepage, contact us page, about us page, etc.
Dynamic can include blog posts, services pages, etc.

I've used react-helmet to inject metadata into the pages, but i've since moved to using react-head. This works on static pages, it's included in the SSR version of the pages - but it doesn't work for dynamic pages. I've also put in a console.log on a Layout component that I use on all of the pages, and on the static pages it shows up on the terminal, but on dynamic pages it doesn't.

My config includes the following plugins:
plugins: [
    `gatsby-plugin-catch-links`,
    `gatsby-plugin-sass`,
    `gatsby-plugin-resolve-src`,
    `gatsby-plugin-remove-trailing-slashes`,
    `gatsby-plugin-emotion`,
    `gatsby-plugin-preload-fonts`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: "gatsby-source-prismic-graphql",
      options: {
        repositoryName: "<redacted>",
        linkResolver: () => (post) => `/${post.uid}`,
        omitPrismicScript: true,
      },
    },
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `sample`,
        short_name: `sample`,
        start_url: `/`,
        background_color: `#663399`,
        theme_color: `#663399`,
        display: `minimal-ui`,
        icon: `sample-notext.png`, // This path is relative to the root of the site.
      },
    },
    {
      resolve: `gatsby-plugin-google-analytics`,
      options: {
        trackingId: "UA-107057776-1",
        head: true,
      },
    },
    {
      resolve: "gatsby-plugin-iltorb",
      options: {
        extensions: ["css", "html", "js", "svg", "png", "ttf"],
      },
    },
    `gatsby-plugin-preact`,
    {
      resolve: `gatsby-plugin-html-minifier`,
      options: {
        minifyCSS: true,
        minifyJS: true,
        minifyURLs: true,
        removeEmptyAttributes: true,
        removeComments: true,
      },
    },
    {
      resolve: "gatsby-plugin-html-attributes",
      options: {
        lang: "en",
      },
    },
    {
      resolve: `gatsby-plugin-nprogress`,
      options: {
        color: "#dd8d83",
        showSpinner: false,
        minimum: 0.4,
      },
    },
    `gatsby-plugin-react-head`,
  ],

Please help. Thanks!
Have you ever tried any JetBrains product?
Tags: webdev, discuss, jetbrains, productivity
Published: 2020-10-30 13:37:23

---
title: Have you ever tried any JetBrains product?
published: true
description: 
tags: webdev, discuss, jetbrains, productivity
cover_image: https://vihoth.com/wp-content/uploads/2019/07/danh-muc-san-pham-jetbrains.png
---
From time to time I've seen products like [WebStorm](https://www.jetbrains.com/webstorm/), [PyCharm](https://www.jetbrains.com/pycharm/), [PhpStorm](https://www.jetbrains.com/phpstorm/), [Space](https://www.jetbrains.com/space/), [TeamCity](https://www.jetbrains.com/teamcity/), [IntelliJ](https://www.jetbrains.com/idea/) appearing in the tools list of some devs.

I've also aware their products are pretty pricey, knowing that nowadays you can find a free alternative for almost anything.

Have you ever tried any of their products and is the price/value ratio really good enough to use their stuff?