teleren/devto huggingface dataset:
JavaScript Declaring variables with var/let/const
Tags: javascript, beginners
Published: 2020-03-25 16:19:00

# var (variables)

||Redeclared|Reassignment|Run on old browser(like IE)|
|---|---|---|---|
|is possible|true|true|true|

`var` is function scope.

```javascript
function foo(){
    var x = 0;
    console.log(x); //output: 0
    var x = 1;
    console.log(x); //output: 1
    x = 2;
    console.log(x); //output: 2
    if (true){
        console.log(x); //output: 2
        x = 3;
        var y = "a";
        console.log(y); //output: a
    }
    console.log(x); //output: 3
    console.log(y); //output: a
}
```

Variables defined with 'var' can be called within that function because of function scope.

# let (variables)

||Redeclared|Reassignment|Run on old browser(like IE)|
|---|---|---|---|
|is possible|false|true|need transpiler(ex Babel)|

`let` is block scope.

```javascript
function foo(){
    let x = 0;
    console.log(x); //0
    let x = 1; //error  x has already been declared
    console.log(x); //0
    x = 2;
    console.log(x) //2
    if (true){
        console.log(x); //2
        x = 3;
        let y = "a";
        console.log(y); //output: a
    }
    console.log(x); //3
    console.log(y); //error y is not defined
}
```

The variable y defined in the if statement has scope only within the block of the if statement, so it cannot be used outside of it.

# const (constant)

||Redeclared|Reassignment|Run on old browser(like IE)|
|---|---|---|---|
|is possible|false|false|need transpiler(ex Babel)|

`const` is block scope.

```javascript
function foo(){
    const x = 0;
    console.log(x); //0
    const x = 1; //error x has already been declared
    console.log(x); //0
    x = 2; //error Assignment to constant variable.
    console.log(x); //0
    if (true){
        console.log(x); //0
        const y = "a";
        console.log(y); //a
    }
    console.log(y); //error y is not defined
}
```

Declaring in const allows you to define immutable values.

But objects are not immutable. For example, see the code below.

```javascript
function foo(){
    const like = {fruit: "apple", movie:"GODZILLA", food:"sushi"};
    console.log(like); //output: {fruit: "apple", movie: "GODZILLA", food: "sushi"}
    like.food = "rice";
    console.log(like); //output: {fruit: "apple", movie: "GODZILLA", food: "rice"}

    like = {fruit: "grape", movie: "GODZILLA", food: "rice"}; //However, this is not possible.
}
```

# hoisting

Variables declared using the var are hoisted.
But declared using the let and const are not hoisted.

```javascript
var x = 0;
function foo(){
    console.log(x);//output: undefined
    var x = 1;
    console.log(x);//output: 1
}
```
Why is undefined output on the first log!

JavaScript sets all variables declared by var in the function to 'undefined' when the function is declared

```javascript
function foo() { //x and y become undefined in this line
    var x = 0;
    var y = 1;
    let z = 2; //z is initialized at this line.
}
```

# Use properly

Don't use var!
Only allowed when trying on REPL...
My first Flutter Application
Tags: flutter, newbie, dart
Published: 2020-03-25 16:07:09

After an extensive bit of research and study, I made myself able to code my first Flutter application. The name of the application I did was Flutter Dice. It's a Flutter dice application. I took the help of Udemy and Youtube in making of this application. 

As a newbie to Flutter it was the first time I used stateful widgets in Flutter. The application has two pictures one on the left and the other on the right side that have buttons embedded on them. And a set of six pictures representing different dice heads were given as an asset.

