teleren/devto huggingface dataset:
How to Install Vue CLI  on Ubuntu 20.04
Tags: vue, javascript, ubuntu, linux
Published: 2021-02-28 13:20:02

In this article, we'll explain how to install Vue CLI on Ubuntu 20.04.

Vue.js is an open-source model–view–viewmodel front end JavaScript framework. This article will guide you the installation process and creating hello world first project.

####Prerequisites
A Ubuntu 20.04 installed <a href="https://www.hostnextra.com/dedicated-server.html">dedicated server</a> or <a href="https://www.hostnextra.com/vps-hosting.html">KVM VPS</a>.
A root user access or normal user with administrative privileges.
<a href="https://www.hostnextra.com/kb/4-steps-to-install-nodejs-on-ubuntu-20-04/">Installation of NodeJS on Ubuntu 20.04</a>

<a href="https://www.hostnextra.com/kb/how-to-install-vue-cli-on-ubuntu-20-04/">Install Vue CLI on Ubuntu 20.04</a>

####Install Vue CLI

Following command will install Vue CLI.

 # npm install -g @vue/cli

Verify the installation:

 # vue --version

Output:

@vue/cli 4.5.11

####Create Vue project

 # vue create hello-world

You will be prompted to pick a preset. You can either choose the default preset which comes with a basic Babel + ESLint setup, or select "Manually select features" to pick the features you need.

Output:

Vue CLI v4.5.11
? Please pick a preset: (Use arrow keys)
❯ Default ([Vue 2] babel, eslint)
Default (Vue 3 Preview) ([Vue 3] babel, eslint)
Manually select features

Successfully created project hello-world.
Get started with the following commands:

 # cd hello-world
 # npm run serve

Output:

App running at:
- Local: http://localhost:8080/
- Network: http://192.168.0.106:8080/

Note that the development build is not optimized.
To create a production build, run npm run build.

Navigate to your browser and open http://[server_IP]:8080.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2jlbdcx3upmh65yihirj.png)

That's it. The installation has been completed.

In this article, we have seen how to install Vue CLI on Ubuntu 20.04.
Daily Developer Jokes - Sunday, Feb 28, 2021
Tags: jokes, dailydeveloperjokes
Published: 2021-02-28 13:00:15

---
title: "Daily Developer Jokes - Sunday, Feb 28, 2021"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
cover_image: "https://private.xtrp.io/projects/DailyDeveloperJokes/thumbnail_generator/?date=Sunday%2C%20Feb%2028%2C%202021"
published: true
tags: #jokes, #dailydeveloperjokes
---

