teleren/devto huggingface dataset:
Resources for functional programming
Tags: beginners, functional
Published: 2019-07-03 14:57:53

---
title: Resources for functional programming
published: true
description:
series: Functional Programming basics
tags: #beginners #functional
---

This is a scattered collection of resources I found useful when learning about functional programing. All resources are digital and free.

I figured that rather than trying to make my own series about purely functional programming, it would be better to recycle excellent material by others that already exists.

### Beginner language
Haskell is without a doubt one of the most relevant languages in purely functional programming. Unfortunately, it's ecosystem is rather hard to go through if it is your first language, and it has some features that are nice, but can be daunting to begin with.
- [Elm](https://elm-lang.org/) a simple language for frontend development. If you're going to use the resources on this page with Elm, note that Elm uses `map` with functors and `andThen` with monads.

### Functional programming patterns
- [*Functional programming design patterns* by Scott Wlaschin](https://www.youtube.com/watch?v=E8I19uA-wGY) will give you a basic understanding of various constructs in FP, such as functors and monads, without going into formalisms.
- [*Orthogonal functional programming* by John A De Goes](https://www.slideshare.net/jdegoes/orthogonal-functional-architecture) sets out a guideline for writing nice libraries.

### Category theory
Category theory is the study of composition. Programming is composing basic functions into complex systems. Category theory helps us understand how to do so *correctly*. This is very much optional when learning functional programming.
- [*Category Theory in Life* by Eugenia Cheng, video](https://www.youtube.com/watch?v=ho7oagHeqNc) An easy to understand, but not technically accurate presentation about category theory. Could give you a reasonable basic feeling for the subject.
- [*Category Theory for Programmers* by Bartosz Milewski, book](https://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/) This seems to be the golden standard everybody is using. The book that taught me most of what I know about category theory.
Tutorial on Deploying a Create-React-App Website to Netlify with HTTPS
Tags: reactnetlify
Published: 2019-07-03 14:51:34

---
title: Tutorial on Deploying a Create-React-App Website to Netlify with HTTPS
published: true
description: Tutorial on Deploying a Create-React-App Website to Netlify with HTTPS
tags: react netlify
---

## TL;DR

Click this:

<!-- Markdown snippet -->
[![Deploy to Netlify](https://www.netlify.com/img/deploy/button.svg?utm_source=blog&utm_medium=devto&utm_campaign=devex)](https://app.netlify.com/start/deploy?repository=https://github.com/netlify-labs/deploy-create-react-app&utm_source=blog&utm_medium=devto&utm_campaign=devex)

and click yes to everything!

## Is that it?

Yeah pretty much. This process creates a fork of <https://github.com/netlify-labs/deploy-create-react-app> (simply a site that has the output of `npx create-react-app deploy-create-react-app`) that you can then clone locally and edit. When you're done and `git push origin master`, your changes will be automatically redeployed.

## What do I get?

- [SSL out of the box](https://www.netlify.com/docs/ssl/?utm_source=blog&utm_medium=devto&utm_campaign=devex)
- Free [Custom Domains](https://www.netlify.com/docs/custom-domains/?utm_source=blog&utm_medium=devto&utm_campaign=devex) (you can buy a domain there or use one bought elsewhere)
- [Continuous Deployment](https://www.netlify.com/docs/continuous-deployment/?utm_source=blog&utm_medium=devto&utm_campaign=devex)
- [Redirects](https://www.netlify.com/docs/redirects/?utm_source=blog&utm_medium=devto&utm_campaign=devex#history-pushstate-and-single-page-apps) useful for Single-Page-Apps!

And [many more features](https://www.netlify.com/docs/welcome/?utm_source=blog&utm_medium=devto&utm_campaign=devex)

## Other ways to deploy

These [Deploy Buttons](https://www.netlify.com/docs/deploy-button/?utm_source=blog&utm_medium=devto&utm_campaign=devex) are merely one way to deploy to Netlify.

- **If you have an existing repo on GitHub/GitLab/BitBucket** you can simply [create a new site from that repo.](https://app.netlify.com/start?utm_source=blog&utm_medium=devto&utm_campaign=devex)
- **If you have a local project** you can use the [Netlify CLI](https://www.netlify.com/docs/cli/?utm_source=blog&utm_medium=devto&utm_campaign=devex) and run `netlify init` to initialize a site.
- **If you don't want to use Netlify's buildbot and continuous deploy** you can run your own build and directly deploy a folder to production with `netlify deploy --prod`

## Why?

This tutorial was made in response to [this Reddit thread](https://www.reddit.com/r/reactjs/comments/c8m8z0/tutorial_on_deploying_a_createreactapp_website_to/).
Create factory with an uploaded file in Rails rspec
Tags: rails
Published: 2019-07-03 14:45:49

To create a factory with an uploaded file in Rails rspec, needs to be included `ActionDispatch::TestProcess` module in the `rails_helper.rb` file to use the `#fixture_file_upload` method in the factories.

```ruby
# spec/rails_helper.rb
include ActionDispatch::TestProcess
```

In a factory, when setting the attribute value, use the method `#fixture_file_upload`, specifying the path and file type.

```ruby
# spec/factories/import_file.rb
FactoryBot.define do
  factory :import_file, class: ImportFile do
    data { fixture_file_upload 'spec/fixtures/test_file.pdf', 'application/pdf' }
  end
end
```
Use hash or case-statement in Ruby?
Tags: ruby
Published: 2019-07-03 14:45:34

Often, when we need to get a value based on the other one, we're using a case-statement. Like this
```ruby
def realizing_trade_type(realizable_trade_type)
  case realizable_trade_type
  when 'buy'
    'sell'
  when 'short'
    'cover'
  when 'buy_contract'
    'sell_contract'
  when 'short_contract'
    'cover_contract'
  end
end
```
But, if the conditions and the results are simple values, why don't we use hash for this? We can :)
```ruby
REALIZING_TRADE_TYPES = {
  'buy'            => 'sell',
  'short'          => 'cover',
  'buy_contract'   => 'sell_contract',
  'short_contract' => 'cover_contract'
}.freeze
```
Here is the benchmark of both options, executed 10_000_000 times. It shows that a hash is faster in times for such the kind of usage.
```bash
>> require 'benchmark'
true
>> Benchmark.bm(15) do |x|
  x.report('hash') { 10_000_000.times { REALIZING_TRADE_TYPES['buy'] } }
  x.report('case-statement') { 10_000_000.times { realizing_trade_type 'buy' } }
  x.report('empty') { 10_000_000.times {} }
end
                      user     system      total        real
hash              0.990423   0.003412   0.993835 (  1.057612)
case-statement    1.752263   0.004531   1.756794 (  1.762030)
empty             0.380810   0.000728   0.381538 (  0.382153)
```
So, it's better to use a hash when you are just retrieving some values (like in the example above). If there is additional logic to execute, a case-statement is still a way to go.
Render and combine PDF files into one
Tags: rails
Published: 2019-07-03 14:45:27

Render PDF files from HTML templates in [Rails](https://rubyonrails.org/) can be done using [WickedPDF](https://github.com/mileszs/wicked_pdf).

First you need to use `ActionView` to render HTML to a string:

```ruby
def render_to_string(data)
  action_view = ActionView::Base.new
  action_view.view_paths = ActionController::Base.view_paths

  action_view.class_eval do
    include ApplicationHelper
    include PDFHelper
    # or other helpers
  end

  action_view.render template: 'pdf/template.html',
                     layout: 'layout/pdf.html',
                     locals: { data: data }
end
```
Then you can render pdf with the desired settings like this:
```ruby
# first pdf file with some view settings and values from data1...
pdf1 = WickedPdf.new.pdf_from_string(
		render_to_string(data1), {
			pdf: 'report1',
			page_size: 'Letter',
			orientation: 'Portrait'
		})
# ...and second pdf file with some view settings and values from data2
pdf2 = WickedPdf.new.pdf_from_string(
		render_to_string(data2), {
			pdf: 'report2',
			page_size: 'Letter',
			orientation: 'Landscape'
		})
```
And now you can combine it with [CombinePDF](https://github.com/boazsegev/combine_pdf) gem, that provide you `parse` method to get PDF content and `to_pdf`method to render the result back to PDF.
```ruby
combiner = CombinePDF.new
combiner << CombinePDF.parse(pdf1)
combiner << CombinePDF.parse(pdf2)
combiner.to_pdf
```
Use image files from S3 in WickedPdf
Tags: rails
Published: 2019-07-03 14:45:21

If you need to use image files from S3 in your generated pdf file using WickedPdf, then you need first to download the image. You can create method that does this and add it to the helper.

```ruby
require 'open-uri'

module PdfHelper
  def embed_remote_image(url, content_type)
    asset = open(url, "r:UTF-8", &:read)
    base64 = Base64.encode64(asset.to_s).gsub(/\s+/, "")
    "data:#{content_type};base64,#{Rack::Utils.escape(base64)}"
  end
end
```
And use `image_tag` instead of `wicked_pdf_image_tag`
```slim
= image_tag embed_remote_image(file.logo_url, 'image/jpeg')
```
Manage Elixir versions like RVM & Rbenv
Tags: elixir
Published: 2019-07-03 14:45:16

You can install different versions of the Elixir with help of Kiex, like in Ruby with a RVM and Rbenv.

Download and install Kiex
```bash
\curl -sSL https://raw.githubusercontent.com/taylor/kiex/master/install | bash -s
```bash
 
In .bashrc (or .zshrc if you use z shell), add the following
```bash
[[ -s "$HOME/.kiex/scripts/kiex" ]] && source "$HOME/.kiex/scripts/kiex"
```bash

Install required Elixir 
```bash
kiex install 1.7 # or another version
```bash

And then you can use any version
```bash
kiex use 1.7
```bash
How to create zip files on the fly w/o Tempfile
Tags: ruby
Published: 2019-07-03 14:45:05

There are many articles about how to archive files from the server and send a zip-file to a client without persisting it on the server. But usually they don't literally do it, because they use temporary files.

There is a simple way to do it without creating any file though. You just have to put files directly to `Zip::OutputStream` and then read from it. Btw pay attention: you must rewind the stream before reading it.

```ruby
# some files objects
def download(files)
  zip_stream = Zip::OutputStream.write_buffer do |zip|
    files.each.with_index(1) do |file, index|
     # file name must be uniq in archive
      zip.put_next_entry("#{file.name}--#{index}.#{file.extension}")
      zip.write(file.read.force_encoding('utf-8'))
    end
  end
  # important - rewind the steam
  zip_stream.rewind
  send_data zip_stream.read, 
            type: 'application/zip', 
            disposition: 'attachment', 
            filename: 'files-archive.zip'
end
```
+20 posibles temas para enviar tu propuesta a JSWeek.org
Tags: cfp
Published: 2019-07-03 14:30:33

Angular
Babel JS 
Closures
D3
Design Patterns
ES6
Firebase
Flow
Flux
Git Hooks
Glimmer
Grunt
Gulp
Jasmine (Testing)
Jest (Testing)
Lodash
Mocha (Testing)
NextJS
Optimización en Javascript.
Patrones de diseño
PostCSS
Prettier + ESLint
Programación Funcional
React
Redux
Typescript
VueJS
Webpack

¿Conoces uno que debería estar en nuestra lista? ⬇️ Comenta!

¿Ya sabes qué tema dar? [Envialo aquí](https://docs.google.com/forms/d/e/1FAIpQLSeWPmA_ACxbcidEPmwiBve9fO6zjXDbleJLx4ct3ngnKf59Vw/viewform)
How to delete polymorphic models cascade
Tags: rails
Published: 2019-07-03 14:44:30

If you use a polymorphic model in your Rails application, like in example
```ruby
class Trade < ActiveRecord::Base
  has_many :gl_entries, as: :source, dependent: :destroy
end

class GlEntry < ActiveRecord::Base
  belongs_to :source, polymorphic: true
end
```

You will not be able to add the usual foreign keys for cascading delete records. But this can be implemented using a database.

To do this, you need to write a trigger in the database that will run the delete function for each record. 

```sql
CREATE FUNCTION deleteGlEntriesOfTrade()
  RETURNS TRIGGER
  SET SCHEMA 'public'
  LANGUAGE plpgsql 
  AS $$
  BEGIN
    DELETE FROM gl_entries WHERE source_id = OLD.id AND source_type = 'Trade';
    RETURN OLD;   
  END;
  $$;
      
CREATE TRIGGER deleteTradesGlEntriesTrigger 
  BEFORE DELETE ON trades
  FOR EACH ROW EXECUTE PROCEDURE deleteGlEntriesOfTrade();
```
Create a migration and use :)
How to add index to a large working app on Rails?
Tags: rails
Published: 2019-07-03 14:37:27

Well known fact is that PostgreSQL and many other RDBMS lock write access on the table while the index is being created. It is not acceptable when your project is large enough to allow a downtime for such the small adjustment like a new index.
There is a way to avoid the write-lock though. You can create the index concurrently. But how to do it with Rails Migrations?
First of all you can pass `:algorithm` option:
```ruby
class AddIndexOnBatchIdToFundTrades < ActiveRecord::Migration[5.0]
  def change
    add_index :fund_trades, :batch_id, algorithm: :concurrently
  end
end
```

But when you try to run such the migration, you would get the following error:

```
PG::ActiveSqlTransaction: ERROR:  CREATE INDEX CONCURRENTLY cannot run inside a transaction block
: CREATE  INDEX CONCURRENTLY "index_fund_trades_on_batch_id" ON "fund_trades"  ("batch_id")
```
That's because any migration by default is executed inside a transaction. Thankfully there is a way to pass it through - use `disable_ddl_transaction!` to run your migration without a transaction:

```ruby
class AddIndexOnBatchIdToFundTrades < ActiveRecord::Migration[5.0]
  disable_ddl_transaction!

  def change
    add_index :fund_trades, :batch_id, algorithm: :concurrently
  end
end
```
Need help with terminology for humans that follow instructions from a script
Tags: help, terminology
Published: 2019-07-03 14:32:32

---
title: Need help with terminology for humans that follow instructions from a script
published: true
tags: #help #terminology
---

I'm trying to name things in my project, and I've been struggling too long to find names for two roles. These names are important because they are going to appear as prefixes/suffixes all over the codebase.

One of these roles is for a script that connects to the server and transmits instructions. The other role is for humans that connect to the server with a client. The client shows the instructions from the script to the humans, and they need to follow them and click on a button to report when they have finished.

My initial thought was to call them _Host_ and _Client_ - but the host is also a client that connects to the server, so that doesn't feel right.

I also thought to call them _Script_ and _Human_, but "script" already packs too much meaning in general. Same with _Plan_ and _Worker_.

Does anyone have any ideas? Maybe common terms for these roles from fields where this pattern is common?
Most efficient way to add to an array. 
Tags: react
Published: 2019-07-03 14:20:21

I’m learning react and building a site which basically has a heap of lists. Which the user can filter with a search box. 

My question is:

As I add more and more objects with multiple props to an array it’s going to get quite large and time consuming. So what is the best way that I should be looking at doing this. ?

I was thinking I would like to have a form with fields for different props etc that then pushes the data as an object into the array onclick of a submit button etc. 

As that would save a lot of time. But I’m open to any better ideas that may be available. 

Also I’f I push the data from the form to the array as a new object. Will it actually physically change the array. As in I can look at the array and the new object will be there ?

I don’t have any code yet as I’m just looking for some direction to which avenue I should pursue. 

Thanks in advance for any help.
Deploying Node/Express app on a Windows Server
Tags: node, express, iis, windows
Published: 2019-07-03 14:14:10

---
title: Deploying Node/Express app on a Windows Server 
published: true
description: Deploying Node/Express app on a windows server and using IIS as a proxy 
tags: node, express, iis, windows
---

I had this small side project I worked on for a client over a weekend, it was a simple express API. 
Everything worked well and good until it was time to deploy! This was my conversation with the client..

*Me*: Cool so the app is ready, can you send me your staging server details so i can deploy for you?
*Client*: Yea cool, i will send you an RDP credentials to our Windows VM
*Me*: Wait what? ![](https://thepracticaldev.s3.amazonaws.com/i/o4si5el1jpz9cxxe6p41.jpg)

Ok jokes apart, lets get straight into it!

Before we continue, you should have a basic knowledge of Setting up a simple [Express App](https://expressjs.com/) and using [Nodemon](https://nodemon.io/) or  any other Node Process manager.

To speed things up, i have setup a simple express app with a single endpoint for this demo, please note that the target is not necessarily an introduction to Express but how to deploy an Express based app on Windows.

{% github massivebrains/express-demo %}

You can clone the repo to follow along.

## Setup the express app on the server
If you are using the sample app that was cloned, run `yarn` and then `yarn start` . The app should now start with `nodemon`. Assuming you have not changed the default port, head over to your browser at http://localhost:3000 . you should see the sample json response as below

```json
{
  status: true,
  data: "Api Works"
}
```

## Setting up a proxy with IIS
Now the app is running locally but not available outside the server. What we want is for the public to be able to reach the app at `http://yourdomain.com/app` where `http://yourdomain.com` is our domain.

### Step 1
Search and open Internet Information Services (IIS)
![](https://thepracticaldev.s3.amazonaws.com/i/aiitjluhal1o2qghm2gv.png)

### Step 2
Expand Sites -> Default Web Site

![](https://thepracticaldev.s3.amazonaws.com/i/bx8hjft0roovya37xc19.png)

Right click on *Default Web Site* and select *Add Application*

![](https://thepracticaldev.s3.amazonaws.com/i/1g023u4vfzlvs07jejib.png)

### Adding a URL rewrite
Make sure the newly created app is selected under the *Default Web Site*, click on *URL Rewrite* from the IIS dashboard on the right.

![](https://thepracticaldev.s3.amazonaws.com/i/19kk6nuxqcs65ffznyyh.png)

On the right, click on *Add Rule(s)* and then select *Reverse Proxy*

![](https://thepracticaldev.s3.amazonaws.com/i/6vi0d3ichu777enpfk8p.png)

On the inbound rules dialogue box, enter `localhost:3000` as illustrated below.


![](https://thepracticaldev.s3.amazonaws.com/i/0b7ay2r4qogmgp2urgxy.png)

> If you changed the port number where the express app is currently running, make sure you use `localhost:{port_number}`

Click on *OK* after this.

Now head over to a browser (outside your server) and try to access *http://yourdomain.com/api* (where *http://yourdomain.com*) is your actual domain name.
Daily Challenge #4 - Checkbook Balancing
Tags: challenge
Published: 2019-07-01 15:51:14

---
title: Daily Challenge #4 - Checkbook Balancing
published: true
series: Daily Challenge
description: We're ramping up the difficulty with our fourth daily challenge. 
tags: #challenge
---
Good morning, everyone. 

Don’t say I didn’t warn you, we’re moving from letters to numbers with this challenge. 

Today’s challenge comes from user [_@g964_ on CodeWars](https://www.codewars.com/kata/59d727d40e8c9dd2dd00009f). 

>You are given a small checkbook to balance that is given to you as a string. Sometimes, this checkbook will be cluttered by non-alphanumeric characters. 

>The first line shows the original balance. Each other (not blank) line gives information: check number, category, and check amount. 

>You need to clean the lines first, keeping only letters, digits, dots, and spaces. Next, return the report as a string. On each line of the report, you have to add the new balance. In the last two lines, return the total expenses and average expense. Round your results to two decimal places. 

>####Example Checkbook
1000.00
125 Market 125.45
126 Hardware 34.95
127 Video 7.45
128 Book 14.32
129 Gasoline 16.10

>####Example Solution
Original_Balance: 1000.00
125 Market 125.45 Balance 874.55
126 Hardware 34.95 Balance 839.60
127 Video 7.45 Balance 832.15
128 Book 14.32 Balance 817.83
129 Gasoline 16.10 Balance 801.73
Total expense  198.27
Average expense  39.65

>#### Challenge Checkbook
1233.00
125 Hardware;! 24.8?;
123 Flowers 93.5
127 Meat 120.90
120 Picture 34.00
124 Gasoline 11.00
123 Photos;! 71.4?;
122 Picture 93.5
132 Tires;! 19.00,?;
129 Stamps 13.6
129 Fruits{} 17.6
129 Market;! 128.00?;
121 Gasoline;! 13.6?;

Good luck and happy coding!
***
_Thank you to [CodeWars](https://codewars.com/), who has licensed redistribution of this challenge under the [2-Clause BSD License](https://opensource.org/licenses/BSD-2-Clause)!_

_Want to propose a challenge for a future post?  Email **yo+challenge@dev.to** with your suggestions!_
Sometimes when I'm writing Javascript I want to throw up my hands and say "this is bullshit!"....
Tags: jokes, javascript, beginners
Published: 2019-07-03 13:44:49

# **...but I can never remember what "this" refers to. 😭**

***

It's an old tweet of mine 😄

{% tweet 578925947245633536 %}

***

We elevated this the jokes tag today, follow if you like more content like this.

{% tag jokes %}
Did you hear about the JS dev who applied for a job?
Tags: jokes, javascript
Published: 2019-07-03 13:43:53

---
title: Did you hear about the JS dev who applied for a job?
published: true
description: JavaScript joke
tags: jokes,javascript
canonical_url: https://twitter.com/dmakogon/status/954394441892102145
---

Did you hear about the JavaScript programmer who applied for a job???

The recruiter said they might get a callback, but no promises…

{% twitter 954394441892102145 %}
Short URLS from Python
Tags: python
Published: 2019-07-03 13:42:54

---
title: Short URLS from Python
published: true
description: python, short url
tags: python
---
<img src="https://media1.tenor.com/images/c2945b67e01fe831f8b42696d7899a4c/tenor.gif">

Many times you'll have long URLs that need to go to another device. Like say you have a long url in one computer, but you want to open that on another computer or phone.

To solve that problem, you can use short urls, or an url shortener.
But, did you know you can do that from Python?

    #!/usr/bin/python3
    import urllib.request
    
    def tiny_url(url):
        apiurl = "http://tinyurl.com/api-create.php?url="
        tinyurl = urllib.request.urlopen(apiurl + url).read()
        return tinyurl.decode("utf-8")
 
    print(tiny_url('https://news.ycombinator.com/item?id=20342791'))

This will output a short url for "https://news.ycombinator.com/item?id=20342791".

You can turn this in a little command line app

    ./tinyurl.py https://duckduckgo.com

Like this:

    #!/usr/bin/python3                                                                                                        
    import urllib.request
    import sys
    
    def tiny_url(url):
        apiurl = "http://tinyurl.com/api-create.php?url="
        tinyurl = urllib.request.urlopen(apiurl + url).read()
        return tinyurl.decode("utf-8")
    
    url = sys.argv[1]
    print(url)
    print(tiny_url(url))

Learn Python?

* https://pythonbasics.org
* https://pythonprogramminglanguage.com