teleren/devto huggingface dataset:
Why AsyncLocalStorage instead of LocalStorage?
Tags: javascript, typescript, webdev, beginners
Published: 2020-05-31 03:29:16

### Cons of LocalStorage

<a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage" target="_blank">LocalStorage</a> is synchronous, each local storage operation you run will be one-at-a-time. For complex applications this is a big no-no as it'll slow down your app's runtime.

### Pros of AsyncLocalStorage

<a href="https://github.com/createnextapp/async-local-storage" target="_blank">AsyncLocalStorage</a> is asynchronous, each local async storage operation you run will be multi-at-a-time. It'll speed up your app's runtime.

The AsyncLocalStorage JavaScript code is a facade that provides <a href="https://github.com/createnextapp/async-local-storage/blob/master/API.md" target="_blank">a clear JavaScript API</a>, real Error objects, and non-multi functions. Each method in the API returns a Promise object.

### Installation

async-local-storage is available on npm. It can be installed with the following command:

```
npm install --save @createnextapp/async-local-storage
```

async-local-storage is available on yarn as well. It can be installed with the following command:

```
yarn add @createnextapp/async-local-storage
```

### Usage

#### Import

```js
import AsyncLocalStorage from '@createnextapp/async-local-storage'
```

#### Store data

```js
storeData = async () => {
  try {
    await AsyncLocalStorage.setItem('@key', 'value')
  } catch(e) {
    // error
  }
}
```

#### Read data

```js
readData = async () => {
  let data

  try {
    data = await AsyncLocalStorage.getItem('@key')
  } catch(e) {
    // error
  }

  console.log(data)

  /*
    output: 
    value
  */
}
```

To learn more how to use async-local-storage:

* <a href="https://github.com/createnextapp/async-local-storage/blob/master/API.md" target="_blank">API Documentation</a>
What did you learn too early in life?
Tags: lifelessons, motivation
Published: 2020-07-20 06:52:56

---
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/ar8sbgcsfvzkm1y76hsg.jpg
title: What did you learn too early in life?
published: true
date: 2020-05-31 03:16:30 UTC
tags: lifelessons,motivation
canonical_url: https://rajeshroyal.com/what-did-you-learn-too-early-in-life/
---

> To talk smartly and don’t open all your 52 cards in front of everyone.

> Life is like an ice cream enjoy it before it melts.

> Don’t express your opinion in front of a person who is arrogant stupid and never listens other.

> Stick firmly to one thing at a time, don’t mix things as to create a mess.

> Ignore toxic people and try to make friends who have similar goals like you.

> Everyone suffers in life, so when it’s your turn don’t panic.

> Work Hard don’t waste time. Time is precious.

> Help the needy not the greedy.

> Never let the inner child die inside you.

> Be social but don’t waste time.

> Forget the past and believe in present and future.

> Believe in yourself and be a tough person.

> Eat healthy food. Later you will suffer from different problems if the eating habit is not good.

> Travel at least to a new place every year.

> Study whatever you like to study.

> Be happy, work and believe, Your moon will shine bright.

