teleren/devto huggingface dataset:
Databases in AWS - RDS and Aurora
Tags: aws, cloud, devops, cloudskills
Published: 2021-08-10 02:27:24

There are many managed databases provided by AWS which allows us to setup databases very easily.

## Why use managed databases given by AWS

You can setup your own Db on your on premises server or on your Ec2 instances but then you have to take care of backups, replication, scaling, availability, durability. Which is a lot of operational work added to your plate. If you mainly want to focus on developing your applications and don't want to worry about managing and handling your data bases then managed DB's by AWS are your best choice. These managed DB have a built in 
1. Scaling, Availability
1. Backups and upgrades
1. Monitoring, alarms etc.

## Relational DB services

### RDS

Amazon Relational Database Service (Amazon RDS) makes it easy to set up, operate, and scale a relational database in the cloud. It allows you to setup many relational DB with many different engines like  Amazon Aurora, PostgreSQL, MySQL, MariaDB, Oracle Database, and SQL Server. 

Using RDS has the following advantages over traditional Db

1. Ease of setup - You can setup a production-ready relational database in minutes

1. Scaling - These Db has built in scaling you can also setup replicas to reduce load on each server

1. Availability - If you setup a multi-az db then all the data is automatically replicated and we can even recover our DB from there. There are also continuous backups and we can recover DB's from those timestamps

1. Secure - It allows you to encrypt your data using industry standard encrypted IPsec VPN. It also offers encryption at rest and encryption in transit.

1. Maintenance - We have to do less management as OS management and updates are handled by AWS

### Aurora 

Aurora is a special proprietary DB by AWS and you can use Mysql or Postgres it combines the performance and availability of traditional enterprise databases with the simplicity and cost-effectiveness of open source databases. Amazon Aurora is up to five times faster than standard MySQL databases and three times faster than standard PostgreSQL databases. It auto-scales up to 128TB per database instance and delivers high performance and availability with continuous backup to Amazon S3.

Next we will do a Hands on setting up RDS on AWS cloud.
How to insert a single document into a MongoDB collection
Tags: mongodb
Published: 2021-08-10 01:44:56

---
title: How to insert a single document into a MongoDB collection
published: true
date: 2021-08-10 01:00:00 UTC
tags: MongoDB
canonical_url: https://donaldfeury.xyz/how-to-insert-a-single-document-into-a-mongodb-collection/
series: "Small Bytes of MongoDB"
---

For a full overview of MongoDB and all my posts on it, check out my [overview](https://donaldfeury.xyz/introduction-to-mongodb/).

MongoDB has several ways of inserting documents into collections. The main way is using a method on collections called `insert.` Here is an example:

```
// Let's say we want to insert a new document representing a new user
db.users.insert({
	email: "test@test.com",
	username: "test_user",
	password: "please encrypt your passwords"
})

```

This will insert our "user" document into the users collection. We don't even have to make sure the users collection already exists since collections in MongoDB are automatically created during inserts. You can insert many documents at one time into a MongoDB collection using the `insert` method as well.

More recent versions of MongoDB will give you a deprecation warning when using `insert` and will instead want you to use `insertOne` for inserting single documents.

```
db.users.insertOne({
	email: "test@test.com",
	username: "test_user",
	password: "please encrypt your passwords"
})

```
What I learned from Flexbox Froggy: Item Properties
Tags: beginners, css
Published: 2021-08-10 02:13:41

In the interest of learning Flexbox during bootcamp, I tried my hand at the brilliant [Flexbox Froggy](https://flexboxfroggy.com) challenge. I completed all 24 levels, but in a pattern-matching, brute-force kinda way. By the end, I felt like I had learned nothing.

Today, months later, I decided to try my hand again at [Flexbox Froggy](https://flexboxfroggy.com). Here's what I learned about *item* properties ([to see what I learned about children properties, click here](https://dev.to/mathlete/what-i-learned-from-flexbox-froggy-container-properties-509f). (Spoiler: it's all about overriding the settings of the container)

## Override the container's order
We use `flex-direction` to define the main axis and thus the order of a container. That should be good enough, right? Well, if for some reason you want to define the order of your items as distinct from the defined order of the parent container, here's an example:

####Example: Before

```javascript
#pond {
  display: flex;
  // nothing here yet
}
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ioi57tnc9ds2fm0x48uk.png)

####Example: After

```javascript
#pond {
  display: flex;
  flex-direction: column;
}
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nfeyt24hyfon6a7zilwi.png)

---

## Override the container's vertical alignment 
We use `align-items` to specify the alignment of the contents of a container along the *cross-axis*. If you want to override that, you can use `align-self` like we do here:

####Example: Before
```javascript
#pond {
  display: flex;
  align-items: flex-start;
}

.yellow {
  // nothing here yet
}
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6en1u2kbnday7be559od.png)

####Example: After
```javascript
#pond {
  display: flex;
  align-items: flex-start;
}

