teleren/devto huggingface dataset:
React: Context, Custom hooks and multiple components problem
Tags: react
Published: 2021-07-10 13:07:17

I had a problem with updating state in my app, which drove me mad. After creating a simplified version in CodeSandbox, and a lot of Googling I eventually figured out the problem.

## The set up
My app contains two components, Button and Text.

Button contains a button. When you click it, it runs a function on a custom hook to update the state, which is in the Context API.

Text shows the state on the page.

## The problem

Here's the **non-working** version in CodeSandbox. If you click on the button you'll see a message in the console, but the text doesn't change.
{% codesandbox brave-bush-hohi0 %}

In app.tsx in this version, the return statement is:
```
 <Button />
 <MyContext.Provider value={{ myState, setMyState }}>
   <Text />
 </MyContext.Provider>
``` 
Which makes sense initially because Text is showing the state, but Button is just running a function on the custom hook. The function sets the state, not Button.

## The solution

Here's the **working** version in CodeSandbox. If you click on the button you'll see a message in the console and the text changes.
{% codesandbox trusting-hoover-b2rx9 %}

In app.tsx in this version, the return statement is:
```
 <MyContext.Provider value={{ myState, setMyState }}>
   <Button />
   <Text />
 </MyContext.Provider>
``` 
The difference here is that Button is inside the Context Provider.

## Why it works

I'm not sure, but I presume it's because Button is setting the state, albeit not via the custom hook, therefore Button also needs to be inside the context provider.

Can anyone confirm/deny/explain?

## CodeSandbox

I also learnt how useful CodeSandbox is. I've done some React in CodePen and found it a pain, but CodeSandbox is much easier. You just tell it you want to create a React app and it uses Create React App, like you would on your computer, only it's much quicker. And then you can have as many files of whatever type as you need, the same as you would on your computer. And it saves everything automatically.
MENA Game Tech Day 2021 - Building a real-time leaderboard with serverless on AWS
Tags: aws, serverless, gaming
Published: 2021-07-10 12:39:20

---
title: MENA Game Tech Day 2021 - Building a real-time leaderboard with serverless on AWS
published: true
description: Resources for MENA Game Tech Day 2021 on building a real-time leaderboard with serverless on AWS
tags: aws,serverless,gaming
// cover_image: https://cdn.grosch.se/dev-to/lets-build-series/lets-build-series-building-an-event-driven-application-in-the-cloud.png
---

This post contains resources for MENA Game Tech Day 2021 on building a real-time leaderboard with serverless on AWS.

#### AWS Game Tech
https://aws.amazon.com/gametech/

#### Build a real-time leaderboard with Amazon Aurora Serverless and Amazon ElastiCache
https://aws.amazon.com/getting-started/hands-on/real-time-leaderboard-amazon-aurora-serverless-elasticache/

#### How to Build a Real-Time Gaming Leaderboard with Amazon DynamoDB and Rockset
https://aws.amazon.com/blogs/apn/how-to-build-a-real-time-gaming-leaderboard-with-amazon-dynamodb-and-rockset/

#### Building serverless applications with streaming data
https://aws.amazon.com/blogs/compute/building-serverless-applications-with-streaming-data-part-1/
https://aws.amazon.com/blogs/compute/building-serverless-applications-with-streaming-data-part-2/
https://aws.amazon.com/blogs/compute/building-serverless-applications-with-streaming-data-part-3/
https://aws.amazon.com/blogs/compute/building-serverless-applications-with-streaming-data-part-4/
https://aws.amazon.com/blogs/compute/building-serverless-applications-with-streaming-data-part-5/
https://github.com/aws-samples/serverless-streaming-data-application

#### Introduction to Scalable Game Development Patterns on AWS Whitepaper
https://d1.awsstatic.com/whitepapers/aws-scalable-gaming-patterns.pdf

