teleren/devto huggingface dataset:
SOLID Programming (Part 2): Open/Closed Principle
Tags: solidprogramming, python
Published: 2019-09-27 14:22:00

---
title: SOLID Programming (Part 2): Open/Closed Principle
published: true
description: Overview of the Single Responsibility Principle with an example in Python
tags: #solidprogramming #python
---

‘O’ in SOLID stands for Open/Closed Principle. It is closely related to the Single Responsibility Principle as code written with Single Responsibility in mind tends to comply with the Open/Closed Principle too.

**Open/Closed Principle says that the code should be open for extension but closed for modification**. In other words, the code should be organized in such a way that new modules can be added without modifying the existing code.

Let’s look at an example of the function that counts words in a text after extracting it in a local file:

```python
def count_word_occurrences(word, localfile):
content = return open(file, "r").read()
 counter = 0
    for e in content.split():
        if word.lower() == e.lower():
            counter += 1
    return counter
```


But what if we wanted to extract content from other source, like for example a url? If we worked with the above function, to implement new functionality, we would need to modify the existing function which would go against the Open/Closed Principle.

The better way of organizing the code would be the following:

```python
def read_localfile(file):
    '''Read file'''
    return open(file, "r").read()


def count_word_occurrences(word, content):
    '''Count number of word occurrences in a file'''

    counter = 0
    for e in content.split():
        if word.lower() == e.lower():
            counter += 1
    return counter
```



This way, if we wanted to add reading from url functionality, we would just add the function that extracts text from url:

```python
from bs4 import BeautifulSoup
from urllib.request import urlopen

def get_text_from_url(url):
    '''Extract html as string from given url'''
    page = urlopen(url).read()
    soup = BeautifulSoup(page)
    text = soup.get_text()
    return text
```

Next we would just call the already existing function `count_word_occurrences()` with the content extracted using `get_text_from_url()` function:

```python
content = get_text_from_url('https://en.wikipedia.org/wiki/Main_Page')
count_word_occurrences('and', content)
```

So we added new functionality to the code without needing to modify the existing code.

### Code in GitHub

You can find the code for this article in this GitHub repository:
https://github.com/AnnaLara/SOLID_blogposts
New Contributors Welcome / Open Source project (ES4X)
Tags: hacktoberfest, contributorswanted
Published: 2019-09-27 11:49:34

---
title: New Contributors Welcome / Open Source project (ES4X)
published: true
description: 
tags: hacktoberfest, contributorswanted
---

👋 there!

