teleren/devto huggingface dataset:
Deno WebSocket Simplified in 2 hours
Tags: deno, node, javascript, typescript
Published: 2020-06-09 05:20:23

# Create Deno Real Time Chat in a very simple way

Create Real-Time Chat System using #Deno #WebSocket
Let's see who is joined or who left
Real-Time Message and Registration system

{%youtube haOrVOUnDlw %}

Join Deno Progressive Course https://bit.ly/deno-course
Let's discuss more on twitter, follow me http://twitter.com/Sarthaksavvy

## Uniqueness of this course
1 Using vanilla Javascript
2 HTTP server and WebSocket server on same port (localhost:8080)
3 Refactoring code to make it managable
4 Extreamly easy way of explaining concepts

## How this tutorial is different
There are many blog post and tutorials out there for #deno websocket real time chat system

But this is a simple video of about 2 hours and explained each and every bit of websocket in full details.

So even if you don't know websocket, you will become confident on this.

## Module Used
1. WebSocket module https://deno.land/std/ws
2. Http Server Module https://deno.land/std/http

# What if you want to use WebSocket with oak framework of deno
Here is a progressive course on Deno https://bit.ly/deno-course , where 
1. we will create WebSocket using OAK framework
2. using vuejs to handle frontend part
3. storing chat data into mongodb database
4. using registered user only to enter chat room

dev.to people get a discount of 30% using coupon DENO-DEV.TO-30


## Here is the list of topic we will cover in this tutorial
1.  Intro to websocket
2.  Setup WebSockets
3.  Close WebSocket Connection
4.  Getting Data from WebSocket
5.  Talk to Different Websocket
6.  Broadcast to others only
7.  Handle Http Connections
8.  http and ws on same route
9.  Send Event from html file
10. Send Json in event
11. Register with name
12. Create Join Event
13. Show Joined User
14. Show all Online Users
15. Create User leave event
16. Remove leaved user
17. Handle Closed Connection
18. Refactor Main file
19. Display User Name
20. Real Time Chat
21. Message From You


I hope this will help you to get started with Deno
Any suggestions or comments are most welcome.
Paint shop with focus on hsl (hue, saturation, lightness)
Tags: css
Published: 2020-06-09 04:21:18

