teleren/devto huggingface dataset:
It's All About (The) Next.js Api routes (Part-2)
Tags: nextjs, javascript, frontend
Published: 2021-05-19 09:05:39

#API Routes Get Data from Database


As promised in our last article, this article focused on retrieving the data from the database (in the Next.js api routes) and return the JSON object to the browser. It proves Next.js is absolutely a full-stack framework.

We'll quickly set up the database (MySQL/MariaDB) for this article. And then see how to retrieve the data. In this article, you must have at least a basic familiarity with MySQL or MariaDB.

Create the database *nextjsDemo* and create the table users.


```mysql
create database nextjsDemo;
create table users(
    user_id INT NOT NULL,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL
);
```


The next step is to insert few lines of data into it. 


```mysql
INSERT INTO users (user_id, name, email) 
	VALUES 
(1, 'Michael Foo', 'michael@foo.com'), 
(2, 'John Cena', 'john@example.com'), 
(3, 'Zoho S', 'zoho@example.com');
```

Install the Node MySQL package

```node
npm install mysql
```

In our last article, we created a file getuser.js under the api folder. Delete all the contents of the file and add the following:


```javascript
const mysql = require('mysql');
let connection = mysql.createConnection({
    host: 'localhost',
    user: 'your_db_user',
    password: 'your_db_password',
    database: 'nextjsDemo'
});


connection.connect(function(err) {
  if (err) {
    return console.error('error: ' + err.message);
  }
  console.log('MySQL Connection Successful.');
});

function getUsers(req, res) {
	res.status(200).json({ users: 'Will return user object'})
}


export default getUsers;
```


If you visit the page http://localhost:3000/api/getuser and, you'll see "{"users": "Will return user object"}" And on the command line, you'll see 'MySQL Connection Successful.'

We have successfully set up the MySQL connection. It already proves that Next.js is a Full Stack React Framework. The next task is to retrieve the data from the database.


We need to use the query function to retrieve the data from the database.

Update the function code as following:

```javascript
function getUsers(req, res) {
    const user_query = "select * from users";
    connection.query(user_query, function (error, result, fields){
        if (error) throw error;
        res.status(200).json({ users: result})
    })
}
```

If you visit the page again http://localhost:3000/api/getuser and, you'll see the user object. 

But there is one catch, in the console, there is a warning 'API resolved without sending a response for /api/getuser, this may result in stalled requests'. It's due to the async nature of NodeJs. You can fix by using a promise and make the export function async.
Terraform unsensitive
Tags: terraform, shortposts
Published: 2021-05-19 08:45:48

For every `sensitive=true` in Terraform, there is a nonsensitive function...

```terraform
variable "password" {
   type        = string
   description = "Password"
   sensitive  = true
}
```

> nonsensitive takes a sensitive value and returns a copy of that value with the sensitive marking removed, thereby exposing the sensitive value.

```terraform
output "sensitive_password" {
  value = nonsensitive(var.password)
}
```