Generated by Daily Developer Jokes, a project by [Fred Adams](https://xtrp.io/) ([@xtrp](https://dev.to/xtrp) on DEV)

___Read about Daily Developer Jokes on [this blog post](https://xtrp.io/blog/2020/01/12/daily-jokes-bot-release/), and check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/).___
### Today's Joke is...
![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e1258c20b362.png)

---
*Have a joke idea for a future post? Email ___[xtrp@xtrp.io](mailto:xtrp@xtrp.io)___ with your suggestions!*

*This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit.*

<!-- 
Joke text:
___Q:___ Why did the computer keep sneezing?

___A:___ It had a virus!
 -->
JavaScript Interview Question #27: Handling errors in JavaScript Promise chains
Tags: javascript, webdev, beginners, codenewbie
Published: 2021-02-28 12:58:37

![js-test-27](https://learn.coderslang.com/js-test-27.png)

Are there any differences between f1 and f2?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

If you're not sure what is a Promise in JS or how to use it, read these articles first:
- [What is a JavaScript Promise and how it works](https://learn.coderslang.com/0027-javascript-asynchronous-programming-and-promises/)
- [How to create Promises in JS and handle Promise chains](https://learn.coderslang.com/0029-javascript-promise-chains/)

There are two ways of providing error handlers to the JavaScript Promises.

The first one is shown in the function `f1`. We pass the `errorHandler` as a second argument to `.then()`.

The second approach is implemented in `f2`. Here, we add the `errorHandler` using the `.catch()` function.

In both cases `errorHandler` will be called if the original `promise` is rejected.

If `promise` resolves successfully, then the execution continues in `successHandler`. And if `successHandler` throws the error, then it will only be handled by `f2` and not `f1`.

This happens because of the internal implementation of `.catch()`. It handles all errors in the promise chain, including the ones inside of the `.then()` handlers.

---

**ANSWER**: Yes, there’s a big difference between `f1` and `f2`. The former doesn’t handle the error in `successHandler`  (if it appears) and the latter does.

[Learn Full Stack JavaScript](https://js.coderslang.com)
Testing select option with React Testing Library
Tags: react, select, test, javascript
Published: 2021-02-28 12:58:06


####이번 글은 셀렉트 박스를 react testing library를 통해서 어떻게 테스트하는지에 대한 포스트다.
<br>
**react testing library**는 Semantic HTML을 사용할수록 더 간편하게 query를 할 수가 있다. 아래의 `Select` 컴포넌트 같은 경우는 semantic 하게 html을 사용했기 때문에 `label` 태그와 같이 사용되었다.


```javascript
import { FC } from 'react';

const Select: FC = () => {
  return (
    <div>
      <label htmlFor="language-select">
        Choose a country
        <select id="language-select">
          <option value="">choose a country</option>
          <option value="ko">한국</option>
          <option value="usa">미국</option>
        </select>
      </label>
    </div>
  );
};

export default Select;
```

```javascript
import React from 'react';
import { render, screen, userEvent } from '@test-utils';
import Select from './Select';

test('default option should be falsy when different option is selected', () => {
  render(<Select />);
  const selectElement = screen.getByRole('combobox', { name: 'Choose a country' });
  userEvent.selectOptions(selectElement, 'usa');
  const defaultOption = screen.getByRole('option', { name: 'choose a country' }) as HTMLOptionElement;
  const selectedOption = screen.getByRole('option', { name: '미국' }) as HTMLOptionElement;
  expect(defaultOption.selected).toBeFalsy();
  expect(selectedOption.selected).toBeTruthy();
});
```

#####위의 테스트 코드는 짧지만, step by step으로 최대한 자세하게 설명을 해보겠다.

<br>

- 먼저 **Select** 컴포넌트를 렌더링을 시켜줘야 한다. `render`를 통해서 해당 컴포넌트를 렌더링했다.

<br>
- react testing library의 Query는 여러 가지 종류가 있는데 공식 홈페이지에서 정해놓은 
[우선순위](https://testing-library.com/docs/queries/about/)가 있다.

<br>
- 우선순위에서 1순위인 `getByRole` 쿼리 같은 경우는 DOM의 **Accessibility tree** 안에 있는 [aria-role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles)
을 통해서 DOM 접근을 한 다음에 해당 엘레멘트를 반환을 해준다.

<br>
- **select** 태그의 role은 `listbox` 또는 `combobox`가 이고, multiple attribute가 사용되지 않고, size attribute가 없거나 또는 사이즈가 1보다 크지 않을 때에는 `combobox`로 분류가 된다.

<br>
-  `Select` 컴포넌트는 여러 개의 select 태그가 없기 때문에 `getByRole` 의 두 번째 인자인 option 객체를 통해서 다시 쿼리를 해줄 필요가 없다. 하지만 만약에 이 컴포넌트 안에서 여러개의 select 태그가 있으면 에러가 나게 된다. 

<br>
- 이러면 두번째 인자로 옵션 객체의 name 속성을 이용해서. 다시 한 번 더 쿼리를 할 필요성이 있다. 화면에 표시되는 텍스트가 돔의 **Accessibility tree**의 name(레이블 텍스트: Choose a country)이 되기 때문에 옵션객채에 name속성을 넣어줘서 쿼리를 해준다.

<br>
- 만약에 semantic한 html을 사용하지 않았을 경우에는(label이 없이 select를 사용한 경우), `aria-label` attribute를 select 태그에 추가해주면 name으로 query가 가능하다. 다만 aria-label을 화면상에 보이는 label이 없는 경우에만 사용을 권장하고 또한 **Accessibility** Tree의 name을 덮어씌울 수 있기 때문에 무조건 사용해서는 안 된다. 

<br>
- 이제 해당 `Select` 컴포넌트의 value를 바뀌기 위해서 이벤트를 실행해보아야 하는데, 공식 홈페이지에서 `fireEvent` 보다는 `userEvent` 사용을 권장하고 있기 때문에 userEvent를 사용해서 select의 value를 usa로 바꿔주었다.

<br>
- 다음 단계는 getByRole의 인자로 option을 넣어줘서 쿼리를 해준다. option엘레멘트의 role은 option이다. option 태그 또한 여러개기 때문에  옵션객체에 name을 이용해서 쿼리를 했다. 다만 get쿼리 같은 경우는 항상 타입을 `HTMLElement`를 반환하기 때문에 selected라는 속성이 없기 때문에 타입 assertion을 통해서 `HTMLOptionElement`를 반환을 했다.

<br>
- 자 이제 마지막으로 처음에 선택이 돼 있던 `defaultOption`의 selected 속성이 `falsy`인게 확인이 됐고, 새로 선택이 된`selectedOption`의 selected 속성이 `truthy`인걸 확인할 수 있다.
JavaScript is bananas
Tags: javascript, jokes, twitter
Published: 2021-02-28 12:51:49

During one of these dev Twitter *"Offend a JavaScript developer in one line of code."* jokes, [I replied with](https://twitter.com/drochetti/status/1365418508599795713):

```javascript
('b' + 'a' + + 'a' + 'a').toLowerCase();
```

It's a good old joke about how JavaScript dynamic and *forgiving* type system handles some operations.

It's worth it calling out that I didn't come up with it. I don't even remember the first time I saw it, but it was interesting to notice the curiosity and confusion it created.

### What's happening there?

Let's take a deeper look at what happens in each step of that line:

1. `'b'` is concatenated with `'a'`, resulting in `'ba' + + 'a' + 'a'`. So far so good.
2. Now things get interesting. The next expression is `+ + 'a'`. The first `+` is a concatenation operation just like the previous one, but then it finds another `+` sign, followed by `'a'`, a `string`. The `+ 'a'` is then evaluated as a unary operation, but since 'a' is not a number, JavaScript tries to convert it which results in a `NaN`, the JavaScript global property that indicates a failed numeric expression. Then it gets converted to a string, `'NaN'`, to complete the concatenation operation. Phew!
3. Now we have `'baNaN' + 'a'`, which is the last step of the string concatenation, nothing unusual there.
4. Last but not least, `baNaNa.toLowerCase()` gets rid of the `NaN` to make the joke less obvious.

The key thing happens in step #2. The expression `+ + 'a'` is something that would be considered an invalid syntax in most languages, but JavaScript tries to *guess* what you're trying to accomplish and then things get weird.

JavaScript is very permissive when it comes to interaction between its different types. Whenever a `string` is present or an operation is happening between two incompatible types, JavaScript will try to transform everything to a `string`.

Of course this is a generalization and there are exceptions, but `1 + '1' === '11'` (number + string) and `[1, 2, 3] + 4 === '1,2,34'` (array + number) are two good examples of such behavior.

### JavaScript is bad

For years JavaScript wasn't taken seriously, often considered a bad scripting language that couldn't be avoided due how Browsers work.

Reality is the language has evolved quite a bit, it has an engaged community, a diligent development process through TC39, and it enables a variety of different solutions in all sorts of platforms and devices. However, that wasn't always the case and some of its (weird) early days behaviors remain the same.

I appreciate its power and all the products that were made possible due to its resilience and extensibility. These peculiarities will remain a good source of jokes for years to come nonetheless, and that is just another thing I love about the language.
Basic in .gitlab-ci.yml config
Tags: git, gitlab, ci
Published: 2021-02-28 12:26:14

# ขั้นตอนการใช้งาน
1) ลง Gitlab runner ในเครื่องที่เราต้องการให้มันทำงานด้วย
- download ตัวโปรแกรมมาก่อน โดยที่ ${arch} ให้แทนที่ด้วย
  - amd64, arm หรือ arm64
```shell
curl -LJO "https://gitlab-runner-downloads.s3.amazonaws.com/latest/deb/gitlab-runner_${arch}.deb"
```
- ลงโปรแกรม
```shell
dpkg -i gitlab-runner_${arch}.deb
```
- เพิ่มสิทธิ์ให้กับโปรแกรม gitlab-runner
```shell
sudo chmod +x /usr/local/bin/gitlab-runner
```
- สั่งให้ gitlab-runner ทำงานบน user gitlab-runner และเก็บ build cache ไว้ที่ /home/gitlab-runner
```shell
sudo gitlab-runner install --user=gitlab-runner --working-directory=/home/gitlab-runner
sudo gitlab-runner start
```
2) ทำการผูก repository เข้ากับโปรแกรม gitlab-runner
- ไปเอาข้อมูล token ของ repository มาจากเว็บโดยเข้าที่เมนูด้านข้างของ repository บนเว็บที่ชื่อว่า Settings > CI / CD 

> ถ้าใครไม่เห็นเมนู Settings อาจจะเกี่ยวข้องกับ User ของท่านมีสิทธิ์เข้าไม่ถึง

- เข้าไปเมนู Runners เพื่อคัดลอก Token มา
- กลับมาในโปรแกรม gitlab-runner เพื่อทำการ register และใส่ข้อมูลตาม

> ควรสั่งคำสั่งด้วย sudo เพื่อให้ gitlab-runner เราทำงานใน user ของ gitlab-runner เอง

```shell
sudo gitlab-runner register
```

3) เขียนไฟล์ .gitlab-ci.yml
```yml
# ขั้นตอนในการสั่งงาน
stages:
  - dev-build
  - dev-run

# ก่อนการทำงานในขั้นตอน dev-build และ dev-run
before_script:
  - echo hello world
  - $(pwd)

dev-build:
  # stage ในการทำงาน
  stage: dev-build
  # enviroment ในการทำงานซึ่งมีผลกับการใช้งานตัวแปรใน Settings > CI / CD > Variables
  environment:
    name: dev
  # tag หรือ branch ที่อยากให้ทำงานขั้นตอน dev-build
  only:
    - dev
  # ต้องใส่ให้ตรงและครบถ้วนกับตอนที่เรา register ด้วย token
  tags:
    - dev
  before_script:
    - echo this is before script
  after_script:
    - this is after script
  script:
    - ./myshell.sh $CI_PROJECT_DIR $GITLAB_USER_EMAIL $MY_FIRST_KEY
    - echo ending

dev-run:
  stage: dev-run
  environment:
    name: staging
  only:
    - dev
  tags:
    - dev
  before_script:
    - echo this is before script
  after_script:
    - this is after script
  script:
    - ./myshell.sh $CI_COMMIT_TAG $MY_FIRST_KEY $MY_PEM
    - cat $MY_PEM
    - echo ending
```

4) หลังจากนั้นเราสามารถลอง push project เราขึ้นไปใน branch dev เพื่อทดลองการทำงานไฟล์ .gitlab-ci.yml ของเรา

ผลลัพท์จากการทำงานใน pipeline
![1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ubmd1452ru6hsafzeq97.png)

ผลลัพท์จากขั้น dev-build
![21](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hfyeor9k95zyuazndccd.png)

(highlight สีแดง)
variable ชื่อ $MY_FIRST_KEY แต่เป็นของ environment dev
 
ผลลัพท์จากขั้น dev-run
![31](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/njtyqmw709wr4t21prml.png)

(highlight สีแดง)
variable ชื่อ $MY_FIRST_KEY แต่เป็นของ environment staging

(highlight สีเหลือง)
จะเห็นว่าหากใช้งาน variable แบบไฟล์ มันจะเก็บตัวแปรไว้ในไฟล์ และพอเรียกใช้สิ่งที่ได้คือ path ชั่วคราว (เมื่อ stage นี้ทำงานเสร็จแล้วมันก็จะหายไป)

![41](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kl2cxc4vigz02463eo20.png)
จะเห็นว่า MY_FIRST_KEY มี 2 ค่า คนละ environment
Day 4 of the #100daysofCode Challenge. Learning React
Tags: react, webdev, 100daysofcode, codenewbie
Published: 2021-02-28 12:18:53

## STATEFUL OR STATELESS COMPONENTS WHICH ONE TO CHOSE AND WHY?
During my fourth day in my #100dayofCode journey I have been learning about stateful and stateless components and I decided to write an article about it.

The first question that comes to mind is what is state?
State is simply an object that hold information about a react Component. State is used in tracking changes that occur in a react Component and re-rendering it. 


```
import React from "react";
import ReactDOM from "react-dom";

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = { date: new Date() };
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(<Clock />, document.getElementById("root"));
``` 
The above example is a simple component that has state and we use the state to render output on  the web page.

### stateful and stateless components

What is a stateful component ?
Its is simply a  class component as it has a state object  initialized in the constructor and can change it own state.

```
class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }
 
ReactDOM.render(<Counter />, document.getElementById("app"));

``` 
The above example is a stateful component as  the component contains a state object initialized in the constructor.

#### stateless components
 stateless components are simply functional components which have no state object.
stateless components just take information via props and and outputs it on the web page.

```
import React from "react";
import ReactDOM from "react-dom";
const Header = (props) => {
  return (
    <div>
      <h1>{props.title}</h1>
    </div>
  );
};

ReactDOM.render(<Header title="my App" />, document.getElementById("app"));


``` 
This simple example shows a stateless component which receives information via the props and displays it.

So I know  you are asking when to use one over the other 

### when to use stateless components
1.When there is no interactivity  needed
2. when there is need to reuse your code
3. when no state is required

### when to use stateful components
1.when you want to pass data to the component for rendering
2.when you need interactivity in your web app
3. when taking in user data via input forms 

### Advantages of  stateless components
 1 Easy to understand - Stateless components are usually JavaScript functions which are easy to understand. 
2.High performance - stateless components have high performance compared to stateful components as they don't have state and life cycle.
3.Stateless components reduce the code base  size making  the code to become clean and optimized.

This has been my fourth day learning  react and is has been awesome and interesting.
cheers guys and happy learning.
  [Connect with me on twitter and lets talk about react](https://twitter.com/mc_wachira)
I built a simple anime quotes API with Next.js and Koa.✨
Tags: showdev, webdev, programming
Published: 2021-02-28 12:18:23

Hi Guys, I just quickly wanted to share with you all my recently re-created side project [Animechan](https://animechan.vercel.app/). A tiny rest API that serves your favorite anime quotes in no-time. You can use this API in any of your personal projects.

The project is built upon :
- Next.js (frontend)
- Koa.js (backend)
- TailwindCSS
- MongoDB.

Thanks :)
Containerize a simple PHP laravel Application using docker
Tags: devops, docker, php
Published: 2021-02-28 12:13:22

Docker is an open-source project for automating the deployment of applications as portable, self-sufficient containers that can run on the cloud or on-premises. Docker is also a company that promotes and evolves this technology, working in collaboration with cloud, Linux, and Windows vendors, including Microsoft.

In this short tutorial we're going to containerize a simple PHP laravel application.

1. Create the Application
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/184894jkbwko8cru91y8.png)
2. Go to the folder "cd docker-laravel"
3. Run Locally "php artisan serve"
4. Next we write the Dockerfile, this is a set of commands the docker engine uses to build the image.
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nubpqmyl6xfbdpxgrjun.png)

FROM php:7.4.15-fpm-alpine3.13

RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

WORKDIR  /SRC

COPY . /SRC

RUN composer install

EXPOSE 8000

CMD php artisan serve --host=0.0.0.0 --port=8000 



"FROM php:7.4.15-fpm-alpine3.13" is the image that your docker image is based on.

Second command downloads and install Composer on the base image

Third Command specifies working directory, where the code will be in the image and container.

Fourth command will copy files from your present working directory to /SRC folder

Fifth command runs the command Composer Install

Sixth command allows access to the app on port 8000

Seventh command starts the server.

5. Build your image "Docker build -t laraveldocker .
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jr7pux0qv147cw87q552.png) 

6. List of images "Docker image ls"
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ckhtkk6w5cctgajxqt1a.png)

7. Create a running container from the image "docker run -d -t -p 8080:8000 --name=laraveldocker laraveldocker 
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3b7k5xedcrn1mmvlher2.png)