.yellow {
  align-self: flex-end;
}
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iqs0p18qo9t1xdm46vyq.png)

####Options
* `align-self: flex-start`: vertically align items to the top of the container
* `align-self: flex-end`: vertically align items to the bottom of the container
* `align-self: center`: vertically align items to the center of the container
* `align-self: stretch`: vertically stretch items from the top of the container to the bottom of the container
* `align-self: baseline`: vertically center each item to the baseline of the container that text sits upon

*Next up: What I DIDN'T learn from Flexbox Froggy!*
Authentication with Flask and GitHub | Authlib
Tags: authlib, flask, github, nelsoncode
Published: 2021-08-10 02:09:08

For this example we will use Authlib which is the ultimate Python library in building OAuth and OpenID Connect servers

### Installation

```bash
pip3 install Flask Authlib requests python-dotenv
```

### Configuration

```python
from flask import Flask, url_for, redirect
from dotenv import load_dotenv
from os import getenv
from authlib.integrations.flask_client import OAuth


app = Flask(__name__)

app.secret_key = "mysecretkey"

oauth = OAuth(app)

github = oauth.register(
    name='github',
    client_id=getenv("CLIENT_ID"),
    client_secret=getenv("SECRET_ID"),
    access_token_url='https://github.com/login/oauth/access_token',
    access_token_params=None,
    authorize_url='https://github.com/login/oauth/authorize',
    authorize_params=None,
    api_base_url='https://api.github.com/',
    client_kwargs={'scope': 'user:email'},
)   

@app.route("/")
def saludo():
    return "Hello"

if __name__ == '__main__':
    load_dotenv()
    app.run(debug=True, port=4000, host="0.0.0.0")
```

### Route for Authorization
**authorize_redirect** indicates the url to redirect to the **"Callback URL"**

```python
@app.route("/login")
def login():
    redirect_url = url_for("authorize", _external=True)
    return github.authorize_redirect(redirect_url)
```

### Callback URL

```python
@app.route("/authorize")
def authorize():
    token = github.authorize_access_token()
    resp = github.get('user', token=token)
    profile = resp.json()
    # do something with the token and profile
    print(profile, token)
    return redirect('/')
```
### Settings in GitHub

![OAuth application settings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/le02uucwzzt4n09vqcye.png)


