teleren/devto huggingface dataset:
Emulating TypeScript union types with ReasonML, part 2
Tags: reason, ocaml, bucklescript
Published: 2020-06-06 00:04:23

---
title: Emulating TypeScript union types with ReasonML, part 2
published: true
description: 
tags: reason,ocaml,bucklescript
//cover_image: https://direct_url_to_image.jpg
---
IN a [previous post](/yawaramin/emulating-typescript-union-types-with-reasonml-3ea0), I showed a technique in Reason for automatically creating a 'union type' like the ones that TypeScript has. In essence, this TypeScript union type:

```typescript
type Labels = 'Down Arrow' | 'Left Arrow'
```

Can be modelled with a Reason function:

```ocaml
let labels = fun
  | `DownArrow => "Down Arrow"
  | `LeftArrow => "Left Arrow";
```

...and Reason infers that the function has type:

```ocaml
let labels: [< `DownArrow | `LeftArrow] => string;
```

Of course, this is not exactly the same–it's more of a way to _convert_ a limited set of polymorphic variant values into a limited set of strings. We can think of it as a 'poor man's union type'.

## Slightly richer

But Reason's abilities don't stop there. The BuckleScript compiler actually has a feature, called [`@bs.deriving jsConverter`](https://bucklescript.github.io/docs/en/generate-converters-accessors#convert-between-js-string-enum-and-bs-polymorphic-variant), that can do a two-way conversion between a polymorphic variant type and string values. Here's the previous example, converted to use it:

```ocaml
[@bs.deriving jsConverter]
type label = [
| [@bs.as "Down Arrow"] `DownArrow
| [@bs.as "Left Arrow"] `LeftArrow
];
```

If you look at the JavaScript output for this, you'll notice the following functions: `labelToJs`, `labelFromJs`. These convert the polymorphic variant values to strings and vice-versa. The cool part is that the `labelToJs` conversion is exactly what we hand-wrote above, so if you pass in an unsupported value you get a type error:

```
/* let test = labelToJs(`DownArray);

We've found a bug for you!
OCaml preview 5:22-32