[Paint shop demo](https://heggy231.github.io/chingu-webdev-speedrun-challenge/frontend/paint-store)

[hsl(hue, saturation, lightness)](https://www.w3schools.com/css/css_colors_hsl.asp#:~:text=HSL%20Value&text=Hue%20is%20a%20degree%20on,100%25%20is%20the%20full%20color.)

* Hue: 

  - unit: degree 
  - range: 0 to 360
  - ex: 0 is red, 120 is green, and 240 is blue.

* Saturation:

  - unit: % 
  - range: 0% (gray) to 100% (full color)

* Lightness:

  - unit: % 
  - ex: 0% (black), 50% (neither light | dark), 100% (white)

![color wheel](https://discourse-user-assets.s3.dualstack.us-east-1.amazonaws.com/optimized/3X/8/0/8057d553e6cff0427048798efda3b08f0121476f_2_1034x580.png)

[More info hsl](https://www.freecodecamp.org/forum/t/the-basic-principles-of-web-design-a-guide-to-using-hsl-what-is-it-and-is-it-better-than-rgb/326663)
Code Signing Failure due to Symlink Folders 
Tags: macos, appkit, framework, security
Published: 2020-06-09 04:10:53

Symlinks are *not* the correct way to reduce space in a macOS application bundle. When you share code or resources in an app bundle by creating symbolic links across frameworks, that can wreak havoc with code signing — and consequentially notarization.


Learn the proper way to use code exported from one framework into another framework within the same application bundle. Not just code, also learn how to share images and other resources across framework within the same application. Thus reduce your app’s download time by nullifying duplications *and* be compliant with code signing and notarization that’s mandatory starting from macOS Catalina.


https://tinyurl.com/rhjys6c
How to upgrade your Python version
Tags: python, tutorial
Published: 2020-06-09 03:10:22

On my latest post, I introduced a way to make a python IDE that you can access from anywhere. On this post, I will go over on how we can install the latest python 3.8.3 on our IDE. 

For those who haven't read the post before this, I recommend you to check them out: https://dev.to/daniel2231/a-python-ide-that-you-can-use-anywhere-26cg

In this tutorial I will use an IDE called goormIDE, but you can follow this tutorial on any IDE that you wish. However, you must be using a linux based terminal if you want to follow this tutorial. 

Personally, I would recommend using apt to install python as it is faster and less cumbersome.

## Installing the latest Python from Source
First, update your package lists and install the packages required.

```shell
sudo apt update
sudo apt install libffi-dev libsqlite3-dev wget libbz2-dev build-essential libssl-dev libreadline-dev zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev
```

You will be prompt to install the packages. Press y to continue.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/n24lrem458ic50j0j8j6.png)

Now, download the python version you want. In this tutorial, we are going to install python3.8.3

```shell
wget https://www.python.org/ftp/python/3.8.3/Python-3.8.3.tgz
```

Extract the downloaded package using the command below.

```shell
tar -xf Python-3.8.3.tgz
```

Now, after you are done extracting the installation file, switch to the python source directory and run the following command.

Move to python source directory
```shell
cd Python-3.8.3
```

Then run command: 
```shell
./configure --enable-optimizations
```

After that, lets start the python build by using the following command.

```shell
make -j 8
```

Now, install the python binaries.

```shell
sudo make altinstall
```

Once that's finished, check if your python is installed correctly.

```shell
python3.8 --version
```

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/o7dho6qzfx2rn8tccmub.png)

Yup, its correctly installed. 👍 

## Installing the latest Python using Apt
This
First of, run the following commands to update your package list and install the prerequisites.

```shell
sudo apt update
sudo apt install software-properties-common
```

Next, add deadsnakes PPA to your system's resource list. PPAs are Personal Packages Archives that lets users upload Ubuntu source packages to be built and published as apt repositories.

```shell
sudo add-apt-repository ppa:deadsnakes/ppa
```

You will get prompted to press Enter. Press Enter to continue.

```shell
Press [ENTER] to continue or Ctrl-c to cancel adding it.
```

After you are done, install the python you desire. In this tutorial, we will be installing python 3.8

```shell
sudo apt install python3.8
```

After installation, verify if python is installed correctly.

```shell
python3.8 --version
```

Presto! We got it!
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/7mlf3agux5q79hpnrljb.png)
Coffe roasting site with focus on color spectrum 
Tags: css
Published: 2020-06-09 03:01:54

[Coffee site Demo](https://heggy231.github.io/chingu-webdev-speedrun-challenge/frontend/coffee)

- Some terminology:

  font color is called foreground and use css's `color` property

  background color uses css's `background-color` property

  [H](https://www.december.com/html/spec/colorhsl.html) in `hsl` is hue which measure of degrees of the color circle ranging from 0 to 360 (red = 0°; green = 120°; blue = 240°)

![color wheel hsl](https://discourse-user-assets.s3.dualstack.us-east-1.amazonaws.com/original/3X/8/0/8057d553e6cff0427048798efda3b08f0121476f.png)

To change the lightness - change l of hsl
To update the saturation - change s of hsl

More info on [hsl](https://www.freecodecamp.org/forum/t/the-basic-principles-of-web-design-a-guide-to-using-hsl-what-is-it-and-is-it-better-than-rgb/326663)

- When parent container has `position: relative`, the children elements with `position: absolute` are positioned relative to its parent's container.

  Demo:

```html
<div class="notice">
  <p>Don't close me!!</p>
  <img src="images/abs-pos-close.png" class="close" alt="close">
</div>
``` 

```css
.notice {
  position: relative;
}

.close {
  // close button is position relative to its parent
  //   container .notice
  position: absolute;
  left: 0;
  top: 0;
}
```

[In-dept explanation positioning](https://css-tricks.com/absolute-positioning-inside-relative-positioning/)
You probably don't need body-parser in your Express apps
Tags: javascript, node, webdev
Published: 2020-06-09 02:33:44

# What is body-parser?
Often, when I see a blog post or article describing an [Express.js](https://expressjs.com/) server, it usually starts out with something similar to the following:
```bash
npm init -y
npm i express body-parser
```
Followed by the classic
```js
const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());
// more express stuff
```

I used to have these four lines of code in practically *every* Express app I've ever made!

However, a few weeks ago I was poring over the [Express Docs](https://expressjs.com/en/api.html) and noticed that as of version 4.16.0 [(which came out three years ago!)](https://www.npmjs.com/package/express/v/4.16.0), [Express basically comes with body-parser out of the box!](https://expressjs.com/en/api.html#express.json)

# How do I use the Express version?
Well, you can pretty much just search `bodyParser`, and replace it with `express`!

This means our four lines of code above can be refactored into the following three lines of code:
```js
const express = require('express');

const app = express();
app.use(express.json());
```

If you are using [Babel](https://babeljs.io/) (which I would highly recommend!), you can even use a named import to make the code even more concise:
```js
import express, { json } from 'express';

const app = express();
app.use(json());
```
Persistence is a Skill 
Tags: productivity, motivation, newbie, persistence
Published: 2020-06-09 02:30:03


If you're a beginner, you've probably heard that persistence is an essential developer trait. "Try to solve it on your own. Don't just copy from Stack Overflow. Don't let yourself get stuck in tutorial hell. Build stuff. Practice, practice, practice." Certainly good advice. Yet it can be intimidating. 

I know it intimidated me. As a beginner, I reached a problem in my code. I had to look at the solution video. I wondered if maybe I wasn't cut out to be a developer, since I gave up so quickly. 

I have continued coding for 7 months now. When I started it was hard to force myself to work through a solution, because of how much easier it was to look it up. But I realized something had to change, if I was going to prepare myself to solve real-world problems - problems that don't have a solution video that I can run to when I get stuck. 

Persistence is a skill. If you are not persistent now, that doesn't mean you can't become a persistent person. Like any skill, you need to exercise your persistence. 

Here is my tip for becoming more persistent. When you feel like giving up, extend your work a few minutes beyond that point. But don't just try the same approach over and over hoping for it to "just work."  Try to see the problem from a different perspective. 

How? Write the problem out. You can scrawl a sloppy bullet list. You can vent your frustration in all caps. Whatever format you choose, articulating the problem forces you to actually figure out what the problem is. Once you know the true issue you are facing, you can tackle it and overcome it.

How is this related to persistence? Writing out the problem gives you something tangible to put your energy into when you feel like you're wasting your time glaring at an unforgiving computer screen. You will turn your frustration into a visible accomplishment. You will have a record of your problem to start with in your next coding session. But you will also have a record of not giving up to prove to yourself that you are becoming a more persistent programmer. 

Positive reinforcement of a persistent attitude will give you the courage to try it again next time you encounter a road block in your coding journey.
Docker 19.03 without sudo
Tags: docker, linux, sudo, virtualization
Published: 2020-06-09 02:11:31

## Summary

[Docker](https://www.docker.com) requires administrative privilege by default on some [Linux](https://kernel.org/) distros.
Therefore, in their cases, "permission denied" happens when using `docker` subcommands.

```console
$ docker pull centos:centos8
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post "http://%2Fvar%2Frun%2Fdocker.sock/v1.40/images/create?fromImage=centos&tag=centos8": dial unix /var/run/docker.sock: connect: permission denied

$ docker image ls
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get "http://%2Fvar%2Frun%2Fdocker.sock/v1.40/images/json": dial unix /var/run/docker.sock: connect: permission denied

$ docker build --tag image-name:version . -f ./some.dockerfile
ERRO[0000] failed to dial gRPC: cannot connect to the Docker daemon. Is 'docker daemon' running on this host?: dial unix /var/run/docker.sock: connect: permission denied 
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post "http://%2Fvar%2Frun%2Fdocker.sock/...": dial unix /var/run/docker.sock: connect: permission denied
```

They are solved by using [`sudo`](https://www.sudo.ws).
Well, so as not to use `sudo` frequently in development, it would be useful to let users be members of `docker`.

### Reference

[docs.docker.com](https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user) says:

> The Docker daemon binds to a Unix socket instead of a TCP port. By default that Unix socket is owned by the user `root` and other users can only access it using `sudo`. The Docker daemon always runs as the `root` user.
> 
> If you don’t want to preface the `docker` command with `sudo`, create a Unix group called `docker` and add users to it. When the Docker daemon starts, it creates a Unix socket accessible by members of the `docker` group.

## How-to

Here is how to do it. Replace "$MY_USER" with the real user name, please.

### Validate docker group exists

See your group list:

```console
$ cat /etc/group | grep docker
docker:x:***:
```

When it isn't found't, create first:

```console
$ #sudo groupadd docker
```

### Add the current user to docker group

Invite your user to `docker` group:

```console
$ sudo usermod -a -G docker $MY_USER
```

Validate:

```console
$ cat /etc/group | grep docker
docker:x:***:$MY_USER
```

### Logout, and login again

With GUI or runnning some command-line such as:

```console
$ #exec: xfce4-session-logout, gnome-session-quit, i3-msg exit, ...
```

## Conclusion

After all, it might get more comfortable, because the command-lines which failed will be successful :)

```console
$ docker image ls
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

$ docker container ls
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
```
BottomSheetDialog에서 ViewPager2, RecyclerView, NestedScrollView를 함께 사용할 때 겪은 문제 해결
Tags: android, viewpager2
Published: 2020-06-09 02:05:34

---
title: BottomSheetDialog에서 ViewPager2, RecyclerView, NestedScrollView를 함께 사용할 때 겪은 문제 해결
published: true
description: 
tags: android, ViewPager2
//cover_image: https://direct_url_to_image.jpg
---

며칠 간 나를 괴롭히던 문제들을 어제 드디어 해결했다.

BottomSheetDialog 안에 복잡한 UI가 들어간다. 상태에 따라 RecyclerView , NestedScrollView, ViewPager2 가 보였다 사라졌다 한판 흥겨운(...) 축제의 한마당이 펼쳐진다.

3가지 문제가 있었다.

## 1. 스크롤이 잘 안된다.

첫 화면은 `ViewPager2` 가 등장한다. 상태가 바뀌어 `ViewPager2` 가 gone 되고 `RecyclerView` 가 visible 한다. 근데 `RecyclerView` 스크롤이 안되는 것도 아니고, 잘 되는 것도 아니고 묘하게 버벅인다.

이전에도 NestedScrollView 와 RecyclerView 가 서로 왔다리갔다리 할 때 문제를 겪었다. 당시엔 현재 보이는 뷰에 `isNestedScrollEnabled` 를 true로, 보이지 않는 뷰엔 false로 주어 그나마 간단하게 해결했다.

하지만 이번엔 온갖 속성 (`enabled`, `isNestedScrollEnabled` 등등)을 주어봐도 제대로 해결이 되지 않았다. 자세히 살펴보니 좀 희안한 속성이 있었다. 이미 화면에서 사라진 `ViewPager2` 가 있었던 자리에선 스크롤이 잘 되고, 그 바깥 자리에선 스크롤이 안된다.

그래서 이런 말도 안되는 더미 뷰를 넣어봤다. 문제가 해결되었다. 왜 그런진 모르겠다 -_-;

```xml
<ConstraintLayout>
 <androidx.core.widget.NestedScrollView
        android:id="@+id/dummy"
        android:visibility="invisible"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_width="0dp"
        android:layout_height="0dp" />
 ...
</ConstraintLayout>
```

## 2. `TabLayout`을 이용해 표현한 `ViewPager2`의 indicator가 제대로 안보임

`ViewPager2`를 이용해 dot indicator를 보여주려면 좀 꼼수를 부려야 한다. 나는 [Android ViewPager(2) with dots indicator](https://medium.com/@adrian.kuta93/android-viewpager-with-dots-indicator-a34c91e59e3a)에서 소개한 방식을 썼다. `TabLayout`을 사용하고, 탭의 배경을 조정해서 보여줬다. 잘 동작했다. 

문제는 이 `TabLayout` 도 `ViewPager2`가 사라질 때 사라지고, 나타날 때 다시 나타나야 하는데, 다시 나타날 때 스크롤 위치를 제대로 표현하지 못했다. 항목이 아주 많을 경우 스크롤 포지션을 제대로 못잡는다. 물론 이렇게 항목이 많다면 ViewPager를 쓰는게 맞는지 UI 구성부터 다시 해야 하지만, 극히 예외적인 경우에 대한 테스트용도였다. 

이것도 엄청 삽질을 하다 결국 찾아낸 솔루션은 `TabLayout` 과 `ViewPager2`의 연결을 끊었다 다시 붙이는 방법이었다.

```kotlin
val tabLayoutMediator =
                TabLayoutMediator( tabLayout, viewPager2) { _, _ -> }

//초기에 붙였다가
tabLayoutMediator.attach()

//viewPager2 gone 될 때 떼었다가
tabLayoutMediator.detach()

//viewPager2 visible 될 때 다시 붙인다.
tabLayoutMediator.attach()
```

아 정말...

## 3. ViewPager2 의 좌우 항목이 안보인다.

`ViewPager` 시절부터 좌우 항목을 살짝 보이게 만들 수 있었다. `ViewPager2` 에선 `PageTransformer`를 통해 더 확장성이 좋지만 조금은 더 어렵게 구현할 수 있따. 이 내용은 [ViewPager2 파헤치기](https://blog.gangnamunni.com/post/viewpager2/) 이 글을 따라하면 쉽게 구현할 수 있다.

문제는 ViewPager2 가 다시 나타날 경우이다. 다시 나타날 때 저 `PageTransformer`가 제대로 적용이 되지 않은 상태로 나타나서, 좌우 항목이 안보이다 살짝 손을 대면 갑자기 튀어나온다.

이건 `ViewPager2.requestTransform()` 메서드를 써서 해결했다. 하지만 제대로 보였다 안보였다 문제가 있었다. 이 경우엔 그냥 마법의 30ms 딜레이를 주던지, 다른 layout callback을 쓰던지 해서 해결할 수 있을 것 같다. 나는 일단은 마법의 30ms 딜레이를 주었다.

```kotlin
viewPager.postDelayed(30) {
 viewPager.requestTransform()
}
```

일단 여기까지 해서 스크롤, dot indicator, page transform 문제는 다 해결이 되었다. 이 문제 해결하느라 한 5일 정도 쓴 것 같다. 안드로이드 개발 힘들어요 ㅠㅠ
Power of Two - LeetCode
Published: 2020-06-09 01:44:21

---
title: Power of Two - LeetCode
published: true
description: Easy Problem
tags: 
---

Given an integer, write a function to determine if it is a power of two.

**Algorithm:**

The intuition here is compare all the 2 ^ i values with n. If they are equal return true else if 2 ^ i is greater than n then return false

**Code:**

``` JS
/**
 * @param {number} n
 * @return {boolean}
 */
var isPowerOfTwo = function(n) {
    let cur = 0
    let temp = 1
    while(temp <= n) {
        if(temp == n) {
            return true
        }
        temp = Math.pow(2, cur);
        cur++
    }
    
    return false
};
```

**Alternative ways:**

``` JS
/**
 * @param {number} n
 * @return {boolean}
 */
var isPowerOfTwo = function(n) {
    return Math.log2(n)%1 === 0
};
```

``` JS
/**
 * @param {number} n
 * @return {boolean}
 */
var isPowerOfTwo = function(n) {
    return n < 1 ? false : Number.MAX_VALUE % n == 0
};
```
Event Propagation: Capturing, Bubbling
Tags: javascript, beginners, computerscience
Published: 2020-06-09 00:34:29

DOM event flow has three phases: Capture, Target, Bubbling phase.


```html
<html>

<head>
    <title>Event Propagation</title>
    <style>
        #parent {
            width: 200px;
            height: 200px;
            text-align: center;
            line-height: 3;
            background: green;
        }

        #child {
            width: 100px;
            height: 100px;
            margin: 0 auto;
            background: orange;
        }
    </style>
</head>

<body>
    <div id="parent">
        Parent element
        <div id="child">
            Children element
        </div>
    </div>
    <script type="text/javascript">
        var parent = document.getElementById("parent");
        var child = document.getElementById("child");

        document.body.addEventListener("click", function (e) {
            console.log("click-body");
        }, false);

        parent.addEventListener("click", function (e) {
            console.log("click-parent");
        }, true);

        child.addEventListener("click", function (e) {
            console.log("click-child");
        }, false);
    </script>
</body>

</html>
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/sne4e6a58fpcbqrgkou5.png)



#### Event Capturing
When clicking mouse or triggering dom event(here click child's div), browser will propagate event from outside to target,starting from root(document). 


See the code above, parent's listener were registered using a value of true in <code>addEventListener</code>

```javascript
parent.addEventListener('click', listener, true)
```

If third parameter is omitted, its default value is false and the listener is not a capturer. Then it is not event capturing, event bubbling instead.


#### Event Bubbling
Event Bubbling is other way around. Its event order is from target to outside(can be parent), going up back to root.
```javascript
child.addEventListener("click", function (e) {
            console.log("click-child");
        }, false);
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/obiiimhka9lltt9jxzse.png)

#### Summary
1.**Event Propagation order** : Capturing -> Target -> Bubbling
2.When event reaches target itself, all the listeners registered on the event target will be invoked, regardless of event capturing(true) or event bubbling(default or false).
#40daysofHybridCloud (Day-5)
Tags: aws, cloud, cloudfront, server
Published: 2020-06-09 00:18:32

##*#Day5*

Today I have learnt about <u><b>*CLOUDFRONT*</b></u>
I have given a brief idea about Cloudfront in my [previous post](https://dev.to/kaushiksahil16/40daysofhybridcloud-day-4-32kp).

today we will discuss little more about the same , like why it is used at the first place ? 

> Cloudfront is a kind of service in AWS which allow data present at certain places or location around the globe so that specific data can reach to the client without any delay or at low latency.

Cloudfront is using CDN(content delivery Network) which allow the content to be placed in all over the servers in the location where Data centers are not established , so this CDN stored the data in cache format specially for the  static content .

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/bu4d6y1ofmyp1opvwo8l.PNG)

###*Difference between static and dynamic content in terms of CDN*
- Static :- Content which are not subject to change like photos, videos etc .

- Dynamic :- the data which is subject to change like code files and database structures etc.

Now Edge Location are the locations where this CDN servers are present and help the static data to be stored in form of cache and the data which is not present will be delivered to edge location from Origin(Data center).

The process of providing data from edge loc to client  is called called Proxy method.

Now during this process of retriving data from CDN or Edge location there are two types of term used:- 
- HIT 
- MISS

Now this **HIT** is occurring when the data which is demanded by client is present on edge location then it is called as HIT or otherwise if Data is not present on Edge Loc then it is called as **MISS**.
After the MISS occur the request is sent to origin(S3 or EC2) by process called *forwarding*.


We can also make then access permissions for data stored in S3 by the Cloudfront only instead of client directly reaches to the S3 to get the data from the origin , In this way we can avoid getting  unwanted request to S3 .

With the above mention operation Cloudfront give us lot more flexibility in terms of choosing between the users or clients as we can also select which region to allow to see our content or website and which to not also called **<i>Geo Restrictions</i>**.

We often knew the terms called *Whitelist* and *Blacklist*

> the areas(IP's) where the access is given for the content in AWS services  is termed under <b>Whitelist</b>.

>the area or region where content is not displayed by services are called under <b>Blacklist</b>


Thanks,
*Happy Learning :)*