![programming books stack, multiple books programming](https://rajeshroyal.com/wp-content/uploads/2020/05/programming-books-stack-multiple-books-programming.jpg)<figcaption id="caption-attachment-1219">programming books stack, multiple books programming</figcaption>

Footnotes: [Quora](https://www.quora.com/What-did-you-learn-too-late-in-life), Image Sources: [Google Images](https://www.google.co.in/).

The post [What did you learn too early in life?](https://rajeshroyal.com/what-did-you-learn-too-early-in-life/) appeared first on [Rajesh Royal](https://rajeshroyal.com).
Functional Programming in PHP: Part 2
Tags: functional, php
Published: 2020-05-31 03:10:03

[First part](https://dev.to/asiros/functional-programming-in-php-knc)

Today we will cover: First Class and High Order Functions.

So, now we know what is a pure function, what else do we need to know?
In PHP we have a First Class Function, what is it and how to use it?

First Class Function means, we can use our function like any other types. 
For example, we can pass it around, we can assign it, destroy, etc.

Let's see an examples:

```php
// Assign
$validate = fn(string $x): bool => strlen($x) > 14;

// Destroy
unset($validate);

// Pass it
$id = fn($x) => $x;

function map(callable $fn, array $arr): Generator {
    foreach($arr as $item) {
        yield $fn($item);
    }
}

$fruits = ['apple', 'orange'];
$unchangedFruits = map($id, $fruits); // ['apple', 'orange'];
$capitalizedFruits = map('ucfirst', $fruits); // ['Apple', 'Orange'];
```

So, now we know, that we can use our functions like everything else, that's great!
And now get to know what is High Order Functions, that's a function which accepts a function and/or returns a functions! So, that's basically our map function above :)

So, let's see how does it look, when function returns a function.

```php
// Change our function a little
function map(callable $fn): callable {
    return function(array $arr) use($fn): Generator {
        foreach($arr as $item) {
            yield $fn($item);
        }
    }     
}

$doube = map(fn($x) => x * 2);
$doube([1, 2, 3]); // 2, 4, 6
```

What benefits we gained? 
Well, now we have a function which work with arrays and can easily return  to us our function which will work with any array and double it, so we can easily reuse our High Order map and First Class double function :)
Complete React Ecosystem learning
Tags: javascript, react
Published: 2020-05-31 03:09:56

I have started learning react a week ago and found learning react is a bit difficult because it is a library not a framework like Angular.

I have collated a list of useful sites to kick off:

[1.React Introduction - Video](https://www.youtube.com/playlist?list=PLC3y8-rFHvwgg3vaYJgHGnModB54rxOk3)

[2.React Redux- Video](https://www.youtube.com/playlist?list=PLC3y8-rFHvwheJHvseC3I0HuYI2f46oAK)

[3.React Complete- Video](https://www.youtube.com/playlist?list=PL4cUxeGkcC9ij8CfkAY2RAGb-tmkNwQHG)

[4.React Context and Hooks- Video](https://www.youtube.com/playlist?list=PL4cUxeGkcC9hNokByJilPg5g9m2APUePI)

[5.React Official](https://reactjs.org/)

[6.React-Redux Official](https://react-redux.js.org/)

[7.Jest for React](https://jestjs.io/docs/en/tutorial-react)

[8.React Material-UI](https://material-ui.com/)

[9.React - Create APP](https://create-react-app.dev/)

[10.Formik](https://jaredpalmer.com/formik)

[11.React Component Profiling](https://calibreapp.com/blog/react-performance-profiling-optimization)

[12.Enzyme](https://enzymejs.github.io/enzyme/)

[13.React Router](https://reacttraining.com/react-router/core/guides/quick-start)

[14.React Sever Side Rendering](https://www.udemy.com/course/server-side-rendering-with-react-and-redux/)



I hope it will be useful to all the react learners from beginner to advanced level.
Monitor NGINX
Tags: nginx
Published: 2020-05-31 02:53:54


Nginx status page can give us realtime information about the server's current status, such as number of connections and requests.

# Configure Nginx

Run this command to check if your Nginx server support status page:

```
nginx -V 2>&1 | grep -o with-http_stub_status_module
```

Edit Nginx config file and add the following inside server{...} block:

```
 location /nginx_status {
          stub_status on;
          access_log   off;
          allow 1.1.1.1;
          deny all;
        }
```

Then reload Nginx config:
```
nginx -s reload
```
After reloading config, visit http://yourdomain.com/nginx_status and the output will be something like:

```
Active connections: 81 
server accepts handled requests
 12132 12132 15001 
Reading: 0 Writing: 3 Waiting: 5
```

###Notes:
* Active connections – Number of all open connections. This doesn’t mean number of users. A single user, for a single page view can open many concurrent connections to your server.
    
* Server accepts handled requests – This shows three values.
        1. First is total accepted connections.
        2. Second is total handled connections. Usually first 2 values are same.
        3. Third value is number of accepted and handles requests. This is usually greater than second value.
        4. Dividing third-value by second-one will give you number of requests per connection handled by Nginx. In above example, 15001/12132, 1.24 requests per connections.
     
* Reading – Nginx reads request header
    
* Writing – Nginx reads request body, processes request, or writes response to a client
    
* Waiting – keep-alive connections, actually it is active – (reading + writing).This value depends on keepalive-timeout. Do not confuse non-zero waiting value for poor performance. It can be ignored. Although, you can force zero waiting by setting keepalive_timeout 0;

# Configure [SysUpTime](http://ireasoning.com/network-monitoring-software.php)

1. Add a web site monitor: 
![add monitor](https://dev-to-uploads.s3.amazonaws.com/i/qtr7ozqotmxwai5i6y8u.png)

2. Configure it to use simple content match, and choose the third token of first line of the http response, which is the value of active connections. 
![configure](https://dev-to-uploads.s3.amazonaws.com/i/lmru2dyesc5hoguvjpms.png)

3. The chart of the monitor will be something like:
![Nginx Connections](https://dev-to-uploads.s3.amazonaws.com/i/pfg3794ps8lqly6poepv.png)
cryptotako.com
Tags: crypto, eth, twitter, github
Published: 2020-05-31 01:49:07

---
title: cryptotako.com
published: true
description: 
tags: crypto, ETH, twitter, github
---

I developed a service called [cryptotako.com](https://cryptotako.com) in a private project.

You can transfer ETH through the system without asking for the other party's Ethereum address.

The main features of the service are as follows

* Log in with your social network accounts such as Twitter, GitHub, etc.
* Log in from your MetaMask, Dapper or other wallet
* Select Twitter, GitHub or ETH Address to send ETH
* Notifications on Twitter, GitHub
* Transaction history
* Twitter and GitHub account integration to generate addresses
* Private Key Export
* Change email, username
* Conversion in USD, JPY, the Fiat.

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

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

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

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

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/tat2dhh817pscytmq1xt.png)
A Timeless Directory Layout for  Projects
Tags: linux, discuss, beginners, git
Published: 2020-05-31 01:41:04

Directory layouts are like log cabins that start from a basic shed, gradually adding a room at a time.When you start out on UNIX, everything gets thrown inyour home directory. Over time you start to develop a structure for your sources, binaries,projects, data files (like CSV, images, tar files), config, etc

My layout is called **TDL** -- because it allows me to juggle open sourceprojects, partnerships and jobs in a consistent structure across machines and time.

```
~/
│── .cfg            # bare git repo with my dotfiles
│── local           # e.g. make install --prefix=~/local
│   - lib, bin, man  
│── .trash          # files to delete
│       # VARIOUS DIRECTORIES WITH REPOS
│── src             # clone public open source repos, e.g. for contribution, research or debugging
│── stellar         # personal repositories
│   - archive       # hold tgz of repos to save space and indexing
│   - repo1
│   - repo2
│── apple           # contains repos for a previous company
│── microsoft.      # repos from another company , consulting project, charity effort

```

## `.cfg`

Store your dotfiles using the [git bare repo technique](https://www.atlassian.com/git/tutorials/dotfiles). this way your config travels with you. If you have host-specific config, either test for the hostname e.g. in your .bashrc, or `git checkout -b $(hostname)`

## `local`

e.g. `make --prefix=~/local` -- install binaries, libs, man pages into your home directory. Add `$HOME/local/bin` to your path with `export PATH=$PATH:$HOME/local/bin`The contents are machine specific

## Storing Repos

Within your home dir, choose "business names" , e.g. for my personal workit's `stellar`, open source is `src` and then a directory each for businesseslike `apple` , `microsoft` etc

## Archiving Sources

Sources get huge, so archive them with `tar -czf archive/repo1.tgz repo1 && rm -rf repo1`

## Syncing Files Across Hosts

most sources will be synced via your git repo, but for large files (e.g. a 5gb csv), generally you'll rsync

Add the alias to your `.ssh/config` so you can quickly send files among machines. Naturally commit that into your `.cfg` repo

e.g.

```
cat ~/.ssh/config
Host cloud9-env1
        User ec2-user
        IdentityFile ~/.ssh/id_rsa
        Hostname cloud9-env1.tonymet.com

```

Then you can easily sync with `rsync myfile cloud9-env1:$(pwd)/`

## Summary

Keeping things consistent over time, across projects and machines is key.  

What's your layout look like?
Day 1: Yeah, Just Change It up a a Bit So It Doesn’t Look Obvious
Tags: webdev, codenewbie, css, html
Published: 2020-05-31 01:32:17

In my younger and more vulnerable years, I didn't *really* want to learn to code. I just wanted results. 

Through sheer repetition, I learned enough to bold and italicize text, sure. I knew how to put an image on a webpage, make a link. But the more complicated stuff, puhh-shaaa! I was far more interested in achieving the look I wanted at the time than gaining a new skill to use later. 

Enter coding myspace and tumblr bloggers. My salvation. 

I was an awkward teen who didn't want to tell anyone about her internet hobbies, and these pioneers saved me. These folks had already figured out how to do all the cool stuff on my blogs that I wanted, and all I had to do was just copy their code out of the tiiiiny scroll boxes they put it in and paste it into the editor on my websites. 

From there, my work began. 

My formative coding education wasn't in learning what tags or attributes meant and how to apply them, it was a hilarious mishmash of trial and error as I learned to reverse engineer code someone had written for a slightly different purpose to suit my needs. Sort of like the "Can I copy your homework?" meme. 

<img src="https://dev-to-uploads.s3.amazonaws.com/i/ydzkn2e7ijf33siwodsr.png" width="300px">

That's why this first day of FreeCodeCamp has been so interesting. Today, I completed all the challenges in the "Basic HTML and HTML5" and "Basic CSS" modules of FreeCodeCamp's Responsive Web Design certification. I remembered a lot  more than I expected to from my teen years, but it was exciting to, for the first time, stare at a blank screen and write code from scratch. 

Now, if you'll permit me make a little list, trying out a bit of HTML I learned today...

<b>That Sweet, Sweet Data:</b>
<ul><li>Bootcamp: FreeCodeCamp</li>
<li>Modules Completed: Basic HTML and HTML5, Basic CSS</li>
<li>Time Spent: 1 hour 55 minutes</li></ul>
The spacing is wonky, but there is a list I made with code I wrote, so I'll call it a win for today, my friends!
ベルマンフォード法 (Bellman-Ford algorithm)
Tags: fellmanford, ベルマンフォード法
Published: 2020-05-31 01:04:11

{% youtube K_T6bDkAUqs %}

## コード

```js
let v = 0, e = 0, r = 0
let path = []

process.stdin.resume();
process.stdin.setEncoding("utf-8");

process.stdin.on("data", function (input) {
  let num = 0
  const lines = input.split("\n")
  for (const line of lines) {
    if (line === "") {
      break
    }
    const m = line.split(" ").map(v => parseInt(v))
    if (num === 0) {
      v = m[0]
      e = m[1]
      r = m[2]
    } else {
      path.push(m)
    }
    num++
  }
});

process.stdin.on("end", function () {
  // console.log(v, e, r)
  // console.log(path)
  bellmanFord(v, r, path)
});

/**
 * @param {number} v 
 * @param {number} r 
 * @param {number[][]} path 
 */
function bellmanFord(v, r, path) {
  const inf = Number.MAX_SAFE_INTEGER
  const dist = Array(v).fill(inf)
  dist[r] = 0
  for (let i = 0; i < v; i++) {
    let change = false
    for (const [s, t, d] of path) {
      if (dist[s] === inf) {
        continue
      }
      if (dist[s] + d < dist[t]) {
        if (i + 1 === v) {
          console.log('NEGATIVE CYCLE')
          return
        }
        dist[t] = dist[s] + d
        change = true
      } else {
        continue
      }
    }
    if (!change) {
      break
    }
  }
  for (const d of dist) {
    console.log(d === inf ? 'INF' : d)
  }
}
```

## 問題

- https://onlinejudge.u-aizu.ac.jp/courses/library/5/GRL/all/GRL_1_B
Utilizando Azure Functions (PowerShell Core) KafkaTrigger
Tags: azure, powershel, kafka, ptbr
Published: 2020-05-31 00:43:27

E ae, pessoal, beleza? Falei recentemente na live do dia 25/05 de como utilizar a trigger Kafka do Azure Functions com o PowerShell Core(na data deste artigo a nova Trigger está em preview),é uma implementação bem simples em questão de código dentro da function, toda a implementação core para consumir a mensagem é implementada por debaixo dos panos. Utilizando o PowerShell recebemos um objeto KafkaEvent e você pode trabalhar com os dados da mensagem. Anúncio do Preview Kafka trigger [blog post](https://techcommunity.microsoft.com/t5/azure-functions/announcing-preview-of-the-azure-functions-kafka-extension/ba-p/1342348)

### Requisitos 
Azure functions core tools.
Conta no Azure.
Conta no Confluente Cloud. 

Neste fork inclui a implementação com os exemplos para PowerShell. 
{% github https://github.com/EwertonJordao/azure-functions-kafka-extension/ %}

__Live dia 25/05.__
{% youtube D_bofQRtpgE %}
Hola Mundo!
Published: 2020-05-31 00:27:26

[![Krupczak Logo](https://matthew.krupczak.org/wp-content/uploads/2019/11/krupczak-1-4.png "Krupczak Logo")](https://matthew.krupczak.org)

-
-
# :~$ whoami
-
-

I’m your host, [Matthew Krupczak](https://matthew.krupczak.org/about-me/)!

[![Matthew Krupczak in front of Computer monitor with Tachikoma, hand soap, and a face mask. Also, he's a total dork](https://matthew.krupczak.org/wp-content/uploads/2020/05/Me2-768x1024.jpg "Matthew Krupczak in front of monitor with Tachikoma")](https://matthew.krupczak.org/about-me/)

-
-
# :~$ whois [foobarbat.dev](https://matthew.krupczak.org)
-
-

I post most of my things on my website: [foobarbat.dev](https://matthew.krupczak.org)

There, you may find:
* [My personal details](https://matthew.krupczak.org/)
* My musings on all number of things tech, with a focus on [hardware/low-level code](https://matthew.krupczak.org/2019/10/19/project-hawking-1-oscillating-avian-game-boy-game-in-c/), [back-end infrastructure](https://matthew.krupczak.org/2019/10/18/cloud-pricing-and-licensing-microsoft/), and [AI](https://matthew.krupczak.org/2019/09/28/the-worst-piece-of-code-ive-ever-writte/).
Cleaning up threads in Haskell
Tags: haskell, concurrency, threads
Published: 2020-05-31 00:00:00

---
title: Cleaning up threads in Haskell
date: 20200531T00:00Z
tags: haskell,concurrency,threads
---

When you press Ctrl+C in ghci or when your code gets reloaded in ghcid, only the main thread is killed (via a [`UserInterrupt`](https://hackage.haskell.org/package/base-4.14.0.0/docs/Control-Exception.html) exception). All other spawned threads continue to run. Here's how to clean them up:

Since the addition of [`listThreads`](https://downloads.haskell.org/ghc/9.6.1-rc1/docs/libraries/base-4.18.0.0/GHC-Conc.html#v:listThreads) in GHC 9.6.1, you can label your threads with [`labelThread`](https://downloads.haskell.org/ghc/9.6.1-rc1/docs/libraries/base-4.18.0.0/GHC-Conc.html#v:labelThread) then list all, filter, and kill them later. This won't work for threads spawned by dependencies since they're probably not labeled. Perhaps a labeling convention could emerge to support this use case, or GHC could apply descriptive labels to all threads to enable user code to disambiguate between user threads and runtime threads (e.g. the IO manager). One hacky idea that doesn't need labels is to sort the list of threads, drop the first 3 (which probably correspond to runtime threads, dangerous assumption though), and kill the rest.

Prior to GHC 9.6.1, it [was not possible to list threads](https://stackoverflow.com/questions/24999636/is-there-a-way-to-kill-all-forked-threads-in-a-ghci-session-without-restarting-i), so it was up to you the programmer to clean up. Here's an idea for cleaning up at least some threads (although it suffers from the same shortcoming as above in that it can't catch threads spawned by dependencies):

- Keep track of all currently-running threads in an `IORef (Set (Async a))`
- When an exception occurs in any thread, hand it to the main thread with `putMVar exceptionVar exception`
- Have the main thread wait for an exception then kill all currently-running threads

Implementation:

```haskell
main = do
  safeAsync $ runApp

  dieOnException

-- NOINLINE ensures that there is only one MVar
{-# NOINLINE errorVar #-}
errorVar = unsafePerformIO $ newEmptyMVar :: MVar SomeException

-- Set of currently-running threads
{-# NOINLINE asyncsRef #-}
asyncsRef = unsafePerformIO $ newIORef Set.empty :: IORef (Set (Async a))

-- Waits for an exception the kills all threads
dieOnException = (readMVar errorVar >>= print) `finally` (do
  mapM_ cancel =<< readIORef asyncsRef
  putStrLn "exiting entire Haskell process"
  exitFailure)

-- A version of `async` that additionally stores itself in the currently-running threads.
-- It also notifies the main thread when there's an exception.
safeAsync a = do
  asyncValue <- async a
  forkIO $ do
    (wait asyncValue `finally` (atomicModifyIORef' asyncsRef (Set.delete asyncValue))) `catches`
      [ Handler $ \(e :: AsyncCancelled) -> return ()
      , Handler $ \(e :: SomeException) -> putMVar errorVar e
      ]
  atomicModifyIORef' asyncsRef (Set.insert asyncValue)
  return asyncValue
```