This has type:
  [> `DownArray ]
But somewhere wanted:
  label
The second variant type does not allow tag(s) `DownArray */
```

We can think of this as not exactly a union type, but a type that is 'isomorphic' to a union type. Pretending for a second that Reason had real union types:

```
let labelToJs: [`DownArrow | `LeftArrow] => "Down Arrow" | "Left Arrow"
```

Reason does a lot of things by spreading the workload (so to speak) between types and functions. Data types describe the data and function types describe the relationships between them. And even though Reason doesn't have real union types, we can still take advantage of guarantees from features like `@bs.deriving jsConverter` to come close.
Why I decided to publish on a blog?
Tags: writing, sharing, growing
Published: 2020-06-06 00:00:00

---
title: Why I decided to publish on a blog?
description: Just if you care.
cover_image: https://raw.githubusercontent.com/abedurftig/personal-blog/master/static/undraw_launching_125y.png
date: '2020-06-06'
published: true
canonical_url: https://abedurftig.github.io/2020-06-06-why-i-have-a-blog
tags:
  - Writing
  - Sharing
  - Growing
devToId: 355215
devToUrl: https://dev.to/abedurftig/why-i-decided-to-publish-on-a-blog-1a6d
---
There are already so many blogs out there, most of them have probably more and better content than mine. Yet I have decided to start running my own blog. So why?

Over the years as a software professional working on different projects and with different people, I naturally started to collect some experiences. I began to formulate opinions in my head, but I rarely formally express them. So, I have decided that I want to start writing down some of my opinions, really more as a reference for myself. I want to practise to summarise and verbalize my thougths. It has been quite some time since I wrote my thesis, so I want to get back in shape. Why would I not do this publically?

I hope that a good part of my writing will be about software design and implementation. Small examples from the field, but also about little experiments I am doing on the side. Possibly there will be some posts about teamwork and collaboration. Some of it may well be worth sharing. So putting my words in the internet seems like one way of doing it.

Further, running this blog gives me a chance to try out new things and technologies. For example Vue.js with Nuxt.js and the content module, which I used to create this blog. Let's see if I learn something about SEO. Will this blog show up on Google? 🤔

Last, but not least I would like to get some feedback and maybe engage in some discussions related to a post that I am publishing. For that aspect I am planing to also publish my posts on platforms like for example [DEV](https://dev.to/). This gives me some additional outreach and it has a nice comment/discussion feature.

So, let's see.
Install Composer on Mac / Linux /Unix machine
Tags: php, laravel, composer, beginners
Published: 2020-06-05 23:52:18

To install composer using terminal your computer,
(Please note that installation requires that you have php already installed in your system)
 * Open the terminal
 * In your home directory type

`{{ php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php -r "if (hash_file('sha384', 'composer-setup.php') === 'e0012edf3e80b6978849f5eff0d4b4e4c79ff1609dd1e613307e16318854d24ae64f26d17af3ef0bf7cfb710ca74755a') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');" }}`

* This command allows composer to only run in the home directory, to install composer globally type the following command

`mv composer.phar /usr/local/bin/composer`

* After this step, the composer package can be used in any directory within your system.

* Type `composer` in terminal to confirm

* To learn more on how to use composer read official documentation on  https://getcomposer.org/doc/
I bought a MERN stack course, and I want to share it with you. Is that okay?
Tags: mern, javascript, discuss, webdev
Published: 2020-06-05 23:24:22

So, recently i bought a MERN stack course from a local online course website, but i dont learn it yet because i am busy writing posts on my blog <a href="https://www.devaradise.com">devaradise.com</a>.

This course teach me with study case: building a travel web app using MERN stack.

Then, i have a thought that "why dont i learn it and share it on my blog (and here of course) so i can complete 2 tasks at once, learning for myself and writing for blog". Of course, i won't share the course materials and its resources with you. I know its not ethical.

What i want to share is a documentation of my learning, along with some explanation of what i learn, so you can learn it as well. I also want to make my learning project open source on github and create a demo page.

But still, i dont feel right to the course author because its like i create an alternative content for that course in different format.

What do you think guys?
Do you have any opinion about this?
And are you interested if i create the serial posts of my learning documentation?
Deadline Extended for Grant For The Web x DEV Community hackathon
Tags: gftwhackathon, meta, webmonitization, opensource
Published: 2020-06-05 23:23:05

---
title: Deadline Extended for Grant For The Web x DEV Community hackathon
published: true
description: New deadline for project submissions is June 14
tags: gftwhackathon, meta, webmonitization, opensource
---

This week has been challenging for the United States — and for Black and Brown communities all over the world. 

As such, we've decided to extend the submission deadline for the Grant For The Web x DEV Community hackathon. There is a lot to process right now, and rightfully so. Healing and action for marginalized communities should be prioritized over code.

**The NEW Deadline for the Grant For The Web x DEV Community hackathon is June 14th. We will announce winners on June 18th.**
---

### For a review on the details of the Grant For The Web x DEV Community hackathon, please visit this post: 

{% link https://dev.to/devteam/announcing-the-grant-for-the-web-hackathon-on-dev-3kd1 %}


When you're ready to return to your projects and submissions, here again is the help thread:
{% link https://dev.to/thepracticaldev/grant-for-the-web-hackathon-help-thread-19pb %}

---
We're wishing everyone a safe, healthy, and healing weekend.
89/100 100daysofcode  Flutter
Tags: 100daysofcode
Published: 2020-06-05 23:13:47

day 89/100 of #100daysofcode #Flutter
Learning Flutter , courses Udemy from
@maxedapps

Today implements about future builder,key and some ui,
https://github.com/triyono777/100-days-of-code/blob/master/log.md
Web Monetization for games
Tags: gftwhackathon, monetization, games, ideas
Published: 2020-06-05 22:42:57

## What I built

A proposal to expand the Web Monetization `<meta>` tag for games.
This could then be used as a basis for a JS implementation.
It _could_ eventually lead to a new specification proposal if the usage scenario is common enough amongst other content as well.

### Submission Category: Creative Catalyst

This projects use existing Web Monetization technology (the `<meta>` tag) to explore the creation, distribution, and discoverability of online games.

## Demo

Since this is an idea/proposal, there is no working demonstration.


## Link to Code

The idea is basically to do this:

```
<meta name="monetization" content="$example.com/alice" >
<meta name="monetization-mode" content="allow-payback;asynchronous" />
```

To allow turn-based (asynchronous) rather than time-based (synchronous) payments.

This is explained in more detail here:

{% medium https://medium.com/@potherca/web-monetization-for-games-7ad49c853827 %}

{% medium https://medium.com/@potherca/extending-the-meta-tag-for-game-monetization-9bbfeb38acc8?postPublishedType=initial %}

## How I built it 

First I brainstormed my initial idea and tried to capture it in words.  

Next I searched online to see if this (or a similar idea) had already been proposed or implemented elsewhere. 

To make sure I understood the technical and practical limitations, I read the [Web Monetization Specifications][1], [Interledger Protocol V4 Specifications][3], [W3C Interledger Payment Method specifications][4], and [Web Monetization Documentation][2].

Then I continued working in my writing. During writing I referenced https://schema.org/.

When I was done (or actually, when time ran out) I posted my writing here.

## Additional Resources/Info 

I plan to expand my submission into a full-on application for the Grant for the Web CFP before June 12. 

Due to a lack of time during the hackathon, I could not create an implemenation, only documentm my idea.

If my proposal gets accepted, I will be able to create the JS implementstion that will bring this idea into reality.

[1]: https://webmonetization.org/specification.html
[2]: https://webmonetization.org/docs/
[3]: https://interledger.org/rfcs/0027-interledger-protocol-4/
[4]: https://w3c.github.io/webpayments/proposals/interledger/
APIs
Tags: beginners, api, javascript
Published: 2020-06-05 22:36:48

An API is an acronym for Application Programming Interface which means communication between multiple software. Don't be scared, Let me break it down.

Basically, An API enables you to have access to a website's/software's data (like spotify, twitter and so on). 
How, you may ask? It gives you a nice user-friendly way to read and write data to and from another website's database.

Where to get a websites API from?
APIs are usually located at the footer of a webpage and usually anchored as **developer**. Go to [Last.fm](https://www.last.fm) and navigate to the bottom and thats a real world api. 

APIs ain't really scary, they are just here to make our lives better, and to enable us use rich datas without having to create and write them ourselves.

#### Resources
* [The coding train](https://www.youtube.com/watch?v=tc8DU14qX6I)
Web Monetization made easy for Gatsby
Tags: gatsby, react, webmonetization, gftwhackathon
Published: 2020-06-05 22:31:51

## What I built

I'm late to the party as I got to know about #gftwhackathon yesterday. Without further ado, I read the docs of Web Monetization API and thought of creating a package for react. But after a bit of digging I found [react-monetize](https://github.com/guidovizoso/react-monetize) and some other packages which were doing the same thing, so I created Gatsby plugin for `react-monetize`.

### Submission Category: 

- Foundational Technology: Gatsby plugin for Web Monetization API

## Link to Code

{% github https://github.com/mrmuhammadali/gatsby-plugin-monetization %}
Instructions for setting up example code is given in the [docs](https://github.com/mrmuhammadali/gatsby-plugin-monetization#examples).


## How I built it 
Technology Stack:
- React
- Babel
- Gatsby

I learned about Web Monetization API and how it works along the way and it was my first time of creating a plugin for Gatsby.


## Additional Resources/Info 

I've some ideas to create components necessary for Web Monetization API to integrate in React.

I've also created a [PR](https://github.com/WICG/webmonetization/pull/80) in official docs of web monetization API to publish this plugin there.
Ansible Journey: Adding /etc/fstab Entries
Tags: ansible, mounts, s3fs
Published: 2020-06-11 03:41:42

---
title: Ansible Journey: Adding /etc/fstab Entries
published: true
date: 2020-06-05 22:27:00 UTC
tags: Ansible,mounts,s3fs
canonical_url: https://thjones2.blogspot.com/2020/06/ansible-journey-adding-etcfstab-entries.html
---

As noted in [yesterday's post](https://dev.to/ferricoxide/til-you-gotta-be-explicit-2na2-temp-slug-6918287), I'm working on a new customer-project. One of the automation-tools this customer uses is [Ansible](https://docs.ansible.com/). This is a new-to-me automation-technology. Previously — and aside from just writing bare BASH and Python code — I've used frameworks like Puppet, SaltStack and a couple others. So, picking up a new automation-technology — especially one that uses a DSL not terribly unlike one I was already familiar with, hasn't been super much of a stretch.  
  
After sorting out yesterday's problem and how I wanted my <tt>/etc/fstab</tt> to look, I set about implementing it via Ansible. Ultimately, I ended up settling on a [list-of-maps](https://docs.ansible.com/ansible/latest/plugins/lookup/subelements.html) variable to drive a [lineinfile](https://docs.ansible.com/ansible/latest/modules/lineinfile_module.html) role-task. I chose a list-of-maps variable mostly because the YAML that Ansible relies on doesn't really do tuples. My var ended up looking like:

> ```
> s3fs_fstab_nest:
>   - mountpoint: /provisioning/repo
>     bucket: s3fs-build-bukkit
>     folder: RPMs
>   - mountpoint: /provisioning/installers
>     bucket: s3fs-build-bukkit
>     folder: EXEs
>   - mountpoint: /Data/personal
>     bucket: s3fs-users-bukkit
>     folder: build
> ```

  
And my play ended up looking like:  
  

> ```
> ---
> - name: "Add mount to /etc/fstab"
>   lineinfile:
>     path: '/etc/fstab'
>     line: "s3fs#{{ item.bucket }}:/{{ item.folder }}\t{{ item.mountpoint }}fuse\t_netdev,allow_other,umask=0000,nonempty 0 0"
>   loop: "{{ s3fs\_fstab\_nest }}"
> ...
> 
> ```

  
Was actually a lot simpler than I was expecting it to be.
Futter + Gitlab + unit test + CI
Tags: flutter, ci, test, gitlab
Published: 2020-06-05 21:48:53

## Como lograr Integración continua usando Gitlab y desarrollando una app con Flutter?


### En el proyecto que estoy trabajando actualmente me pidieron que comience a realizar pruebas unitarias para la app y que se ejecuten en cada merge request antes de fusionar los cambios a la rama master.


> Hasta el momento nunca había realizado test en Flutter, por lo que me puse a leer la documentacion ver videos en youtube y leer muchos post.


### Los pasos que seguí para lograr lo que me pidieron fueron los siguientes:

- Dentro de la carpeta test que esta en la raíz del proyecto cree una nueva carpeta solo para las pruebas unitarias con el nombre **unit_test**.

- Agregue **test:** a las dependencias de desarrollo (dev_dependencies) en el archivo **pubspec.yml**  
```json
dev_dependencies:
	test:
```
- Cree un test básico de ejemplo para empezar a probar
```
import  'package:test/test.dart';

void  main(){
	group('example two unit test', (){
		test('#sum' , (){
			expect(1+1, 2);
		});
		test('#sum' , (){
			expect(1+1, 2);
		});
	});
});
```
- Cree un archivo de configuración  en la carpeta raíz del proyecto llamado **.gitlab-ci.yml** para implementar CI en gitlab con el siguiente contenido:
```
image: cirrusci/flutter:stable