[Code of example in GitHub 🔗](https://github.com/NelsonCode/authlib-flask-github)
How to call api within api
Tags: react, javascript
Published: 2021-08-10 01:46:34

i have two api first one is restaurant which i succesfully run now the product id mean the breakfast and sweet api is different now that breakfast sweet api will automatically call according to sell id mean restaurant id i am not able to solve this problem pls help me i am using react js for that and i am using axios for calling api

code for restaurant
const getProductInfo = () => {
    const prodId = params.id;
console.log("this is proid",prodId)
    const apiUrl = /restaurant/${prodId} ;
    axios
      .get(apiUrl)
      .then((res) => {
        console.log("api info res", res.data.vendorDataID);
        setUser(res.data.vendorDataID);
      })
      .catch((err) => {
        console.log("error", err);
      });
To-Do List ✍️
Tags: watercooler, webdev, javascript, showdev
Published: 2021-08-10 01:31:27

#### Live preview and can be found <a href="https://fatrixienicolieopetina.github.io/todo-list/">here</a>

### About 👨‍🏫
The todo list have projects or separate lists of todos. When a user first opens the app, there is some sort of ‘default’ project called 'Home' to which all of the todos are put. Users can create new projects and choose which project their todos go into. **localStorage** is used to save user’s projects and todos between sessions.


### WIL/Thoughts 🤔
Tried revisiting and reading about SOLID principles to properly write a maintable code. 


📌 **Single Responsibility Principle** . Design classes/functions in a way that it is only doing ONE thing.

📌 **Open/Closed Principle** - For me , this is very difficult to apply. You really have to think carefully about each class design, its associations, relationships etc.

📌 **Liskov Substitution Principle** - It is like saying that a child can act as a proxy to the parent (my definition for simplicity 😆). I believe this is almost always enforced in OOP languages like Java.

📌  **Interface Segregation Principle** - In simple terms, interfaces should not force implementing classes to implement methods they do not need. That is why we have functional interfaces, interfaces with only one abstract method. This special type of interface enforces ISP.

📌 **Dependency Inversion Principle** - At first, I had trouble understanding what the second rule of this principle meant.
> High-level modules should not depend on low-level modules.  Both should depend on abstractions. 

This is achievable by using constructs such as interfaces to facilitate loose coupling between modules. 

> Abstractions should not depend upon details.  Details should depend upon abstractions.

I did not quite understand what it meant at first. After searching through the web, this 👇 is the best answer I found.

🥇 <em>It means that if the details change they should not affect the abstraction. The abstraction is the way clients view an object. Exactly what goes on inside the object is not important. Lets take a car for example, the pedals and steering wheel and gear lever are abstractions of what happens inside the engine. They do not depend on the details though because if someone changes my old engine for a new one I should still be able to drive the car without knowing that the engine changed.

The details on the other hand MUST conform to what the abstraction says. I would not want to implement an engine that suddenly causes the brakes to double the speed of the car. I can re-implement brakes any way I want as long as externally they behave the same way.</em>

And those are my WIL(What I Learned) thoughts for a very, very simple to-do project.

_Check out the code of the exercise in this [link](https://github.com/fatrixienicolieopetina/todo-list)_ 

_This project is taken from the [The Odin Project](https://www.theodinproject.com/paths/full-stack-javascript/courses/javascript/lessons/todo-list) todo list exercise._

As always cheers to continued learning :wine_glass:!
Keycloak instalação - P03
Tags: keycloak, ubuntu, nginx, ssh
Published: 2021-08-10 01:13:45


Bom, como mencionado na parte 02, estamos com o servidor pronto para execução. Entretanto, por medida de segurança, para a criação do usuário administrador da aplicação é necessário acessar a aplicação usando o endereço localhost, e ao menos que esteja executando um servidor com ambiente gráfico, não será tão simples o acesso.

Vamos fazer uma execução inicial e ver se a aplicação esta apta para produção/configuração inicial.
Vamos acessar a pasta bin e iniciar o script standalone.sh.
Caso seja executado sem a passagem do parâmetro -b=0.0.0.0, não será possível acessar a aplicação pelo endereço externo do servidor.

```bash
./standalone.sh -b=0.0.0.0
```

![Keycloak](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5d45sg19fwb72ez61b80.png)

Apos o sistema criar a base de dados inicial, fazer algumas migrações e etc, já conseguimos acessar a interface de gerenciamento do keycloak. Entretendo, podemos observar que somos orientado a acessar a mesma via endereço localhost para a criação do usuário administrador. 

![Keycloak server](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0tqz1ijizyrd2uv47oi1.png)

Uma forma de contornar isso é realizar um redirecionamento de porta por meio de um túnel sobre ssh. Dessa forma ao tentar acessar uma porta no computador local, as solicitações serão feitas para o servidor remoto a qual estamos conectados.
Contudo, existe um script para a criação e associação de usuários aos realms da aplicação.  

```bash
./add-user-keycloak.sh -r master -u pedrostefanogv -p testekeycloak
```

![Criação usuário Keycloak](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v4d03gdp5y1qdxbh5q4d.png)

Uma vez que o usuário inicial está criado, podemos acessar ao painel administrador do Keycloak, lembrando que devemos iniciar o servidor novamente. Como podemos verificar na imagem abaixo, agora está disponível a opção de realizar login.

![Servidor Keycloak](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k3xty3ygnqv3f4u8l50k.png)

![Login Keycloak](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/di3ak9zukzvnwe5ayqpa.png)

No próximo artigo, vou abordar como configurá-lo para rodar como serviço no Ubuntu. Dessa forma, garantimos que ao reiniciar o servidor ou caso a sessão do usuário seja encerada, a aplicação continue em execução.
Scoping variables in JavaScript switch statement
Tags: javascript
Published: 2021-08-10 01:02:29

---
title: Scoping variables in JavaScript switch statement
published: true
description: Block level scope fix in switch statement in javascript
tags: JavaScript
---

In JavaScript, variables can be scoped to a block. A block is enclosed by curly braces. This makes the switch statement a block.

A switch statement is used in place of several if...else statements. Using one or several case statements to match expression. The matching case is then run otherwise if there is no matching case, the default case is run.

Normally when you declare variable in case statements, they would hoisted to the switch statement. I would show you a very simple way to make sure the variables you declare in your case statements can only be accessed from that block.

## Block level scope issue

One important point to remember is that each case statement is not a block. Variables declared anywhere within the switch statement is locally scoped to the switch statement.

```js
let number  = 2;

switch (number) {
	case 1: 
		let message = "first number";
		console.log(message)
		break;
	case 2:
		let message = "second number";
		console.log(message)
		break;
  case 3:
		let message = "third number";
		console.log(message)
		break;
	default
		let message = "second number";
		console.log(message)
		break;
}

//This throws a syntax error: identifier "message" 
//has already been declared
```

This shows that the case statements themselves are not blocks, variables declared within them are hoisted to the switch statement block. When the compiler hoists the new declaration of the "message" variable, you are now re-declaring an existing variable which results in a syntax error.

## Block level scope fix

There are cases where you might need yo hold different variable values in each of the case statements. It's possible to keep a variable scoped to the case statement. There's a very easy fix for this, Let's solve this

```js
let number  = 2;

switch (number) {
	case 1: { // braces make the case statement a block
		let message = "number" + number; // this remains in this block
		console.log(message)
		break;
	}
	case 2: {
		let message =  "number" + number; // this is a valid syntax
		console.log(message)
		break;
	}
	case 3: {
		let message = "number" + number; 
		console.log(message)
		break;
	}
	default
		let message =  "number" + number;
		console.log(message)
		break;
}
```

By wrapping  a block in braces, any variable declared within that block is only visible within the block,and is garbage collected once the block ends.

With this syntax, each of these variables are declared within a block, scoped away from each other. They can only be accessed from within the case scope and thrown away once the  block ends.

## Conclusion

I'm sure this is a much easier than you thought. This fix is a legal syntax.

Thank you for reading, I'm Azeez Lukman and here's a developer's journey building something awesome everyday. Please let's network on Twitter, LinkedIn and GitHub @robogeeek95
What is the ordering of Ruby on Rails controller filters?
Tags: rails, shopifyapp
Published: 2021-08-10 01:00:30


Some of my application's controllers are a blend of modules from other people's Rubygems, such as ShopifyApp library. They inject before and after action filters around my actions. Sometimes they abort the request and redirect somewhere else. I wanted to know what filters were being invoked and in what order:

```ruby
class ProductsController < AuthenticatedController
  def index
    __callbacks[:process_action].map { |c| [c.kind, c.instance_variable_get(:"@key")] }
  end
end
```

The output was like:

```ruby
[
  [:around, 82000],
  [:before, :set_shop_host],
  [:before, :redirect_to_splash_page],
  [:before, :set_locale],
  [:after, :set_test_cookie],
  [:before, :verify_authenticity_token],
  [:after, :verify_same_origin_request],
  [:after, :set_esdk_headers],
  [:before, :login_again_if_different_user_or_shop],
  [:around, :activate_shopify_session],
  [:before, :set_shop_origin]
]
```
Learn IoT from scratch #1
Tags: iot, tutorial, beginners, computerscience
Published: 2021-08-10 00:22:12

I am studying about IoT, that is a very interesting topic and I am enjoying and having some fun, so I decided to document my progress and share my knowledge about this. I will study multiple topics of IoT and post a weekly summary, containing all the new things I have learned.

&nbsp;

In this series I will go through the following topics, in order:

**1. What is IoT and how it works?**
**2. What are microcontrollers and how they work?**
**3. Computer networks**
**4. IoT protocols & architecture**
**5. C/C++ basics for embedded systems**
**6. Python/JavaScript for data analysis, monitoring devices and web development**
**7. Best databases for IoT (opinion based)**
**8. Detailed study of sensors**
**9. Electronics essentials**
**10. Network security and encryption**
**11. Linux-OS**
**12. Tools, platforms, languages and frameworks for IoT**
**13. InfluxDB and Grafana**
**14. MongoDB for IoT**
**15. MQTT**
**16. Wifi and Bluetooth**
**17. GPS systems**
**18. Final IoT project**

So if you have interest in this area, and wants to become a IoT developer, save these articles in your list and follow me in this journey! :smile::heart:
Easiest Way To Add Icons To Your React Apps 😎
Tags: webdev, tutorial, javascript, react
Published: 2021-08-10 00:01:58

## A great UI begins with some great icons. 
Icons are important as they add familiarity to your website. Such as a hamburger menu. Everyone knows to click a hamburger icon to get more information, or how a down arrow at the bottom of the page, indicates the user should scroll. 

If you're working with React, it's extremely easy to implement icons into your projects, with thousands of choices from various libraries. 


**Let's begin.**

---

### Resources
- react-icons: https://react-icons.github.io/react-icons
- Demo: https://react-icons-blog-example.netlify.app/
{% github chansen17/react-icons-blog no-readme %}

---

## 1. We're going to be using the `react-icons` package 📦

Download `react-icons` either with yarn or npm. Like so:
```
yarn add react-icons 
or 
npm install react-icons --save 
```
---

## 2. Import Icons ↩️

On the react-icons homepage, you'll see a ton of libraries to choose from. From Bootstrap, Font-awesome, Material-UI and many more. Choose your favorite. 

Once you find the icon you like, click to add the code to your clipboard. 

Now, in `App.js` all we need to do is import the Icon and the library like so: 
```
// fa is the reference to the font-awesome library
import { FaReact, FaSass, FaLinux} from 'react-icons/fa';

// md is the reference to the material-ui library
import { MdFavoriteBorder, MdChat } from 'react-icons/md';
```
---

## 3. Let's use our icons 👍

Lastly, in your `App()` component, all you need to do is use the Icon like any other component. So back in step 2, if you imported the React, Sass, Linux, Favorites and Chat Icons, just use them like so:
```javascript
function App() {
  return (
    <ul>
      <li><FaReact/></li>
      <li><FaSass/></li>
      <li><FaLinux/></li>
   
      <li><MdFavoriteBorder/></li>
      <li><MdChat/></li>
    </ul>
 );
}
```

---

## Conclusion 😎

Congrats! That's it! That's all it takes to bring Icons into your React projects. You have the choice of thousands of Icons from 21 different libraries! And the best part is you only import the Icons you need from each individual library, which helps with performance! 

*So bring some flare to your UI, & get creative!*

--- 

## Are you on the Web Dev learning journey!? 

Check out my other posts on *productivity* and *React.*

{% link https://dev.to/hyggedev/how-to-stay-focused-as-a-self-taught-frontend-web-developer-7gp %}
{% link https://dev.to/hyggedev/how-to-build-a-responsive-react-navigation-menu-with-styled-components-3682 %}

--- 

{% tag codenewbies %}
{% tag tutorials %}