The [nonsensitive function](https://www.terraform.io/docs/language/functions/nonsensitive.html) removes the sensitive marking from a value that Terraform considers to be sensitive.

**Note:** The nosensitive function is only available in #Terraform v0.14 and later.
What’s New In Angular 12?

Published: 2021-05-19 08:41:23

Angular is Google’s TypeScript-based framework for building desktop and mobile web apps. The latest update of Angular has been launched on 12th May and is now accessible as a production release. With various improvements, the upgrade deprecates the inheritance Vie Engine assemblage and delivers a pipeline for more current Ivy technology. The new version Angular 12 draws nearer to an “Ivy all over” vision for structure. Ivy is depicted as a cutting edge gathering and delivering pipeline, offering faster AOT compilation. Current libraries using View Engine will work with Ivy applications. The angular latest versions follows similar upgrades with contributions of sticker types and better router performance. Let us see the new features in Angular 12 version. 

Know the angular best practices at- Top 10 Angular Best Practices To Follow In 2020

#Features Of Angular 12-
**1. Ivy Everywhere-**
The View Engine has finally been deprecated in Angular 12. The angular community has been working over ongoing deliveries towards the aim to combine the Angular ecosystem on Ivy. It is called “Ivy Everywhere”. As the View Engine is deprecated, it will be eliminated in future releases also. Current libraries are using View Engine and it will in any case work with Ivy apps, yet library authors should start transition to Ivy.  

**2. Deprecating Support For IE11-**
Angular keeps it updated with an advancing web ecosystem. Removing the support for legacy browsers allows us to focus on giving modern solutions and better help to engineers and clients. Also, the team has included new deprecation warning message as  another Angular 12 feature- and remove support for IE11 in Angular v13.

**3. Protractor: Planning For Future-**
It is one of the latest features of Angular 12. The team has been working with the community to determine the eventual fate of the Protractor. Now, they are investigating the feedback shared in the RFC and figuring out the best future for Protractor. The team have decided to exclude it in new tasks and, it in new tasks, considering all alternatives with popular 3rd party solutions in the Angular CLI. Now, team is working with Cypress, WebdriverIO, and TestCafe to help angularjs development company with receiving elective solutions. More data to come as this develops.

**4. Migrating From Legacy i18n Message IDs-**
Legacy message-ids are delicate as issues can emerge dependent on whitespace and organizing formats and ICU expressions. To deal with this issue the Angular team is relocating away from them. New standard message-id design is more natural and tough. This configuration will reduce the superfluous translation invalidation and related retranslation cost in applications where translations don’t coordinate because of  whitespace changes. 

Since Angular version 11, new tasks are normally intended to use the new message ids and now they have the tooling to move existing tasks with existing translations.

Know more at- [https://solaceinfotech.com/blog/whats-new-in-angular-12/]
Top 5 Python Coding Practise Playground
Tags: python, learning, productivity, programming
Published: 2021-05-19 08:29:23

Python is a powerful general-purpose programming language. It is used in web development, data science, creating software prototypes, and so on. Fortunately for beginners, Python has simple easy-to-use syntax. This makes Python an excellent language to learn to program for beginners. 

There are many resources from which you can learn and practice Python right now, below is my list of Python Coding Practise Playgrounds that you can start using right now. 

1.  [Codingbat](https://codingbat.com/python). CodingBat is a free site of live coding problems to build coding skill in Java and Python ([example problem](https://codingbat.com/prob/p151833)). CodingBat is a project by  [Nick Parlante](http://www-cs-faculty.stanford.edu/~nick/), a computer science lecturer at Stanford. Going through many practice problem is a great way to solidify your understanding of how the code should work. CodingBat problems work great as homework, or for self-study practice, or in a lab, or as live lecture examples. The  [CodingBat](https://codingbat.com/)  problems are designed to have low overhead: short problem statements (like an exam), nothing to install, immediate feedback in the browser, and there's lots of them to build up those skills. 
2. [CodeChef](https://www.codechef.com/). CodeChef was created as a platform to help programmers make it big in the world of **algorithms**, **computer programming**, and **programming contests**. Apart from providing a platform for **programming competitions**, CodeChef also has various algorithm tutorials and forum discussions to help those who are new to the world of **computer programming**.
3. [Coderbyte](https://coderbyte.com/). Coderbyte is a web application built to help you practice programming and improve your coding skills. They offer a collection of code challenges and web development courses that can help you prepare for upcoming job interviews. The coding challenges range in difficulty and they can all be completed straight in our online editor.
4.  [Exercism](https://exercism.io/) Exercism aims to provide opportunity for people of **all backgrounds** by helping them develop their programming skills through practice and mentorship. They provide thousands of exercises spread across over 50 language tracks, and offer both **automated and human mentoring.**
5. [Codewars](https://www.codewars.com/) Codewars is a collective effort by its users. They are creators - authoring kata to teach various techniques, solving kata with solutions that enlighten others, and commenting with constructive feedback. The leaders among them moderate the content and community.


***Note*** - This list is created on the basis of my personal experience. I hope it will help you to learn Python programming.

Thanks for reading!
Sử dụng Docker để chạy website Wordpress thay cho XAMPP trên Windows 10
Tags: docker, wordpress
Published: 2021-05-19 08:21:48

Từ trước giờ nếu bạn dùng Windows để xây dựng website bằng **wordpress** chắn hẳn bạn đã từng xử dụng XAMPP để host trang web wordpress ở máy bạn. 
<br />
Bài viết này sẽ hướng dẫn bạn host trang web wordpress  bằng Docker trên Windows 10 cũng như Mac OSX hay Linux.

## 1. Bật chế độ thử nghiệm trên Docker (Chỉ Windows)
>Đối với những bạn sử dụng **Mac OSX** hay **Linux** thì bỏ qua bước này

Mở **Docker** lên, click vào **Setting** (Biểu tượng răng cưa), thay đổi `experimental` sang `true` nếu đang có giá trị `false`.
```json
{
  "registry-mirrors": [],
  "insecure-registries": [],
  "debug": false,
  "experimental": true
}
```

Click **Apply & Restart**.

## 2. Cấu hình
 Tạo thư mục chứa website wordpress của bạn, sau đó vào thư mục vừa tạo, tạo file `docker-compose.yml` với nội dung như sau:
```yaml:docker-compose.yml
version: '3.3'

services:
  db:
    image: mysql:5.7
    volumes:
      - db_data:/var/lib/mysql
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: somewordpress
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: wordpress

  phpmyadmin:
    depends_on:
      - db
    image: phpmyadmin/phpmyadmin
    restart: always
    ports:
      - '8080:80'
    environment:
      PMA_HOST: db
      MYSQL_ROOT_PASSWORD: somewordpress 

  wordpress:
    depends_on:
      - db
    image: wordpress:latest
    ports:
      - "8000:80"
    volumes: ['./:/var/www/html']
    restart: always
    environment:
      WORDPRESS_DB_HOST: db:3306
      WORDPRESS_DB_USER: wordpress
      WORDPRESS_DB_PASSWORD: wordpress
      WORDPRESS_DB_NAME: wordpress
volumes:
    db_data: {}
```

Các tham số bạn cần chú ý và đặt lại ở đây là:
- `MYSQL_ROOT_PASSWORD`: Mật khẩu user **root** của database.
- `WORDPRESS_DB_USER`: Tài khoản database trang wordpress của bạn.
- `WORDPRESS_DB_PASSWORD`: Mật khẩu database trang wordpress của bạn.
- `WORDPRESS_DB_NAME`: Tên database trang wordpress của bạn.


## 3. Khởi chạy
Mở `cmd` nằm trong thư mục vừa tạo, chạy lệnh:
```shell
docker-compose up -d
```
> `docker-compose` được cài kèm với docker, lệnh `docker-compose` sẽ chạy tất cả các service đã định nghĩa trong file `docker-compose.yml` ở trên.

Vậy là xong, vào trình duyệt gõ địa chỉ `http://localhost:8000`, bạn sẽ thấy trang cài đặt wordpress. Nhập thông tin website và cài đặt như bình thường. Bạn sẽ thấy toàn bộ code trang wordpress của bạn nằm trong thư mục mà bạn vừa tạo ở trên. 
<br />
Để truy cập `phpmyadmin`, bạn hãy truy cập `http://localhost:8080`.

## 4. Tắt và dọn dẹp:
Mở **cmd** ở thư mục chứa file `docker-compose.yml` và sử dụng các lệnh sau
- Tắt, xóa container nhưng giữ lại data: `docker-compose down`
- Tắt và xóa tất cả `docker-compose down --volumes`

Ngoài **Windows 10** ra thì file `docker-compose.yml` ở trên còn áp dụng được cho **Docker** trên **Mac OSX** hay **Linux**.

**Tham khảo**:
https://docs.docker.com/compose/wordpress/
https://hub.docker.com/r/phpmyadmin/phpmyadmin/
Ways to implement Proxy Pattern in Node.js
Tags: node, proxy, pattern
Published: 2021-05-19 08:10:56

https://grokonez.com/node-js/ways-to-implement-proxy-pattern-in-node-js

Ways to implement Proxy Pattern in Node.js

Sometimes we may want to access indirectly to an object, via a substitute. That substitute is called Proxy. The Proxy Pattern helps us deal with a proxy object and talk to the actual object. In this tutorial, we're gonna look at 2 ways to implement Proxy Pattern in Node.js:
<ul>
<li>Using custom Proxy Class</li>
<li>Using Proxy API</li>
</ul>

<!--more-->
<h2>Proxy Pattern Overview</h2>
<img src="https://grokonez.com/wp-content/uploads/2019/04/nodejs-proxy-pattern-example-sample-structure.png" alt="nodejs-proxy-pattern-example-sample-structure" width="550" height="167" class="alignnone size-full wp-image-17708" />

The image above shows that <code>Proxy</code> and <code>Subject</code> have the same methods. <code>Proxy</code> forwards each operation to <code>Subject</code>, we can improve <code>Subject</code>'s methods with additional pre-processing or post-processing.
<h2>Proxy Pattern in Node.js using custom Class</h2>
<h3>Create Subject class</h3>
We create a <code>Bank</code> class with 3 methods:
– <code>deposit()</code> increases cash.
– <code>withdraw()</code> decreases cash.
– <code>total()</code> returns cash.

<em>Bank.js</em>
<pre><code class="language-javascript">
class Bank {

  constructor() {
    this.cash = 0;
  }

  deposit(amount) {
    this.cash += amount;
    return this.cash;
  }

  withdraw(amount) {
    if (amount <= this.cash) {
      this.cash -= amount;
      return true;
    } else {
      return false;
    }
  }

  total() {
    return this.cash;
  }
}

module.exports = Bank;
</code></pre>
<h3>Create custom Proxy class</h3>
The <code>Proxy</code> class also have 3 methods: <code>deposit()</code>, <code>withdraw()</code>, <code>total()</code>. Inside each method, we call <code>Subject</code>'s methods with additional process.

Notice that we need initiate <code>Bank</code> object in <code>constructor()</code> method.

<em>BankProxy.js</em>

More at:

https://grokonez.com/node-js/ways-to-implement-proxy-pattern-in-node-js

Ways to implement Proxy Pattern in Node.js
Stack & Heap Memory in C#
Tags: csharp
Published: 2021-05-19 07:48:35

**What is the Stack?**

Stack is a LIFO (Last In First Out) structure and hold Value Types such as bool, byte, char, decimal, double, enum, float, int, long, sbyte, short, struct, uint, ulong, ushort. Variables are stored directly to the memory and can be accessed fast. The variables stored in the stack can’t be resized and their allocation is static. Stack also contains pointers (or reference) that are pointing to reference types.

**What is the Heap?**

Heap on the other hand is an area of memory where chunks are allocated to store certain kinds of data objects. Data in the Heap can be added or stored in any order and are stored indirectly. Reference Types such as class, interface, delegate, object, string, all live in the Heap. The memory allocation is dynamic and variables can be resized. Access on the heap is slow. Memory allocation and release is managed by a Garbage Collector.

If you would like to read more stories, check out my <a href="https://kapadev.com/" target="_blank">blog</a>.
CodePen - Wibbly Wobbly SVG Jelly ✨
Tags: codepen, webdev, javascript
Published: 2021-05-19 07:43:54

This lil' jelly character is an example from my upcoming tutorial “Creating a Liquid Hover Effect with GSAP &amp; SVG“ — stay tuned for updates! 👀

{% codepen https://codepen.io/georgedoescode/pen/MWpjVgB %}
make sudo not ask for password
Tags: ubuntu, linux, sudo, opensource
Published: 2021-05-19 07:32:11

Modifying the system files to skip asking for password can be dangerous and also can lead to unexpected behaviour and problems.

So the way without Modifying anything it to use

`sudo su`

this will make you login to the super user and you can do anything you want without asking for password and the good thing is when you close the terminal and open a new terminal , the new one will be normal as before without the need to undo the change in any files
Improve the performance of git on WSL2
Tags: windows, wsl2, git
Published: 2021-05-19 07:24:35

---
title: Improve the performance of git on WSL2
published: true
description: Git status on WSL2 is slow, but there's an easy way to speed it up.
tags: Windows, WSL2, git
canonical_url: https://stapp.space/git-wsl2/
---
I've returned to Windows after a year on the Mac. I built up pwsh and added a lot of tools, but I still need some Linux/MacOS ones, such as `envsubst`. Of course, WSL2 comes to the rescue, but you'll have to checkout the repo twice for Linux and Visual Studio. It is ridiculous.
I set up oh-my-posh with powerline on WSL2, which is a fantastic combination. However, there is a "but": git status is quite slow. What is the reason for this? Just read [4197](https://github.com/microsoft/WSL/issues/4197)

How can this be resolved? Simply replace the git command with the git function, as shown below:
```
function git() {
  if [[ $(pwd -P) = /mnt/* ]]; then
    git.exe "$@"
  else
    command git "$@"
  fi
}
```
And that's all 🙈🙉🙊
Issue with Else If Statement
Tags: javascript
Published: 2021-05-19 07:20:26

Hi,

I am stuck trying to understand a Javascript solution. Please can you help dumb it down for me if possible:

Question:

Write a function addWithSurcharge that adds two amounts with surcharge. For each amount less than or equal to 10, the surcharge is 1. For each amount greater than 10 and less than or equal to 20, the surcharge is 2. For each amount greater than 20, the surcharge is 3.

Example: addWithSurcharge(10, 30) should return 44.

Answer:

function addWithSurcharge (a,b) {

let sum = a + b;

if ( sum < 10) {

return sum += 2}

else if (sum > 10 && sum <= 20) {

return sum += 2}

else if (sum > 20 && sum < 30) {

return sum += 3}

else if (sum >= 30 && sum < 40) {

return sum += 4}

else if (sum > 40) {

return sum += 5}

};

————————————————————————-

I simply do not understand why this works.

FYI: I am a beginner

Thanks in advance
7 Best Online Python Courses for Data Analysis in 2021
Tags: datascience, analytics, analyst, python
Published: 2021-05-19 07:16:46

Python is the internationally acclaimed programming language that will help you to handle data in a better way. Python has a wide variety of **libraries(NumPy, Pandas, and Matplotlib)** for data analytics tasks. So if you are looking for Best Online Python Courses for Data Analysis, then this article is for you.

In this article, you will find the **7 best online Python courses for data analysis**. And these courses are filtered out on the following criteria-

##**Criteria-**

🟠 Rating of these Courses.
🟡 Coverage of Topics.
🟢 Engaging trainer and Interesting lectures.
🟠 Number of Students Benefitted.
🟡 Good Reviews from various aggregators and forums.

So, without wasting your time, let’s start finding the best online Python courses for data analysis.
**[Click to continue reading...](https://www.mltut.com/best-online-python-courses-for-data-analysis/#1-data-analyst-with-python-datacamp)**
Top 3 Golang Web Frameworks In 2021
Tags: go, webdev, beginners, productivity
Published: 2021-05-19 07:10:39

Golang is one of the most powerful and well-known tools used for writing APIs and web frameworks. Google "Go", otherwise known as Golan, orders a quick run of local code. It's amazing to launch several advances in programming by rethinking the specialists and software engineers from different sections. We can say that this is happening on the basis that the engineers thought it was easiest to use Go. It is always considered the best for web and mobile app development because it ranks highest among all web programming languages.

Top 3 Golang Web Frameworks in 2021:

**1. Martini:** Martini is said to be a low-profile framework, as it is a small community, but also known for its various unique things, such as injecting different datasets or working with different types of handlers. It is very active, and there are about twenty or more plugins that may also be the reason for the need for add-ons. It covers some principles of methods such as routing, dealing, etc., the main general techniques for creating middleware.

**2. Buffalo:** Buffalo is known for its fast app development services. This is the complete process of starting any project from scratch and providing an end-to-end tool for creating a web interface. Buffalo comes with a dev command that helps you directly test the transformations in front of you and rebuild your entire binary. It's more of an ecosystem used to create better application development.

**3. Gorilla:** Gorilla is the largest and longest running Go web framework. It can be small and maximum for any user. It's also the largest English-speaking community that comes with robust web socket features, so you can attach REST codes to endpoints by providing a third-party service like Pusher.

So, here are some web frameworks that you can use for the [Golang language](https://exceed-team.com/tech/top-3-golang-web-frameworks-in-2021?s=de&a=a). Each structure has its own unique points that can only be found in them, but they are all the best. IF your developer is on the lookout, this is the place where you can find the best.
Designing Interactive Dashboards for Sales + Stock Summary using Low-Code
Tags: ux, design
Published: 2021-05-19 07:00:11

Sales and stocks summary dashboards are crucial for any organization. Wouldn't it be really cool if you got to build one, customized as per your requirements by yourself?
We are hosting a Low Code Live Designing - A Workshop for UX Designers on how to build interactive stock inventory dashboards using low code this Thursday. You’ll learn how to add charts to measure metrics and make your own customized dashboard! I hope to see you there 😊
Register - https://bit.ly/live-designing
It starts at 6:30 pm IST/ 9:00 am ET on May 20th