before_script:
  - flutter doctor
  
stages:
  - test
  
unit_test:
  stage: test
  
script:
  - flutter test
```

#### Listo con eso ahora ya puedes  hacer un push en tu proyecto y veras algo parecido a esto
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/wy6efcsgewufzouwbpjf.png)

Ahora en los próximos push que hagas van a correr esos dos test del ejemplo.

Espero que sean de ayuda estas lineas.

Este es mi primer post y espero empezar a compartir cosas sobre flutter con las que me vaya topando y resolviendo que considere que puedan llegar a ser útiles a otras personas a la hora de enfrentarse a los mismos problemas
Gerando um totalizador acumulado por linha sem usar cursor. 
Tags: sql
Published: 2020-06-05 21:42:02

Olá pessoas!!!
Acredito que assim como eu vocês já se depararam com situações nas quais precisavam gerar um total que vai se acumulando linha a linha, não é mesmo? 
E quando geramos consultas pra relatórios acabamos usando o famoso **cursor** para gerar esses totalizadores, o que acaba não sendo tão performático assim. 
Dessa forma resolvi mostrar aqui como podemos gerar esse tipo de totalizador usando *Window Function*, no T-SQL. 

Pra montar esse exemplo eu usei: 
1. SQL SERVER 2016 Developer 
2. SSMS
3. Banco de dados de estudo *WorldWideImporters*

Antes de metermos a mão na massa, vocês tão ligados do que são as *Window Function*? 
*Window Function* são funções nas quais podemos utilizar para realizar cálculos ou agregações em um conjunto de linhas que possuem alguma relação, nesse caso não precisamos utilizar o GROUP BY. E torna muito útil pois na mesma consulta podemos ter um resultado analítico e sintético. A sua utilização é bem simples. 

Nesse [Link](https://docs.microsoft.com/en-us/sql/t-sql/queries/select-over-clause-transact-sql?view=sql-server-ver15) da documentação da Microsoft tem um detalhamento melhor sobre Window Function. Pois não é o caso aqui entrar em muito detalhe apenas vamos abordar um caso específico, lá você pode abrir a sua mente e viajar em possíveis soluções... 

###Hora de botar a mão na massa!!!! 
No cenário em questão vamos imaginar que foi feito uma solicitação para você gerar uma consulta que mostre o ID do pedido, ID do Cliente, Data do Pedido, Descrição do pedido, Quantidade, Valor Unitário, Total Geral do pedido e um Total Acumulativo por pedido. 
Abaixo nos tempos os Script para atender essa solicitação. 

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

Na linha na qual geramos o total geral: 
SUM(OL.UnitPrice * Quantity) OVER(PARTITION BY OL.OrderId) AS Total

Usamos a Window Function OVER() gerando uma partição com o PARTITION BY e com isso podemos somar os registros referente a um determinado ID sem precisar usar o GROUP BY. 

Na linha na qual geramos o total corrente: 
SUM(OL.UnitPrice * Quantity) OVER(PARTITION BY OL.OrderID ORDER BY OL.OrderID ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS Total_Corrente 

De forma semelhante ao total geral também criamos uma partição com o PARTITION BY para ele gerar o total corrente por ID do pedido, porém acrescentamos um ORDER BY que é obrigatório quando utilizamos **UNBOUNDED PRECEDING**. 

**UNBOUNDED PRECEDING** indica que a Window Function irá começar da primeira linha da partição. 

**CURRENTE ROW** indica que é até a linha corrente. 

Então **ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW**, seria as lihas entre o início da partição e a linha corrente. Com isso podemos ir gerando o total por linha da partição. 

Abaixo o resultado da nossa consulta. 

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

Então é isso pessoal, espero que isso seja útil pra vocês. :D
Recursion and Space Complexity
Tags: spacecomplexity, recursion, algorithms
Published: 2020-06-05 21:40:41

When I was first reading up on recursive solutions to algorithms, I kept hearing about space complexity and the call stack, and at first had no idea what was up. It's turns out, it's actually pretty simple! I'm hoping this post can condense into one spot what was a disparate learning experience for me.

Let's define some things first.

What is recursion? Honestly that one is worth a blog post (or a few) in itself, so if you're not already familiar with how recursion works, I recommend you read [this excellent rundown](https://www.freecodecamp.org/news/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9/) or find something similar to help you understand, as I'm not going to be going into it fully here. I'll wait.

You back? Okay cool. Next, what is Space Complexity?

> Space complexity in algorithm development is a metric for how much storage space the algorithm needs in relation to its inputs. -[Technopedia](https://www.techopedia.com/definition/22229/space-complexity)

So if my solution to an algorithm involves creating two hash-tables, my space complexity is going to be a lot higher than if it only involves creating a single primitive variable.

Finally, what is the Call Stack?

>In computer science, a call stack is a stack data structure that stores information about the active subroutines of a computer program. - [Wikipedia](https://en.wikipedia.org/wiki/Call_stack)

Translation, it's how many tasks the system is juggling at once.

With recursion, every time you call the function recursively you add one more function to the call stack. Until you hit the 'bottom' and start traveling back up or out, you're adding one each time. Now suppose that your function requires establishing a variable. That variable is being established anew every time you call the function. 

It goes like this. You have a function that requires that 2 rocks be balanced in your hands. Every time you call the function, you add two more rocks to your pile. You can't start putting rocks down until the function they are for finishes. Because of the nested nature of recursion, you're doing a lot of things at once, and so that pile is going to grow bigger and bigger and may get pretty unwieldy and heavy.

That pile of rocks is your space complexity! The more levels of recursion you have, the higher it will get. You're going to get better performance out of your machine the fewer functions you've got going.

Recursion is really neat, and can lead to some beautifully simple code, but it definitely has its drawbacks.