![Application Screenshot](https://dev-to-uploads.s3.amazonaws.com/i/lrwod8x0fdr13k7p8t1o.png)


So when you click on a picture a button gets pressed. I made use of Dart Math library and used Math randomize to randomize the pictures on these buttons. When you click on one picture the left side and the right side picture would get randomize and a picture from the set of pictures that we gave in would appear in a randomized manner. No lags or pings would appear in the happening of this process. To the user, it would appear as if he's playing with a real-world dice.

![Code Snippets](https://dev-to-uploads.s3.amazonaws.com/i/nidz0rm3w0f205nq8xc1.png)


I have learned a lot by making this application. I was able to use the knowledge of Math libraries, Stateful widgets and more in this simple application. And thus I created my first Flutter Application.. :)
Hexagonal Architecture
Tags: java, architecture, principles
Published: 2020-03-25 15:58:49

<h2>1. Overview</h2>
<strong>Hexagonal Architecture is an architectural design pattern</strong> that makes the application highly maintainable and fully testable.
It keeps the important parts of the application isolated from outer components.
<strong>Components are integrated into the core through ports and adapters.</strong>
The core comprises business logic and domain layers.
Also known as Ports and Adapters Pattern it has a lot of benefits visible in the long term.
<strong>Above all, testing and changing the application are easy and cost-effective.</strong>
<img src="https://dev-to-uploads.s3.amazonaws.com/i/iexkpv3tc1uyaj60gv1c.png" alt="drawing" width="200"/>

<mark>The entire article was published at https://weinspire.tech on October 18, 2019.</mark>
Python: Dict setdefault and getdefault
Tags: python
Published: 2020-03-26 03:10:27

---
title: Python: Dict setdefault and getdefault
published: true
date: 2020-03-25 15:53:00 UTC
tags: Python
canonical_url: https://coderscat.com/python-dict-setdefault-and-getdefault
---

![2020_03_25_python-set-default.org_20200326_000322.png](https://coderscat.com/wp-content/uploads/2020_03_25_python-set-default.org_20200326_000322.png)

In this post, we will discuss dict’s `setdefault` and `getdefault` in Python.

These are two handy programming idioms in Python.

## getdefault

When we get the value from a dict, if the key does not exist in dict, a `None` will be returned.

```python
dict.get(key, default = None)
```

The second parameter for get is the default value. Here is an example:

```python
dict = { 'Name': 'Nick', 'Age': 23 }
print "Value : %s" % dict.get('Age')
print "Value : %s" % dict.get('Education', "Master")

# => Value : 23
# => Value : Master
```

## setdefault

Suppose We have a dict which recording the result of a examination:

```python
table = { "Nick" : "A", "Ada" : "B", "Mike": "B", "Leo": "C", "Sandy" : "D" }
```

We want to convert it to a dict with `grade -> list of names` so that we can check how many students in each grade. The result will be:

```python
{ "A" : ["Nick"], "B" : ["Ada", "Mike"], "C" : ["Leo"], "D" : ["Sandy"] }
```

A beginner maybe will write the code in this way:

```python
table = { "Nick" : "A", "Ada" : "B", "Mike": "B", "Leo": "C", "Sandy" : "D" }
result = {}
for name, score in table.items():
    if score not in result:
        result[score] = [name]
    else:
        result[score].append(name)

print(result)

# => {'A': ['Nick'], 'C': ['Leo'], 'B': ['Mike', 'Ada'], 'D': ['Sandy']}

```

In each iteration, we need to check whether the new key exists in the result.

A more pythonic way is using `setdefault` :

```python
table = { "Nick" : "A", "Ada" : "B", "Mike": "B", "Leo": "C", "Sandy" : "D" }
result = {}
for name, score in table.items():
    g = result.setdefault(score, [])
    g.append(name)

print(result)

# => {'A': ['Nick'], 'C': ['Leo'], 'B': ['Mike', 'Ada'], 'D': ['Sandy']}

```

The code can be more simpler if we use `defaultdict`, but the result is an object of defaultdict:

```python
table = { "Nick" : "A", "Ada" : "B", "Mike": "B", "Leo": "C", "Sandy" : "D" }
from collections import defaultdict

result = defaultdict(list)
for name, score in table.items():
    result[score].append(name) # all keys have a default already

print(type(result))
print(result)

# => <type 'collections.defaultdict'>
# => defaultdict(<type 'list'>, {'A': ['Nick'], 'C': ['Leo'], 'B': ['Mike', 'Ada'], 'D': ['Sandy']})

```

The post [Python: Dict setdefault and getdefault](https://coderscat.com/python-dict-setdefault-and-getdefault) appeared first on [Coder's Cat](https://coderscat.com).
Chrome 79 から WebXR Device API が有効になるも Oculus 系の HMD が認識されない件とその解決方法について
Tags: webvr, webxr
Published: 2020-03-25 15:46:49

---
title: Chrome 79 から WebXR Device API が有効になるも Oculus 系の HMD が認識されない件とその解決方法について
published: true
description: 
tags: WebVR, WebXR
---

```
この記事は 2019-12-20 JST 付で Qiita に投稿したものです。
```

```
2020-08-25 時点で最新の Chrome v84 では本記事の方法で対応できません。
```

## TL;DR

Ref. https://twitter.com/ikkou/status/1207912623443865600

## Chrome 79 で WebXR Device API が正式サポートされました🎉

`WebXR Device API` はブラウザから Oculus Rift S をはじめとする (VR|AR|MR) HMD の情報を取得するための API です。

2019/12/20 現在の「メジャーなブラウザ」では Chrome 79 以降のみが「標準で」対応しています。
この「メジャーなブラウザ」というところが肝です。

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

source. https://caniuse.com/#search=WebXR

## Chrome 78 以前はどうだったのか?

`chrome://flags` から以下のフラグを `Enable` にすると Chrome で `WebXR Device API` を通して Oculus Rift S で `WebXR` を楽しむことができました。

* `WebXR Device API`: Enabled
* `Oculus VR support`: Enabled
* `XR device sandboxing`: Disabled

ここで言う `WebXR` を楽しむというのは、[WebXR Sample Pages](https://immersive-web.github.io/webxr-samples/) で `Yes!` が表示され、各サンプルで `ENTER VR` が表示される状態を指しています。

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

`WebXR Device API` に対応している場合に表示されるテキスト
source: https://immersive-web.github.io/webxr-samples/

なお Firefox のように、まだ `WebXR Device API` に対応していない場合でも `WebVR API` へのフォールバックで概ね体験可能です。

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

`WebXR Device API` あるいは `WebVR API` へのフォールバックで VR HMD が認識されているときに表示される状態
source: https://immersive-web.github.io/webxr-samples/immersive-vr-session.html

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

VR HMD が認識されていないときは `VR NOT FOUND` が表示される
source: https://immersive-web.github.io/webxr-samples/immersive-vr-session.html

## Chrome 79 でどうなったのか?

まず `WebXR Device API` は標準対応となったため、`chrome://flags` から変更する必要がなくなりました！

標準対応となったので「これだけでいける！」と思っていましたが、実は Oculus Rift/Rift S に関しては別途フラグを立てる必要がありました。もともと `Oculus VR support: Enabled` を指定していたので、それかと思うとこのフラグは消えていていました！

結論として `Oculus VR support` に代わる `Oculus hardware support` を `Enable` にする必要がありました。

Ref. https://twitter.com/kettlecorn/status/1207880549991366656

## Chrome 79 以降で `WebXR` を動作させるために必要なこと

* `Oculus hardware support` = `chrome://flags/#oculus-vr` を `Enabled` に変更
* `XR device sandboxing` = `chrome://flags/#xr-sandbox` を `Disabled` に変更
* Chrome を再起動

上記の設定で 2019/12/20 現在 Chrome Beta, Chromium の最新バージョンである v81 まで動作することを確認しています。

## 2019/12/20 現在、WebXR Device API に「真の標準対応」しているブラウザは Oculus Browser だけ！

Ref. https://twitter.com/wakufactory/status/1207924277044867077

本記事では一切のフラグ変更を必要としないことを「真の標準対応」と表現していますが、これは W3C として定義している用語ではありません。そして Oculus Browser は決してメジャーなブラウザではない異端児です。

現場からは以上です。

---

Special Thanks: OE Waku さん - https://twitter.com/wakufactory
自分の Qiita の投稿を markdown で全て手元に落とす
Tags: zsh, qiita
Published: 2020-03-25 15:40:21

---
title: 自分の Qiita の投稿を markdown で全て手元に落とす
published: true
description: 
tags: zsh, qiita
---

何らかの事情で Qiita に書いた自分の投稿は手元に残したいときのスクリプト

## 環境
- macOS 10.15.3
- zsh 5.8 (x86_64-apple-darwin19.3.0)

## 落とすやつ

```bash
❯ user_id=<your_qiita_id>
❯ curl -s "https://qiita.com/api/v2//users/${user_id}/items?per_page=100" \
  | jq -r ".[].url" \
  | xargs -n1 -I{} bash -c "curl -s  {}.md > \$(echo {} | awk -F / '{print \$NF}').md"
```

100記事以上投稿している場合は`&page=2` とかで遷移させればよさそう
https://qiita.com/api/v2/docs#%E3%83%9A%E3%83%BC%E3%82%B8%E3%83%8D%E3%83%BC%E3%82%B7%E3%83%A7%E3%83%B3
100daysofcode Flutter
Tags: 100daysofcode, flutter
Published: 2020-03-25 15:36:20

day 16/100 of #100daysofcode #Flutter
Belajar Flutter , dari kursus Udemy from
@maxedapps

Learning about Enum,sample use switch case, another model item, Widget Cliprrect
https://github.com/triyono777/100-days-of-code/blob/master/log.md
Welcome Thread - v66
Tags: welcome
Published: 2020-03-25 15:33:48

---
title: Welcome Thread - v66
published: true
description: Welcome to DEV! A thread of hellos and intros.
tags: welcome
---

![wonka welcomes you!](https://media.giphy.com/media/FJSKYf51xLbvq/giphy.gif)

### Welcome to DEV!

1. Leave a comment below to introduce yourself! You can talk about what brought you here, what you're learning, or just a fun fact about yourself.

2. Reply to someone's comment, either with a question or just a hello. 👋 

**Great to have you in the community!**
Windows zero-day vulnerability ADV200006: How to disable preview pane and details pane in Explorer
Tags: security, windows, vulnerabilities, commandline
Published: 2020-03-25 15:33:44


### Windows Zero-Day Remote Code Execution Vulnerability

"ADV200006 | Type 1 Font Parsing Remote Code Execution Vulnerability", a zero-day vulnerability in the Windows 7, was [reported](https://portal.msrc.microsoft.com/en-us/security-guidance/advisory/adv200006) on 2020-03-23, which is said to be less effective in Windows 10.

### How To Mitigate It

As one of the workarounds, Microsoft suggests to:

> Disable the Preview Pane and Details Pane in Windows Explorer

### Keyboard Shortcuts

Ones of the easiest ways are to use the shortcuts in Explorer with your keyboard:

1. Alt + "P" toggles "Preview Pane".
2. Alt + Shift + "P" toggles "Details Pane".

### Command Lines

By the way, here are the ways to use command lines to edit registries.
They are suitable for automation and bulk batch execution.

__Caution__: Editing registries in wrong ways can break your computer.

First, run command prompt as an administrator.
For example, press Windows + "R" to open the "Run" box, type "cmd" into it and then __press Ctrl + Shift + Enter__. You'll get the prompt after permission's asked.

#### #1. Disable Preview Pane

Add `NoReadingPane` value as DWORD and set 1 as its data in it as below:

```Shell
reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer /v NoReadingPane /t REG_DWORD /d 1 /f
```

_Note_: "HKCU" means "HKEY_CURRENT_USER". `/f` is an option to overwrite the value without confirmation.

Once you sign out and sign in again, the Preview Pane in your Explorer will be disabled.

---

- How to restore it    
    
    ```
    reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer /v NoReadingPane /d 0 /f
    ```

---

#### #2. Disable Details Pane

Edit `IconsOnly` value's data as below:

```
reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced /v IconsOnly /d 1 /f
```

Once you sign out and sign in again, the Details Pane in your Explorer will show just icons instead of rendered content like thumbnails.

---

- How to restore it    
    
    ```
    reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced /v IconsOnly /d 0 /f
    ```
    
---

Here, the two panes are disabled.
The Explorer looks like this.

![disabled preview and details](https://dev-to-uploads.s3.amazonaws.com/i/fm49l62tyirooqt39q6u.png)
Headless Testing with Puppeteer
Tags: puppeteer, chrome, jest, testing
Published: 2020-03-25 15:28:35

Puppeteer is a popular open-source library, built to control a headless instance of the Chrome and Chromium browser.

Puppeteer is used to automate any action you can perform in the browser. You can use it to automate flows, take screenshots and generate PDFs.
It is compatible with Chrome, Firefox and Microsoft Edge (Chromium).


##Why should you use Puppeteer?
There are multiple reasons why you should want to use Puppeteer.
Some of the more popular reasons include:

- Generating PDFs
- Taking screenshots

###Generating PDFs
Let's say you want to generate a PDF of a specific webpage, for example an invoice that your customer can download. Instead of setting up a third-party tool like wkhtmltopdf, you can choose Puppeteer.

Generating PDFs through the Chromium browser will deliver a pixel-perfect PDF.
Puppeteer provides [multiple different options](https://github.com/puppeteer/puppeteer/blob/v2.1.1/docs/api.md#pagepdfoptions) to customise the PDF file, ranging from orientation and scale to margins and formats.


###Taking screenshots
Puppeteer makes it easy to take screenshots from any web page. There are some options to customise the screenshot, including quality, clipping and other formatting options.


##Why should I use Puppeteer for Headless Testing?
Yes, it's true that there are alternative solutions, such as Selenium. But we believe there's a couple of reasons why you should go for [Headless Testing](https://headlesstesting.com) with Puppeteer:

- Puppeteer uses the DevTools Protocol, this is a protocol built into Chrome/Chromium and optimised for both accuracy and performance.
- Headless is enabled by default. Contrary to Selenium, running tests in headless mode is a lot faster, because the browser does not have to do any visible rendering during the test.
- Selenium WebDriver uses the HTTP protocol to send and receive commands between the client and the node. Puppeteer uses a WebSocket tunnel, which 
means less latency and faster tests.

##How to run tests with Puppeteer
A popular package to run automated tests with Puppeteer is called Jest-Puppeteer.
This open-source package allows you to use Jest as a test runner with Puppeteer.

If you include a package called expect-puppeteer, you can write automated tests in a clean way, see this example:

```javascript
import 'expect-puppeteer'

describe('Google', () => {
  beforeAll(async () => {
    await page.goto('https://google.com')
  })

  it('should display "google" text on page', async () => {
    await expect(page).toMatch('google')
  })
})
```

This will launch a browser on your local machine and run the test in headless mode. You will receive a test status back from Jest.


###Running Headless Tests in the Cloud
The next step is to run all the tests you've created with a CI (Continuous Integration) system.

You could use a cloud provider such as [HeadlessTesting](https://headlesstesting.com) to have your Puppeteer scripts connect with the browsers in our grid. Then you can run multiple tests in parallel, drastically shortening the total test duration of your test suite.
Multiple tests run in bulk using Bash
Tags: testing, bash, shell, basics
Published: 2020-03-25 15:24:24

Having briefly explained what a test is we can come to an inevitable conclusion that having only a single test is never enough.
We usually write a lot of them and it is useful to group them. 

Assuming that the tests we are using conform to the contract of returning proper exit statuses, the whole group can technically be treated like a single test.

Let's put them inside a `tests.sh` script:

```bash
test -f file-a.txt
test -f file-b.txt
test -f file-c.txt
```

Now, (I assume that the script is an executable file) let's run it:

```bash
./tests.sh
echo $?
# returns: 1
```

All is well. The required files do not exist, so the test is failing.

Create the files one by one and run the test each time:

```bash
touch file-a.txt
./tests.sh
echo $?
# returns: 1
touch file-b.txt
./tests.sh
echo $?
# returns: 1
touch file-c.txt
./tests.sh
echo $?
# returns: 0
```

All is well again. The test passes.

Now, let's make sure the test is solid.
Delete the first file and run the test again.

```bash
rm file-a.txt
./tests.sh
echo $?
# returns: 0
```

Wait, what? The test returns `0`? It should fail!

The thing is that when we put some commands into a script, only the last one's return status is returned by the script itself.
To ensure that the script will exit when a command within that script exits with a non-zero status, we use the [`set`](https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html) bash builtin with the `-e` option.

Put `#!/bin/bash` (just to make sure we will be running Bash) on the first line and `set -e` on the second line of the test script and run it yet again.

Now the test fails as it should.

### Run a series of tests to ensure all relevant situations are being checked.

```bash
rm file-?.txt

./tests.sh
echo $? # should return 1

touch file-a.txt
touch file-b.txt
touch file-c.txt
./tests.sh
echo $? # should return 0

rm file-a.txt
./tests.sh
echo $? # should return 1

touch file-a.txt
rm file-b.txt
./tests.sh
echo $? # should return 1

touch file-b.txt
rm file-c.txt
./tests.sh
echo $? # should return 1
```

This shows the general idea behind testing.

I have been purposefully avoiding using the terms [`test cases`](https://en.wikipedia.org/wiki/Test_case) and [`test suites`](https://en.wikipedia.org/wiki/Test_suite) as they are usually more abstract concepts I do not wish to get into here.
Getting Hired & Succeeding in your first year as a dev: ZTM Instructor AMA
Tags: hiring, career, codenewbie
Published: 2020-03-25 15:24:05

<br>

[ZTM Academy](https://zerotomastery.io/academy?utm_source=devto&utm_medium=yihuaama) Instructor, [Yihua Zhang](https://zerotomastery.io/about/instructor/yihua-zhang?utm_source=devto&utm_medium=yihuaama) answers the most upvoted student community questions in this AMA style video.

The theme of this AMA was about how to get hired in the software industry and how to succeed in your career, especially your first year. Yihua answers questions about getting your first job, your next job, your dream job and everything in between!

Yihua has experience starting his own company, working at a top development agency and has gone through the interview process at big companies like Google and Facebook.

**Just a few of the topics covered:**
1. Differences between getting hired at startups vs. enterprise vs. FAANG
2. How to prep and know when you're "ready"
3. The HR process
4. What's next after getting hired
5. Workplace culture
6. Imposter syndrome

**Additional resources:**
1. [Don't be a Junior Developer](https://zerotomastery.io/blog/dont-be-a-junior-developer?utm_source=devto&utm_medium=yihuaama)
2. [How To Become A Senior Developer](https://zerotomastery.io/blog/developers-edge-how-to-become-a-senior-developer?utm_source=devto&utm_medium=yihuaama)
3. [Master the Coding Interview: Data Structures + Algorithms](https://academy.zerotomastery.io/p/master-the-coding-interview-data-structures-algorithms?utm_source=devto&utm_medium=yihuaama) (top-rated Zero To Mastery course that walks you step-by-step through a lot of the topics discussed in this AMA)
4. Currently on the job hunt? One of the places we recommend is [Seen by Indeed](https://links.zerotomastery.io/seen_blog). Seen is a platform that helps software engineers find jobs at top tech companies. It's 100% free for all candidates (students) and gives you Career Coaching, Resume Review, Interview Prep and Salary Negotiation. They charge the recruiter, so if you are a good candidate, they get you hired and they make money through the company and not you... (it's free to you). Seen tries to find you a job from their list of 7,500 companies. Evaluate if this is something you want to attempt but we've heard quite a few people who have had a good experience with this... keep in mind this our affiliate link but we think they are doing something great.

**Without further ado... (click the image below to watch full AMA)**

[![Zero To Mastery Instructor AMA: Getting Hired & Succeeding in Tech](https://images.ctfassets.net/aq13lwl6616q/dNjYkJhb6X2zdC9DlV54G/6132a676ac2854ef3aabe79fd53bb1aa/Youtube_AMA_Yihua_Thumbnail.PNG)](https://www.youtube.com/watch?v=b_QrKEcZk3I)


<br>

*****

<br>

__Thank you for watching. If you enjoyed this AMA and want to get more like it in the future, make sure to subscribe on [our blog](https://zerotomastery.io/blog?utm_source=devto&utm_medium=yihuaama). If enough people subscribe, we'll keep making them!__