8. List running containers "docker ps"
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xw6sre2omwqdsmyuwimm.png)
 
9. go to locallhost:8000 to see the running application 
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u84c6b1mclvwa1my6xql.png)
Why Code Review Might Be Something You Need
Tags: codereview, softwaredevelopment, skills, technology
Published: 2021-03-01 11:52:00

---
title: Why Code Review Might Be Something You Need
published: true
date: 2021-02-28 12:12:09 UTC
tags: codereview,softwaredevelopment,skills,technology
canonical_url: https://medium.com/weekly-webtips/why-code-review-might-be-something-you-need-651a2ae96249
---

[![](https://cdn-images-1.medium.com/max/2600/0*sejEvC8pFxp6K8yf)](https://medium.com/weekly-webtips/why-code-review-might-be-something-you-need-651a2ae96249?source=rss-575e54f4c7b9------2)

Code review doesn’t create perfect software but it allows you to create better software

[Continue reading on Weekly Webtips »](https://medium.com/weekly-webtips/why-code-review-might-be-something-you-need-651a2ae96249?source=rss-575e54f4c7b9------2)
Composer update Vs Composer Install
Tags: php, laravel, programming, computerscience
Published: 2021-02-28 12:11:34

Composer update and composer install, These two commands are very useful when you develop any project with composer packages. So Lets figure this out how these two are different from each other🤔.

{% youtube gk6QyqOSNVE %}

*And  Make sure you Like and subscribe* 😉👍👍.

##Composer Install##
When you run **Composer install** in your terminal it reads the `composer.lock` file and install dependencies which are mentioned in this file.
But what if the `composer.lock` file does not exists. So, In this case it reads the `composer.json` file and install the dependencies then creates the `composer.lock` file.

###When to run `composer install`###
In production you need only those dependencies which you have used in development phase, And those dependencies can be found with their exact version in `composer.lock` file. So this command is mainly used in production.
you can use it in development phase also.😎


##Composer update##
When you run **composer update** command it simply process the `composer.json` file and install dependencies, And creates the `composer.lock` file with updated dependencies.

It does not process the `composer.lock` file , but it updates the dependencies version in the lock file.

###When to run `composer update`###
**composer update** command should be used only in development phase of the project. Because It updates the dependencies and also update the `composer.lock` file.
If you run this command in production it can break your code, because it'll update the dependencies which is not good in production because version may change 🤷‍♂️.