[ES4X](https://reactiverse.io/es4x/) is a JavaScript runtime that runs on top of GraalVM and used Eclipse Vert.x for high performance IO and event loop.

{% github reactiverse/es4x %}

The project started a while ago as an attempt to modernize the polyglot aspect of vert.x.

The goals of the project are simple:

1. Provide a *node-like* developer experience
2. Expose all APIs as *.d.ts* files
3. K.I.S.S.

As the project has been through experimentation for a long time, there are many undocumented features that need ♥.

It can also be an intesting starting point if you would like to learn more about GraalVM, by reading the code, fixing bugs, or add more tests!


## Contributors Wanted

If you're interested in practise your `Java` and `JavaScript` skills, follow the project link and see the issues tagged as `Hacktoberfest`. If you would like to work on other features, please open an issue and we will gladly review it and tag if necessary!
How should you ignore files for just you in git?
Tags: programming, git, webdev, productivity
Published: 2019-09-27 14:19:04

---
title: How should you ignore files for just you in git?
published: true
description: Sometimes it's helpful to ignore files in git outside of the shared .gitignore file. In this post, we'll quickly examine a way to keep files out of git without impacting the rest of our team.
tags: programming, git, webdev, productivity
---

## No, this isn't a post about .gitignore

The `.gitignore` file is a great way to exclude files from a repository for all users. This post is not about that.

I often want to ignore files that a tool / editor I use generates in a project. Others who are working in the project may not be using these same tools so adding to a `.gitignore` file may not be the best solution.

## Exclude file

There is the concept of a local exclude file in git. It works just like `.gitignore` but the file is not checked in.

It's available at `.git/info/exclude` from a project directory.

## Keep in mind

Files that should **always** be ignored should be specified in `.gitignore`. Files that you want to exclude locally could go in `.git/info/exclude` 👍

(_[crossposted from ryanlanciaux.com](http://ryanlanciaux.com/blog/2019/08/19/ignoring-files-in-git/)_)
Free workshop on GraphQL, Microservices, Serverless and Deploying to the Cloud, docs+ code solutions, enjoy!
Tags: tutorial, javascript, docker, graphql
Published: 2019-09-27 14:13:49

---
title: Free workshop on GraphQL, Microservices, Serverless and Deploying to the Cloud, docs+ code solutions, enjoy!
published: true
description: This a is free workshop that you can use (MIT License). It covers GraphQL, Docker, Serverless and deployment to the Cloud
tags: tutorial, javascript, docker, graphql
cover_image: https://thepracticaldev.s3.amazonaws.com/i/edejjwta7d7dp4ewprt7.jpg
---

Follow me on [Twitter](https://twitter.com/chris_noring), happy to take your suggestions on topics or improvements /Chris

> This article is part of #ServerlessSeptember. You'll find other helpful articles, detailed tutorials, and videos in this all-things-Serverless content collection. New articles are published every day — that's right, every day — from community members and cloud advocates in the month of September.

Friends, I just open-sourced a workshop with solutions :)

I created the workshop to teach the following:

- **Part I, GraphQL**, this teaches GraphQL with Apollo so you will learn to define a schema with resolvers and it covers both query and mutation and custom types
- **Part II, Microservices and Docker**, this shows how to create a simple Node.js Express app and Dockerize it. It covers some fundamentals of Docker including the usage of Docker-Compose
- **Part III, Serverless**, this teaches Azure Functions and how to integrate our GraphQL Server and also how to integrate our Service endpoints we created in part II
- **Part IV Deployment**, this shows how to deploy to the Cloud using Azure CLI but also how to do so Visually through the portal. So that means deploying our Service endpoints as containers but also how to deploy Serverless.

I've rendered the workshop docs as a static site
> To the workshop [https://aka.ms/graphql-workshop](https://aka.ms/graphql-workshop)

All of this comes with a GitHub repo that has an MIT license. So free to use :) You can find it here: 

> To the GitHub repo [https://github.com/softchris/serverless-graphql-microservices](https://github.com/softchris/serverless-graphql-microservices)

Feel free to use this to teach your colleagues, friends or just yourselves

All the best
/Chris
The difference between cd - vs cd ~-
Tags: linux, bash, ubuntu, productivity
Published: 2019-09-27 14:12:29

The other day I posted one of my old (from 16 years ago) blog entries on [twitter](https://twitter.com/pfreitag/status/1174384933110013952), [Backtracking with Bash](https://www.petefreitag.com/item/66.cfm) which shows a cool trick you can use to go to the directory you were previously in using `cd ~-` for example:

```
$ cd /var
$ cd /etc
$ cd ~-
$ pwd
/var
```

Ryan Guill pointed out that `cd -` also works, so what is the difference between `cd ~-` and `cd -`?

```
$ cd /var
$ cd /etc
$ cd -
/var
$ pwd
/var
```

**So what is the difference?**

The biggest difference between `cd ~-` and `cd -` is that `~-` can be used in any command because it is part of the shells tilde expansion. The `-` shortcut can only be used with the `cd` command.

So for example if your directory was previously `/var/log/apache2` and you want to tail the access_log file in there you can just `tail ~-/access_log`

```
$ cd /var/log/apache2
$ cd /etc
$ tail ~-/access_log
It Works...
$ tail -/access_log
tail: illegal option -- /
```

The second difference is that `cd -` will print the directory it changed to out to standard output, and `cd ~-` just changes directories without printing anything.

Cool trick eh?
Concern | split, and spin-off, share the responsibility in Rails
Tags: rails
Published: 2019-09-27 13:13:59

---
title: Concern | split, and spin-off, share the responsibility in Rails
tags: rails
published: true
---

## 🦄 Code Template
Make `mogera` logic into the concern.

```ruby
# lib/fuga/piyo.rb ( you can make it inside of the lib 👍)

module Fuga::Piyo
  extend ActiveSupport::Concern

  def mogera
    # do something...
  end
end
```

Then, include the `mogera` method.
```ruby
# hoge.rb

class Hoge < ActiveRecord::Base
  include Fuga::Piyo
end
```

## ✅ Testing
Write the test code for the `mogera` and the `piyo` module as `shared_examples_for`.

By building the model from metaprogramming, you can call the model which includes this concern from this concern test. ( The power of the metaprogramming 😎 )

```ruby
# spec/lib/fuga/piyo_spec.rb
require 'rails_helper'

shared_examples_for 'piyo' do
  let(:model_name) { described_class.to_s.underscore.gsub(/\//,'_').to_sym }
  let(:model) { build(model_name)}

  describe 'mogera' do
    # test code
  end
end
```

Enable to load the test files.
```ruby
# spec/rails_helper.rb
Dir[Rails.root.join('spec/lib/**/*.rb')].each { |f| require f }
```

Include it via `rails_helper` and test it at it behaves_like.
```ruby
# spec/hoge_spec.rb
require 'rails_helper'

describe V3::ContactRequest do

  # I recommend to split this test from others to test it isolated. ( `rspec spec/hoge_spec.rb -e 'includes'`
  describe 'includes' do
    it_behaves_like 'piyo'
  end
end
```

Then, test it.
```sh
bundle exec rspec spec/hoge_spec.rb -e 'includes'
```

In this way, you can test this concern at each model which includes the concern.

---

## 🔗 Parent Note
{% link n350071/my-rails-note-47cj %}
Kotlin Class Computed Properties
Tags: kotlin, android
Published: 2019-09-27 13:00:58

Here's a quick tip that I didn't notice when implementing a Kotlin class. I wanted to have a computed property that would return a value of a backing class's property.

This seemed pretty straightforward so I wrote it like this (not the actual code, but you'll get the idea):

    val Age: Int = person.Age()

The problem here is that a property like this is not really a computed property, even though it may look like it since it's getting the value from a function call. Instead this property is initialized only once when its class is created and thus the function is only called once. So if your Age function returns a different value based on information that is provided later then it won't be correct.

Instead the solution is to create an actual computed property by using get like this:

    val Age: Int
        get() = person.Age()

This is a read-only computed property and the get() is called each time so you'll always have the correct value from the Age() function.

Learn more about Kotlin class properties here: https://kotlinlang.org/docs/reference/properties.html
Put Your Dog In Version Control! 🐶
Tags: discuss
Published: 2019-09-27 12:56:07

Let me just preface this by letting you know that reading this blog, you will learn:
- Absolutely nothing.


# Introduction

Last night I had a very strange yet brilliant dream and I feel almost compelled to share it with the world.

Meet Buster:

![Buster photo](https://i.imgur.com/3DXB7s5.jpg)

Recently, Buster has been acting a little differently, he's been really jumpy, barks in the morning and doesn't respond when I shout the bugger. I thought maybe there's a chance he's losing his hearing, I did a google of his symptoms and they seem to match up exactly.

![Symptoms of dog losing hearing](https://i.imgur.com/EvCVJOw.png)

# Dream 💤

Naturally, I've been worrying about him as my working from home days just wouldn't be the same without his snoring, it's like white noise to me.
{% vimeo 362612680 %}

It would seem that even my subconscious is worried about the little fluff ball that last night prompted a peculiarly ingenious dream.

Buster, the brilliant Shih Tzu was uploaded to version control, **GIT-4-DOGS**. Now in my dream, this was completely normal, you'd be absolutely *barking* not to regularly commit your dog to its repo.

Anyway, in my dream, I was worried about Buster losing his hearing so I decided to check out an earlier version of him `Buster_Age_1` so I could perform some tests against the current Buster - `Buster_Age_10`.

I left the two Busters to introduce themselves to themselves, whilst I went and got a couple frying pans. I peaked my head around the corner to watch their reactions as I smashed the two pans together. `Buster_Age_1` jumped a good 2 feet in the air in reaction to the bang. `Buster_Age_10` just looked slightly baffled at `Buster_Age_1` as he jumped about&mdash;that confirmed that. 

# Let me know your brilliant dreams!

This seems to be a recurring thing, I'm constantly engrossed in the world of software development that my dreams make a sloppy merge of it with reality. 90% of the time though I forget the brilliance in the morning. 

I'd love to hear if you've had any dreams related to software development or had any that have been genuinely good ideas (like an app), or just anything even remotely relatable to tech, I want to hear them all!

Follow me on twitter if you don't want to miss out on absolutely brilliant programming insight: 🤣 @luke_garrigan

Thank you, if you like my rambling check out my personal blogging site at https://codeheir.com/

## This blog is sponsored by <a href="https://www.codecanvases.com">Code Canvases</a>

Make your room come alive  with the coolest programming/coding canvases on the market.<a href="https://www.w3schools.com"> codecanvases.com</a> is the number 1 seller for programming prints with 100% exclusively designed canvases. Get them now whilst they're **20% off!!**
![[https://codecanvases.com/](https://codecanvases.com/)](https://cdn.shopify.com/s/files/1/0311/0151/7955/products/jqbr8djyof6ktl8qopmkpvy4_480x480.png?v=1585483987)
model/table name conversions in Rails
Tags: rails
Published: 2019-09-27 12:49:17

---
title: model/table name conversions in Rails
tags: rails
published: true
---

📚 [Doc ActiveSupport::Inflector module](https://api.rubyonrails.org/classes/ActiveSupport/Inflector.html)

## object to class name
```ruby
@person.class.name  #=> "Person"
Person.name         #=> "Person"
```

## Class to table name
```ruby
User.table_name   #=> "users"
```

## tableize
```ruby
"Person".tableize      # => "people"
"Invoice".tableize     # => "invoices"
"InvoiceLine".tableize # => "invoice_lines"
```

## classify
```ruby
"people".classify                        # => "Person"
"invoices".classify                      # => "Invoice"
"invoice_lines".classify                 # => "InvoiceLine"
"highrise_production.companies".classify # => "Company"
```

## constantize

```ruby
"Fixnum".constantize # => Fixnum
```

---

## pluralize
```ruby
"table".pluralize     # => "tables"
"ruby".pluralize      # => "rubies"
"equipment".pluralize # => "equipment"

"dude".pluralize      # => "dudes"
"dude".pluralize(0)   # => "dudes"
"dude".pluralize(1)   # => "dude"
"dude".pluralize(2)   # => "dudes"
```

## singularize
```ruby
"tables".singularize    # => "table"
"rubies".singularize    # => "ruby"
"equipment".singularize # => "equipment"
```

---

## camelize(camelcase)
"/" converts to "::".

```ruby
"product".camelize               # => "Product"
"admin_user".camelize            # => "AdminUser"
"backoffice/session".camelize    # => "Backoffice::Session"
"visual_effect".camelize(:lower) # => "visualEffect"
```

## underscore
"::" converts to "/".
I sometimes use it with `.gsub(/\//, '_')`.

```ruby
"Product".underscore             # => "product"
"AdminUser".underscore           # => "admin_user"
"Backoffice::Session".underscore # => "backoffice/session"
"visualEffect".underscore        # => "visual_effect"
```

## titleize(titlecase)
```ruby
"alice in wonderland".titleize # => "Alice In Wonderland"
"fermat's enigma".titleize     # => "Fermat's Enigma"
```

## dasherize
```ruby
"name".dasherize         # => "name"
"contact_data".dasherize # => "contact-data"
```

---

## demodulize
```ruby
"Product".demodulize                        # => "Product"
"Backoffice::UsersController".demodulize    # => "UsersController"
"Admin::Hotel::ReservationUtils".demodulize # => "ReservationUtils"
"::Inflections".demodulize                  # => "Inflections"
"".demodulize                               # => ""
```

## deconstantize
```ruby
"Product".deconstantize                        # => ""
"Backoffice::UsersController".deconstantize    # => "Backoffice"
"Admin::Hotel::ReservationUtils".deconstantize # => "Admin::Hotel"
```

## parameterize
```ruby
"John Smith".parameterize # => "john-smith"
"Kurt Gödel".parameterize # => "kurt-godel"
```



---

## 🔗 Parent Note
{% link n350071/my-rails-note-47cj %}
Stop checking if it's nil in Rails
Tags: rails
Published: 2019-09-27 12:34:32

---
title: Stop checking if it's nil in Rails
tags: rails
published: true
---

## From Nested Hash 
### 🤔 Umm,
Sometimes, I see like this code. The first row guards from the case of `session[:user] == nil`.

```ruby
if session[:hoge]
  fuga = session[:hoge][:fuga]
  piyo = session[:hoge][:piyo]
end
```

But, this way is not straight forward. How we cut the first line. The logic is NOT THE BUSSINESS LOGIC!!

### 🦄 Clear
[Hash#dig](https://docs.ruby-lang.org/en/2.6.0/Hash.html#method-i-dig) makes it simple. It checks the key-value is existed or not, and if it's not existed, dig returns nil.

It's similar of the `.&` method.

```ruby
fuga = session.dig(:hoge,:fuga)
piyo = session.dig(:hoge,:piyo)
```

## 👍 From Object
The safe navigate operator `&.` (We Japanese call it alone operator. It looks so).

This picture is inversion of &
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/3h1ntxtis1krj91elki8.png)


```ruby
10&.to_s  # => "10"
nil&.to_s #=> nil
```


---

## 🔗 Parent Note
{% link n350071/my-rails-note-47cj %}
Switch a couple of variable WITHOUT tmp in Ruby
Tags: rails
Published: 2019-09-27 11:57:53

---
title: Switch a couple of variable WITHOUT tmp in Ruby
tags: rails
published: true
---

## premise
```ruby
foo = 'foo'
bar = 'bar'
```

## Way that Uses tmp variable(Normal way)

```ruby
tmp = foo
foo = bar
bar = tmp
```

## Multi Assignment
Merit
- no tmp
- 3rows to 1row of the switch logic
- The switch intention became clear.

```ruby
foo, bar = bar, foo

# => [
#      [0] "bar",
#      [1] "foo"
#    ]

foo # => "bar"
bar # => "foo"
```

📚 [Multiassign](https://docs.ruby-lang.org/ja/latest/doc/spec=2foperator.html#multiassign)(ja)

---

## 🔗 Parent Note
{% link n350071/my-rails-note-47cj %}
Specify layout file in Rails Views
Tags: rails
Published: 2019-09-27 11:38:05

---
title: Specify layout file in Rails Views
tags: rails
published: true
---

## 1. At the Controller level
```ruby
class PostsController < ApplicationController
  layout "index_layout" only [:index]
  layout "nomal_layout" expect [:index]
end
```

## 2. At the action level
```ruby
class PostsController < ApplicationController
  if @post.save?
    render layout: "success_layout"
  else
    render :new, layout: false
 end
end
```

---

## 🔗 Parent Note
{% link n350071/my-rails-note-47cj %}
load stylesheet from controller_path
Tags: rails
Published: 2019-09-27 11:34:33

---
title: load stylesheet from controller_path
tags: rails
published: true
---

### 1. Call a metaprogramming code from the ApplicationLayout as the root.

```ruby
# app/views/layouts/application.html.erb
<%= load_stylesheet_from_controller_path %>
```

### 2. Evaluate controller path, and return the stylesheet_link_tag of the path.

```ruby
# app/helpers/application_helper.rb
def load_stylesheet_from_controller_path
  return unless File.exist?("#{Rails.root}/app/assets/stylesheets/#{controller.controller_path}.css.scss")

  stylesheet_link_tag stylesheet_path(controller.controller_path)
end
```

you can use `controller.action_name` instead of the path method.


---

## 🔗 Parent Note
{% link n350071/my-rails-note-47cj %}
Form tags of the ActionView::Helpers in Rails
Tags: rails
Published: 2019-09-27 11:27:16

---
title: Form tags of the ActionView::Helpers in Rails
tags: rails
published: true
---

## 🔗 Parent Note
{% link n350071/my-rails-note-47cj %}

## At the first,
There are several ways to make form tag, so I was confused for a while.  
But, because of [rubyonrails.org](https://api.rubyonrails.org/), I somewhat understand them or can use them now. Thanks!

## f.methods
If you're creating for a model or a form object, you use `<% form_for: @person do |f| %>` ([ActionView::Helpers::FormBuilder](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html)). Then, this way is easy.

```ruby
<% BLOOD_TYPE::Names.each |key, value| do %>
  <%= f.radio_button(:bload_type, key, {checked: key == f.objethe ct.bload_type, class: 'bload_type'}) %>
  <%= value %>
<% end %>

<%= f.text_area(:description, {class: 'myself', rows: 6, placeholder: "self intro"}) %>
```

Rails will make the HTML tags which id, names are made from the object attribute names, AUTOMATICALLY!.

Of course, you can make tags by following way, but you have to write id and names by your hands. It wastes time...

## tag
If you are creating a form for NOT a model, just a form.  
Maybe, you use `<form_tag("/posts/#{@post.id}", method="post")`.  
Then, you can't use `f` object.  
It's like this.

```ruby
<% BOOK::Categories.each do |key, value| %>
  <%= radio_button_tag(
        'book[category]',
        key,
        (key == f.object.category),
        class: 'my-class'
      ) %>
  <%= value %>
<% end %>
```