teleren/devto huggingface dataset:
Angular : How to add A fully customizable, one-time password input component in your angular app just in 10 minutes?
Tags: angular, webdev, typescript, npm
Published: 2021-06-05 03:45:51

![Image](https://media.giphy.com/media/TdpKuX7H1KBvvR2Hpu/giphy.gif)  
  
You can use this component in your app and extend it to SMS API, here I will skip API part as it varies from sms provider to provider.  
  
Let's begin to learn how to add otp component in your angular app.  
  
# Step 1 - Install dependency 
```javascript
npm install --save ng-otp-input
```

# Step 2 - Add `NgOtpInputModule` to imports `app.module.ts` something like
```javascript
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { NgOtpInputModule } from 'ng-otp-input';

@NgModule({ 
declarations: [AppComponent], 
imports: [BrowserModule, NgOtpInputModule], 
bootstrap: [AppComponent] 
})
```

Here in your existing app you have to add `import { NgOtpInputModule } from 'ng-otp-input'`; near all existing imports and then add imports in `NgModule` as `NgOtpInputModule` with your existing code.  
  
# Step 3 - Open your choice of component's ts html file where you want to add OTP feature and add below code -
```javascript
<ng-otp-input (onInputChange)="onOtpChange($event)" [config]="{length:5}"></ng-otp-input>
```

All done, OTP component is added.  
  
**Extra Bits**  
When I decided to add this to my own website [https://rajeshkumaryadav.com/#/auth](https://rajeshkumaryadav.com/#/auth) then I thought of to write config in ts file and pass it in html as below, I will write some more code below which I am using in my website like if all digits are entered then validation should be done etc. If you are happy with default feature you can skip this extra bits part.  
  
auth.component.html
```javascript
 <ng-otp-input #ngOtpInput (onInputChange)="onOtpChange($event)" *ngIf="showOtpComponent" [config]="config" ></ng-otp-input>
```

as my config list is long, I will define it in ts file  
  
auth.component.ts
```javascript
otp: string; showOtpComponent = true; 
@ViewChild("ngOtpInput", { static: false }) ngOtpInput: any; config = { allowNumbersOnly: true, length: 4, isPasswordInput: false, disableAutoFocus: false, placeholder: "*", inputStyles: { width: "50px", height: "50px", }, }; 

constructor(private router: Router) {} // OTP Code onOtpChange(otp) { this.otp = otp; // When all 4 digits are filled, trigger OTP validation method if (otp.length == 4) { this.validateOtp(); } } setVal(val) { this.ngOtpInput.setValue(val); } onConfigChange() { this.showOtpComponent = false; this.otp = null; setTimeout(() => { this.showOtpComponent = true; }, 0); } validateOtp() { // write your logic here to validate it, you can integrate sms API here if you want } 
```

Please note that in above config, you can make necessary changes as per your requirements.

# Live Demo - 
[https://rajeshkumaryadav.com/#/auth](https://rajeshkumaryadav.com/#/auth)
Ruby Sinatra with Postgres using Sequel
Tags: sinatra, postgres, sequel
Published: 2021-06-05 03:29:04

In Ruby on Rails we use ActiveRecord as our ORM (Object Relationship Mapper). Sinatra, being a minimalist framework is unopinionated about what Ruby ORM you use to work with to connect to the database of your choice. We will use the ORM, sequel, to connect our small application to a database.

## Requirements

- Have Ruby Installed

- Have postgres installed and have a server running

- Have Sinatra installed `gem install sinatra`

- Have Sequel installed `gem install sequel`

## Set One - Create a Database to Connect To

- open up the postgres shell with `psql`

- create a database `CREATE DATABASE sequel_test;`

- create a super user to connect `CREATE USER myuser WITH SUPERUSER PASSWORD 'myuser';`

- connect to the database `\c sequel_test`

- create a table `CREATE TABLE people (id SERIAL, name VARCHAR(20), age INTEGER);`

- quit psql `\q`

- construct a connection `postgres://myuser:myuser@localhost:5432/sequel_test` (adjust the url as needed for your environment)

## Write our file!

While Sequel has support for migrations, Model Mapping and more, we will keep it simple with raw sql queries just to demonstrate.

 - create a file called server.rb with the following, read the comments for explanation of the code.

 ```ruby
# Import the needed libraries
require 'sinatra'
require 'sequel'

# Connect to our database using our database string
DB = Sequel.connect('postgres://test7:test7@localhost:5432/sequel_test')

#Create a route to see all records
get '/' do
    # create a dataset from the people table
    result = DB[:people]
    # return all the records from the people table as json
    return result.all.to_json
end

#Create a route to add a record
get '/add/:name/:age' do
    # Extract data from URL Params
    name = params["name"]
    age = params["age"].to_i
    # create query to add
    result = DB["INSERT INTO people (name, age) VALUES (?, ?)", name, age]
    # run the insert query
    result.insert(1)
    return "Record added"
end
 ```

Here we're create a couple of basic enpoint to see and add data using sequel. I recommend going deeper into the sequel documentation to learn how to setup migrations and get more typical ORM patterns. But if you just need some quick database access, this is one way to do it very quickly.

- [Sequel Documentation](http://sequel.jeremyevans.net/documentation.html)
Code Smell 75 - Comments Inside a Method
Tags: codenewbie, tutorial, oop, programming
Published: 2021-06-05 03:03:43

*Comments are often a code smell. Inserting them inside a method calls for an urgent refactor.*

> TL;DR Don't add comments inside your methods. Extract them and leave declarative comments just for not obvious design decisions.

# Problems

- Readability

- Kiss

- Low Reuse

- Bad Documentation

# Solutions

1. Extract Method

2. Refactor

3. Remove not declarative comments.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/eae0f716ae595002445926a33fb4d7e8)
```javascript
function recoverFromGrief() {
    // Denial stage
    absorbTheBadNews();
    setNumbAsProtectiveState();
    startToRiseEmotions();
    feelSorrow();

    // Anger stage
    maskRealEffects();
    directAngerToOtherPeople();
    blameOthers();
    getIrrational();

    // bargaining stage
    feelVulnerable();
    regret();
    askWhyToMyself();
    dreamOfAlternativeWhatIfScenarios();
    postoponeSadness();

    // depression stage
    stayQuiet();
    getOverwhelmed();
    beConfused();

    // acceptance stage
    acceptWhatHappened();
    lookToTheFuture();
    reconstructAndWalktrough();
}
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/06f878717d284007d42c0140ccd0cb8e)
```javascript
function recoverFromGrief() {
    denialStage();
    angerStage();
    bargainingStage();
    depressionStage();
    acceptanceStage();
}

function denialStage() {
    absorbTheBadNews();
    setNumbAsProtectiveState();
    startToRiseEmotions();
    feelSorrow();
}

function angerStage() {
    maskRealEffects();
    directAngerToOtherPeople();
    blameOthers();
    getIrrational();
}

function bargainingStage() {
    feelVulnerable();
    regret();
    askWhyToMyself();
    dreamOfAlternativeWhatIfScenarios();
    postoponeSadness();
}

function depressionStage() {
    stayQuiet();
    getOverwhelmed();
    beConfused();
}

function acceptanceStage() {
    acceptWhatHappened();
    lookToTheFuture();
    reconstructAndWalktrough();
}
```

# Detection

This is a policy smell. Every linter can detect comments not in the first line and warn us.

# Tags

- Readability

- Long Methods

- Comments

# Conclusion

Comments are a code smell. If you need to document a design decision, you should do it before the actual method code.

# Relations

{% post https://dev.to/mcsee/code-smell-03-functions-are-too-long-4hji %}

{% post https://dev.to/mcsee/code-smell-74-empty-lines-467h %}

{% post https://dev.to/mcsee/code-smell-05-comment-abusers-2ba5 %}

# Credits

Photo by <a href="https://unsplash.com/@jasonrosewell">Jason Rosewell</a> on <a href="https://unsplash.com/@jasonrosewell">Unsplash</a>
  

* * *

> Don't get suckered in by the comments, they can be terribly misleading: Debug only the code.

_Dave Storer_
 
{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

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/05*
Day3 - input & document
Tags: webdev, html, beginners
Published: 2021-06-05 02:56:12

```
<!DOCTYPE html>
<!-- html 1 to html5.x  -->
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<BODY>
    <!-- self closing tags -->
    <input type="text" />
    <br />
    <!-- password -->
    <input type="password" />
    <br />
    <!-- button -->
    <input type="button" value="Click me!" />
    <!-- datetime -->
    <br />
    <input type="datetime" />
    <br />
    <BUTTON>BUTTON</button>
    <Button>Button</Button>
    <input type="datetime-local" />
    <br />
    <input type="checkbox" />
    <br />
    <input type="radio" />
    <br />
    <textarea></textarea>
    <!-- https://www.w3schools.com/ -->


    <!-- headings -->
    <h1>Lorem Ipsum</h1>

    <h2>Why do we use it?</h2>

    <h6>Why do we use it?</h6>


    <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at
        its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as
        opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing
        packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum'
        will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by
        accident, sometimes on purpose (injected humour and the like).</p>

    <div>
        i am inside a div
    </div>

    <span>its span here</span>
    <br />
    <label>Username</label>
    <br />
    <label>password</label>

    <!-- list tags -->
    <!-- table -->

</body>

</html>

```
How to redirect your hosted GitHub page to a custom domain
Tags: tutorial, github, web, dns
Published: 2021-06-05 02:52:00


If you have your own domain, and a Github account, you could take advantage of redirecting hosted pages to your own domain.

This article is assuming that you already deployed your GitHub page at yourUsername.github.io 

For example, I have a website _www.example.com_ through Google Domains. Below is a screen shot of my custom domain.
![Screen Shot 2021-06-04 at 10.33.04 PM](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rm1g2arzenjkj23p5i7a.png)

To point your GitHub page to your website, first add to your DNS records the url, CNAME record,  and the IP addresses. CNAME means that it's a Custom Domain.

_www_ , _CNAME_, and _'yourGitHubUsername'.github.io_ .

Next, add GitHub's IP addresses under the DNS - with an A record. The A indicates that it's an 'Alias'. 
As of June 2021, the IPs are 
```
185.199.108.153
185.199.109.153
185.199.110.153
185.199.111.153
```
_@_ , _A_ , and the above IP addresses.
You can double check [here](https://docs.github.com/en/pages/configuring-a-custom-domain-for-your-github-pages-site/managing-a-custom-domain-for-your-github-pages-site).

Lastly, under the Settings tab on your GitHub repo for your site, go to the **Pages** section.
In the custom domain field, put your custom domain (_www.example.com_).
_It might take a little time for it to load_
Congrats, you are now pointing your page to your custom domain!

You can also host pages. 
By deploying through Github pages, that are not username.github.io. If you deploy using gh pages, you can add themto your DNS configuration.

For example, if I had www.mywebsite.com, and deployed a page www.mywebsite.com/books
add into your DNS configuration
books , _CNAME_, and _'yourGitHubUsername'.github.io_ .
I am considering to make Vdev.in Open Source
Tags: opensource, react
Published: 2021-06-05 02:30:15

## What is Open Source ?

Open Source is everywhere. The term “Open Source” refers to something people can modify and share because its design is publicly accessible. You can also contribute in any open source project, 28% of casual contributions to an open source are documentation, such as a typo fix, reformatting, or writing a translation.You Just need to track those issues related to the project And try to solve those issues and Open Pull Request.


## Why I am considering to make it Open Source?

3 Months ago, i have started a Project called Vdev.in and which is mainly a portfolio and resume generator website, where you can make your own portfolio website without doing any coding, and now i am considering to make it an open source because i want to make it better with your help.


## Some features of Vdev.in are
1	You can write your own blog	
2	Share your portfolio as an unique link	
3	Download Your resume	
4	You can add your Projects	
5	You can add your achivements	
6	You can connect your social media handle's	
7	You can add some Custom CSS	
8	Receive direct messages from your audience	
9	You can use our Vdev.in api	


## What Next ?

I am planning to move Front end from React.js to Next.js, It is very important in SEO Point of View and many more.

Thanks for reading, 

## Should i make it opensource ?

you can reach to me from my [profile](https://vdev.in/@vimal)
Django Signals
Tags: django, python
Published: 2021-06-05 02:13:46

Signal is one of the useful feature provided by Django, so let's talk about it.
- What is Signal
- How to use Built-in Signal
- How to create a custom one

### What is Signal

Yes, it is the same as you are thinking, as its name suggests "Signal" gives notification to a sender at a specific event.
Let's say you want to get notified every time a guest visited your house.

You can set up a doorbell which will give you a signal that someone has arrived.

Django Signals works in the same manner whenever some event happens it sends a signal to do some defined task.
So you can use Signal when many codes are interested in a particular event.

### Built-in Signals

There are awesome Built-in signals available which you can easily use.
Let's say I want to do something before an instance saved in my Post model.
First of all, I will create a Post model and then import a signal i.e. "pre_save"

- My models.py files will look like this - 

```python
from django.db import models
from django.db.models.signals import pre_save,post_save  #Inbuilt Signals
# Create your models here.

class Post(models.Model):
    title = models.CharField(max_length=30)

    def __str__(self):
        return self.title

def save_post(sender,instance,**kwargs):
    print("Pre save")

pre_save.connect(save_post,sender=Post) # This will trigger after the saving data into Post model
```
So when I save something in Post model I get the message "Pre Save"

![pre_save django signals](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ieldpu2xah7fp6jqwa1o.png)

Similarly you can do something after saving an instance using post_save signals.

Simple...

Here is the list for all [Built-in Django Signals](https://docs.djangoproject.com/en/3.2/ref/signals/) 

There is another famous one request_finished which you can use after a request is finished.

### Custom Signals

So far so good but how we can create a custom one.

wherever you want to use signals you have to import signals and receiver.

Then create an object of Signals class and then define a sender and receiver.
- views.py file
```python 
from django.shortcuts import render,HttpResponse
from django.core.signals import request_finished
from django.dispatch import receiver,Signal
from .models import Post

# Create your views here.
time_stamp = Signal(providing_args=['timestamp'])
def home(request):
    time_stamp.send(sender=None,timestamp="30/05/2021")
    return HttpResponse("Home Page")

## Custom Signal
@receiver(time_stamp)
def own_track(sender,**kwargs):
    print(kwargs)
```

![Easy](https://media.giphy.com/media/zcCGBRQshGdt6/giphy.gif)

So, if you have any suggestions or feedback let me know in the comment.

Thanks for reading.

Cover Image - Photo by <a href="https://unsplash.com/@mero_dnt?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Chinh Le Duc</a> on <a href="https://unsplash.com/s/photos/signal?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
Project 76 of 100 - Intro to @react-three/fiber (Three.js for React)
Tags: react, javascript, npm, 100daysofcode
Published: 2021-06-05 01:38:57

*Hey! I'm on a mission to make 100 React.js projects. Please follow my dev.to profile or my [twitter](https://www.twitter.com/jwhubert91) for updates and feel free to reach out if you have questions. Thanks for your support!*

Link to today's deployed app: [Link](https://100-react-projects-day-76-intro-to-react-three-fiber.netlify.app/)
Link to the repo: [github](https://github.com/jwhubert91/100daysofreact/tree/master/day-76-react-three-fiber)

Today was another shorter project where I followed up on yesterday's post by building a small world using Three.js in React with the @react-three/fiber npm package. It just goes to show you how fast the Javascript world moves that a well-known npm package will get swept up into some other package every couple of months, introducing breaking changes. I guess this is a tradeoff of modularity.

For this project I followed Daniel Bark's [awesome tutorial](https://www.youtube.com/watch?v=FGG0EeMNUl0) called "Building a 3D world in React with Three JS" up to about the 10 minute mark when he introduces physics. The reason I stopped is that there were breaking changes in the npm cannon library since he made the video as well.

It was interesting doing this little tutorial the day after doing a short tutorial on Three JS in vanilla Javascript because you really get a sense for how easy JSX makes your life. 

Rather than creating copies of objects with the `new` keyword and adding them to the scene with an add function, we simply create a JSX function and include them as components within the canvas.

**If you like projects like this and want to stay up to date with more, check out my Twitter [@jwhubert91](https://twitter.com/jwhubert91), I follow back! See you tomorrow for another project.**
SRE Newsletter Issue #30
Tags: sre, devops
Published: 2021-06-05 01:38:01

For the past 6 months, I've been gathering the best DevOps and Site Reliability Engineering articles that were published during the previous week. I wanted to share this with the dev.to group.

In this issue of the SRE Newsletter:
- A Visual DevOps Career Roadmap
- Docker Best Practices
- Config Changes Break Everything
- and more!

[https://www.srenewsletter.com/issues/030/](https://www.srenewsletter.com/issues/030/)
Removing secrets from a git repo
Tags: react, javascript, webdev
Published: 2021-06-05 01:23:26

---
title: Removing secrets from a git repo
published: true
description: Removing a secret from a git is harder than just deleting the file and committing. In this guide I will show how to make sure your secrets never get discovered.
tags: react,javascript,webdev
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8ztwbpeg5vig5069mbth.png
---

Working on [Awesome Devtools](https://awesomedevtools.com) this past week, I decided to make the repo public so others could contribute to it. I had one slight problem though, I had committed my `.env` file which contained secrets I would rather the world not know.

So how would you delete a file like this? Well standard logic says just....delete it. But with git it's not that simple, when you delete something, even though the latest version of your code no longer has this thing, the previous version of your code still do. Simply deleting the file would not work.

There are two ways of deleting a file entirely in git. One way where you preserve your git history, and one where you do not.

## Delete while preserving git history

If you want to delete a file while still preserving your git history, you can do so with a neat recipe from Github.

```bash
# Delete the file
git rm --cached <your_file>

# Commit the change
git commit --amend -CHEAD

# Push the commit
git push

```

## Delete the file and nuke git history

If you're like me and don't really care about your git history for a particular project, you can do it the way I did it and just nuke the file and all the history leading to the file.

First run `git remote -v` to get your current remote.

```bash

➜ git remote -v
origin	git@github.com:sgolovine/awesome-devtools.git (fetch)
origin	git@github.com:sgolovine/awesome-devtools.git (push)

```
Now delete your the file and also delete the `.git` folder. Once you've deleted the file, recreate the git repository locally

```bash

git init
git add -A
git commit -m "Initial Commit"
git remote add origin <url from step 1>

```
Finally do a force push to your remote to overwrite the previous history with `git push -f`

That's it! If you know of a better way to delete a file from git history, leave a comment below and I will update the article. You can find more of my article here and on my [blog](https://sunnygolovine.com/blog)
How to lazy-load images? The easiest way to lazy-load images on your website! 🖼
Tags: beginners, javascript, wordpress, optimization
Published: 2021-06-05 00:38:39

Lazy-loading is the simple process of loading resources only when they are needed. These resources can be anything, from images to stylesheets, fonts, scripts, iframes etc.

This helps improve the performance of your website drastically because client does not have to download the images, videos and other resources when they aren't required. 🥳🎈

We're going to use the package called, "[Lozad.](https://www.npmjs.com/package/lozad)" To lazy-load images. [Lozad.](https://www.npmjs.com/package/lozad) will only add 1 KB to your production 📦! Check out [Bundlephobia ](https://bundlephobia.com/result?p=lozad@1.16.0) 😱 for more info.

We're only going to lazy-load images but [Lozad](https://www.npmjs.com/package/lozad) can handle lazy-loading for srcsets, background images, videos and iframes too. So, let's include the package and start hacking! 🪓 

```
npm i lozad
```
Include [Lozad](https://www.npmjs.com/package/lozad) in your entry or main JavaScript file. Alternatively, you could use [Lozad CDN](https://cdn.jsdelivr.net/npm/lozad/dist/lozad.min.js) if you don't have module bundler set up.

```javascript
import lozad from 'lozad';

// Makes sure to run the library when DOM loads.
document.addEventListener('DOMContentLoaded', () => {
   /**
   * This is all you need to do!
   * Check the link for advanced usages.
   * https://www.npmjs.com/package/lozad
   */
   lozad().observe();
});
```
By default, [Lozad](https://www.npmjs.com/package/lozad) will look for elements with class, "lozad". When the element is about to enter the viewport, [Lozad](https://www.npmjs.com/package/lozad) takes the _data-src_ or other such [Lozad](https://www.npmjs.com/package/lozad) related attributes and assigns it to the _src_ attribute to load the image.

```html
<img class="lozad" data-src="https://example.com/img.jpg" />
```
That's it, you've successfully added support for lazy-loading 🎉🧨🎊!

Best practice would be to leave the images that are in the header and lazy-load only the ones that are below the initial viewport.

#### Challenge!
Use Lozad to lazy-load a background image and video!

#### Thoughts?
Please, share your thoughts and experiences as to how lazy-loading improved your website. PS, are you guys interested in me writing about lazy-loading using vanilla JavaScript? Let me know in the comments, thank you!