If you have any questions, please reach out on [Twitter](https://twitter.com/GunnarGrosch) or [LinkedIn](https://www.linkedin.com/in/gunnargrosch/). Go build!
Cara Mudah SET NODE_ENV ke Production atau Development
Tags: node, nextjs, javascript, programming
Published: 2021-07-10 12:11:36

Kali ini, kita akan membahas bagaimana kita membuat aplikasi Node.Js menjadi Production atau Development. Terdapat banyak cara untuk melakukannya, tergantung dengan apa kita akan melakukanya. Kali ini kita akan mencoba melakukan set `node_env` ke production atau development dengan menggunakan beberapa cara.

Cara melakukannya cukup mudah, yaitu hanya cukup menggunakan command prompt atau power shall, sebelum memulai aplikasi Node.js kita. Berikut beberapa cara untuk melakukan set `node_env` pada aplikasi Node.Js kita.

##Linux (unix based system lainnya)
Untuk yang menggunakan OS Linux atau unix based system lainnya, dapat menggunakan perintah berikut ini:
```
export NODE_ENV=production
```

##Windows
Apabila kita menggunakan OS Windows kita bisa menggunakan perintah berikut ini:
```
SET NODE_ENV=production
```

##PowerShell
Apabila kita menggunakan PowerShell kita dapat menggunakan perintah berikut ini:
```
$env:NODE_ENV="production"
```

##Set Setiap Running
Kita juga bisa melakukan set di setiap running aplikasi kita dengan menggunakan perintah berikut ini, tapi perintah ini hanya akan berlaku untuk aplikasi tertentu yang sedang kita running tidak secara global. Cara ini dapat digunakan untuk melakukan testing pada aplikasi kita:
```
NODE_ENV=production node app.js
```
Kebanyakan akan menemui error saat menggunakan perintah di di atas, seperti berikut:
```
'NODE_ENV' is not recognized as an internal or external command
```
Untuk melakukan set node_env dengan perintah di atas, perlu untuk install dependensi berikut [win-node-env](https://github.com/laggingreflex/win-node-env), dengan cara menuliskan perintah berikut ini:
```
npm install -g win-node-env
```

##Menggunakan Package
Cara lain, kita dapat menggunakan package tersendiri untuk melakukan set node_env, yaitu dengan menggunakan package [cross-env](https://www.npmjs.com/package/cross-env).

***

##Catatan
Saat mengubah `NODE_ENV` ke dalam mode production, semua `devDependencies` pada file package.json akan diabaikan semuanya saat melakukan running aplikasi. kita juga dapat menggunakan perintah berikut ini:
```
npm install --production
```
untuk dokumentasi lengkap dapat dilihat [di sini](https://docs.npmjs.com/cli/v7/commands/npm-install/).
Daily Developer Jokes - Saturday, Jul 10, 2021
Tags: jokes, dailydeveloperjokes
Published: 2021-07-10 12:00:15

---
title: "Daily Developer Jokes - Saturday, Jul 10, 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=Saturday%2C%20Jul%2010%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/5e1258cecd22f.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 squeak?

___A:___ Because someone stepped on its mouse!
 -->
Can I contact with a experience to discuss and learn from him?
Tags: android, kotlin, firebase
Published: 2021-07-10 11:36:19

I'm a beginner in Android programming and I have some questions to fully understand how to code.

I have learned Kotlin language to programming my first app. And I wanna make firebase as a database.

And on other hand I have a lot of questions in Gradle. and I need to know its answers.

So I need to contact with an experience in Android + Kotlin + Firebase .. To discuss with him and learn from him
The danger of overusing primitive types
Tags: softwareengineering, kotlin
Published: 2021-08-06 18:51:09

---
title: The danger of overusing primitive types
published: true
date: 2021-07-10 11:13:16 UTC
tags: Softwareengineering,Kotlin
canonical_url: https://www.rockandnull.com/the-danger-of-overusing-primitive-types/
---

 ![The danger of overusing primitive types](https://images.unsplash.com/photo-1478486982180-2de2fafa19f9?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwxMTc3M3wwfDF8c2VhcmNofDI0fHxzYWZldHl8ZW58MHx8fHwxNjI1OTE1MzU4&ixlib=rb-1.2.1&q=80&w=2000)

From early on, I was taught that primitive types in Java are the most performant and I need to prefer them when I can.

While this is true, since primitive types are much more lightweight than regular objects, overusing them creates a different kind of problem. Pretty much everything can be represented by a combination of strings and numbers. For instance, whether you need to represent an id for a user or an entity owned by the user (e.g. a blog post), you can use a `long`.

Although this might seem innocent, it's extremely error-prone. Having a method that removes a user and another that removes an entity owned by the user will both accept a `long` in our example.

```
fun deleteUser(long userId) {
    [...]
}

fun deleteBlogPost(long postId) {
    [...]
}
```

If someone is confused and passes the wrong id type, the best-case scenario is that a failure will be thrown at runtime and the worst-case scenario is that the wrong thing will be deleted (assuming both namespaces have an object with the same id). When error-prone situations such as these are identified, it's better to be proactive and set up practices that will avoid them.

There's an easy solution for these types of errors: create domain-specific types by wrapping the primitive types. In our previous example, you can have a `UserID` and `BlogPostId` classes that just contain a `long`.

```
fun deleteUser(UserId userId) {
    [...]
}

fun deleteBlogPost(BlogPostId postId) {
    [...]
}
```

This way a method for deleting a user and a method deleting a post will have different parameter types. In case of confusion where the wrong kind of id is passed, it will be caught on compile time.

Of course, using this approach has a performance hit. The wrapping and unwrapping of objects will cost a few more milliseconds. If your application is not performance-sensitive I think it's worth the cost. If not, take a look at [Kotlin inline classes](https://kotlinlang.org/docs/inline-classes.html) and the upcoming [Java inline classes](https://www.infoq.com/articles/inline-classes-java/) feature that are designed to solve exactly this issue.

Happy coding!
Databricks and PyODBC - Avoiding another MS repo outage
Tags: databricks, spark, pyodbc
Published: 2021-07-10 10:21:32

Not so long ago Microsoft suffered an outage with their package repo over at https://packages.microsoft.com. The short version is that it looks as though the `pools` directory was removed, forcing Microsoft to synchronize everything back out. Of course the outage started pushing traffic to other end-points which added bottlenecks and it was just a lot of pain for around 26 hours.

Whilst this affected a lot of devs for a variety of projects, the one I was more affected by was the impact on Databricks environments which were pulling in the Linux ODBC driver for Microsoft SQL Server. The standard init script for doing this relies on installing the packages at the point the cluster is created. If the repo isn't available then the init script takes longer to run, fails, but the cluster still runs; it just breaks anything which needs the driver.

I wanted to come up with a way to try and prevent this happening again. Whilst it's unlikely to happen again, adding some resiliency is never a bad thing.

So I created a Databricks notebook which downloads the package and it's dependencies from the Microsoft repo to the cluster. It does this by downloading each required package, when they have all successfully completed it swaps out the current set of files with the new ones. If any of the files can't be downloaded for any reason then the existing files are left intact. The init script uses these downloaded files instead to install the driver. In the event of another outage the local files are not replaced and the cluster will start up as normal with the previously downloaded packages.

Each time the packages are successfully downloaded the script updates the init script, just in case any more packages have been added or the file locations have been changed.

```python
try:
    # Download packages
    if previous.exists():
        shutil.rmtree(previous)

    shutil.move(current, previous)
    shutil.move(new, current)
except:
    # Remove any newly downloaded files
    shutil.rmtree(next)
```

The notebook is available on [GitHub](https://github.com/dazfuller/databricks/tree/main/mssql-odbc-driver) as both an `ipynb` and `dbc` file. Hopefully someone else finds it useful.
React Xper - A developer's guide to experiment React 👨‍🔬
Tags: react, reactxper, experiments, javascript
Published: 2021-07-10 10:13:28

React Xper is a experimental website to test out the
many concepts of ReactJS and its related libraries.
The beautiful UI is bootstrapped with Grommet v2 with a little bit of styled-components custom styling. Dark mode is available too 🧛‍♂️ .

> #### The main purpose of this website is to experiment almost any technologies with ReactJS. 👨‍💻

So far, it is currently focused mainly on the new React hooks such as useEffect, useReducer, useMemo and internationalization library such as react-intl. ㊗️

Whenever I have an idea or two and want to try it out as a proof-of-concept, I will use this boilerplate to add-on.
Moreover, it has a brief technical explanation in every post so other people can also visit the pages and have an understanding. 👍🏻

Although there's only like 4 lab experiments , I expect it to grow in the future.

> #### All the science about ReactJS will be happening there for sure.

Please visit https://react-xper.vercel.app/ to check it out.
Or if you would like to contribute or make experiments on your own, create a branch and pull request at https://github.com/m3yevn/react-xper

Thanks for reading & Stay safe! 😷
How To Quit Vim
Tags: vim
Published: 2021-07-10 09:59:05

---
title: How To Quit Vim
published: true
description: Quit Vim in using these simple steps
tags: vim
canonical_url: https://blog.godswillumukoro.com/how-to-quit-vim
cover_image: https://res.cloudinary.com/dlwivxwf8/image/upload/v1625911090/goran-ivos-T8LMIN09-mo-unsplash.jpg
---

Lately, I found myself playing with a lot with Amazon LightSail with the goal of hosting LAMP stack applications. At first, I didn't really like it, but the more I tinkered with LightSail did I get more comfortable with the service.

Then it got to the point where I had to edit documents directly from the terminal and `vim document.php` was the first thing that came to mind. After making all my edits, It was time to close vim and continue with my adventure in the world of terminals, then I recalled all the funny memes about the strange impossibility of quitting vim 😅

## Step One: Remember to Escape
Hit `esc` key on your keyboard

## If No Changes Were Made: Quit Vim
Type this command `:q` accompanied by the `enter` key on your keyboard

## Save changes and Quit Vim
Type this command `:x` accompanied by the `enter` key on your keyboard

## Quit Vim Without Saving Changes
Type this command `:q!` accompanied by the `enter` key on your keyboard

>I hope you found this useful. Happy coding!
How to run nested tmux session
Tags: bash
Published: 2021-07-10 09:44:47

[tmux](https://github.com/tmux/tmux/wiki) is a program that provides convenient way for getting multiple terminal sessions into one window. If you are using it a lot, quickly you can find yourself asking for more - multilevel tmux. Example of nested tmux session:

{% asciinema 424818 %}

There are 2 settings necessary for this set up to work as expected. Inside `~/.tmux.conf` you need:
```
bind-key -n c-g send-prefix
bind-key -n c-t send-keys c-g
```

for prefix key access to nested windows. The default prefix is ctrl+b, so here I'm setting `ctrl+g` to work as prefix on the second level of tmux, and `ctrl+t` to work on the third level.

Thanks to configuration like this, if you use `ctrl+b` & `c` to create a new window on the first level of tmux, you will use:
* `ctrl+g` & `c` - to create window on the second level
* `ctrl+g` & `c` - to create window on the first

The other setting is inside your `.zshrc` or `.profile`:

```
unset TMUX
```

If we skip this, we will end up seeing:

```
$ tmux new -s test
sessions should be nested with care, unset $TMUX to force
```

# Summary
In this short guide we have seen how to set up our tmux to support nesting with minimal configuration & nice mapping for prefix key. Let me know in the comments if you are interested in more tmux or command line tips.
ติดตั้ง NGINX Plus แบบขี้เกียจ
Tags: ubuntu, nginx, nginxplus
Published: 2021-07-10 09:17:50

หลังจากที่ไม่ได้จับ NGINX มาสักพัก มัวแต่ไปนั่งเล่นอย่างอื่นอยู่ แต่พอดีว่าช่วงนี้งานเข้า NGINX รัว ๆ ก็เลยต้อง setup ระบบไว้เตรียมบรรยาย ... แต่มาคราวนี้รู้สึกขี้เกียจ ไม่อยากทำอะไรยุ่งยาก เก็บพลังงานไว้ดีกว่า ... ด้วยความที่เพิ่งไปสอน Ansible มา เห็นว่า NGINX ทำ collection ใหม่ไว้หลายอย่างเลย ลองแวะไปดูให้ละเอียด ... มี Ansible playbook สำหรับติดตั้ง NGINX Plus นินา ก็เลยบันทึกประสบการณ์แบบขี้เกียจ ๆ มาให้ลองอ่านดูครับ

###สิ่งที่ต้องเตรียม
  - server Ubuntu Server 20.04.2 LTS 
  - Key และ ​Certificate ที่เป็น Subscription ของ NGINX Plus เก็บที่ $HOME/nginx-repo.key และ $HOME/nginx-repo.crt

###ติดตั้ง ansible และส่วนอื่น ๆ ที่จำเป็น
```shell
$ sudo apt -y update
$ sudo apt install -y ansible
$ ansible-galaxy collection install nginxinc.nginx_core
$ git clone https://github.com/nginxinc/ansible-collection-nginx.git
```
###แก้ไข deploy-nginx-plus.yml 
```shell
$ cd ansible-collection-nginx/playbooks/
$ vi deploy-nginx-plus.yml
---
- hosts: all
  become: yes
  become_user: root
  become_method: sudo
  connection: local
  collections:
    - nginxinc.nginx_core
  roles:
    - role: nginx
      vars:
        nginx_type: plus
        nginx_license:
          certificate: /home/drs/nginx-repo.crt
          key: /home/drs/nginx-repo.key
```
###เรียกใช้งาน ansible playbook เพื่อติดตั้ง NGINX Plus
```shell
$ ansible-playbook -i "localhost, " deploy-nginx-plus.yml

PLAY [all] *****************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************
ok: [localhost]

TASK [nginx : Check whether you are using a supported NGINX distribution] **************************************
ok: [localhost] => {
    "changed": false,
    "msg": "Your OS, Ubuntu is supported by NGINX Plus"
}
[...]
TASK [nginx : Configure logrotate for NGINX] *******************************************************************
skipping: [localhost]

TASK [nginx : Install NGINX Amplify] ***************************************************************************
skipping: [localhost]

PLAY RECAP *****************************************************************************************************
localhost                  : ok=23   changed=11   unreachable=0    failed=0    skipped=22   rescued=0    ignored=0
```
###ทดสอบการทำงานของ NGINX Plus
```shell
$ curl http://localhost
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
```
#####มูลค่าความสุข
All about HTTPS (part-3)
Tags: tutorial, beginners, todayilearned, https
Published: 2021-07-10 09:44:27

##The handshake

In the [prev post](https://dev.to/akashkumarsikarwar/all-about-https-part-2-2hnd), we talked about two types of encryption keys algorithms. In this post, let me walk you through the process of the handshake.

When you started reading this article, your browser displayed a green lock in the address bar. How did that happen?

Your browser communicated with dev.to server, where this post is hosted, and they both established a secure connection to transmit messages. 
But first, they needed to agree on how to communicate securely. If the negotiation is not successful, your browser lets you know by showing an error or warning. If an agreement is reached, your browser is happy to display a green padlock on the address bar. This process, the negotiation between a browser and a server, is called 'the handshake'. It happens very fast without any delay. Let me help you understand it step by step.

**Step 1:** Client Hello. Your browser sends a list of SSL/TLS versions and encryption algorithms that it can work with to dev.to server. A fancy word for the encryption algorithm list is 'cipher suite'. And then your browser waits for an answer from dev.to server.

**Step 2:** Server Hello. Server chooses the best SSL/TLS version and encryption algorithm among the ones browser sent it, and based on its preferences. Server replies with its certificate, which includes its public key, so that it can verify who it is.

**Step 3:** Client Key Exchange. Your browser checks server's certificate to make sure its legit. It generates a 'pre-master key' so they can both user it later when they generate a unique key. Browser encrypts that pre-master key with server's public key and sends it back to the server.

**Step 4:** Change Cipher spec. Server uses its private key to decrypt the pre-master key. So far all the communication between them has been in open. They have not secured any messages. They used asymmetric keys (public and private keys) to encrypt the pre-master key so nobody could spy on it. Now they both generate the same 'shared secret' that they are going to use as a symmetric key. Browser sends a test an encrypted test message to which server responds saying everything is OK.

**Step 5:** Everything is now secured. Now all data going back and forth between your browser and dev.to server is now secured for the rest of the session. Passwords, credit card details(if any), everything.

Simple right? Here is a diagram to help you understand this handshake better.
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8g8uwzk8htjncbo13tuj.png)

In the [next post](https://dev.to/akashkumarsikarwar/all-about-https-part-4-22ga), we will try to understand the differences between the terms HTTPS, SSL and TLS we talked about earlier.