What does Memoization mean?

I was watching a screencast the other day and the person mentioned in the video: “… and this gives you an mm(…) array”. The (..) means that I did not understand what I had just heard. I admit that I rewinded the video a few times and I could only grasp something along the lines of ‘memorized array’. It was then that I googled this and was autocorrected to “memoization”. WAT?

It turns out that memoization is recording the results of earlier calculations so that we don’t have to repeat the calculations again. It simply means caching the output.

An example may clarify this further. Say I have method that tells me how many Twitter followers a user has:

def total_twitter_followers
  current_user.twitter_followers
end

This is perfectly valid, however, every time we call this method during one request it always calls the Twitter API for the result. By memoizing the call, you store the value thus avoiding expensive fetches again:

def total_twitter_followers
  @current_user_total_followers ||= current_user.twitter_followers
end

The ||= operator is a so-called conditional assignment that only assigns the value on its right to the variable on its left if the variable is not true. Since pretty much everything in Ruby evaluates to true when coerced into a boolean (except nil and, of course, false, as well as a couple of other things) this is exactly what we want: The first call returns the actual string and from the second time on, no matter how often the method is called on the same object, the “cached” result will be used.

Hope you learned something today.

Stacked Solution

I love when I get exposed to new ideas and concepts that enhance my work or expand my intellectual acumen. That is one of the reasons why I picked software development as a career: each day I learn something in the job. It is never boring.

Especially people like me that did not acquire a traditional Computer Science degree (I actually learned programming through this public-private initiative.), chance upon concepts of CS that both better our overall programming understanding and explain the theory behind our coding practices.

I had the opportunity to work on a computer science problem with Tim Mansfield, a very knowledgeable programmer and, as it could be noticed from the short interaction we had, a great guy.

The problem we worked together is called Balanced parenthesis. Later I learned that balanced parenthesis is one of the tasks done by a compiler. It verifies if parentheses in a source code have their counterpart or not. For example you would want that each opening ‘{‘ or ‘(‘ in a source code must have a corresponding closure ‘}’ or ‘)’. So if the code is not put properly, i.e. if they are not balanced ‘{(})’, the compiler should throw an error.

Here is the problem at length:

Write a function to determine if a string is
‘balanced’. Balanced means that opening and closing
brackets match each other in the proper order. Other
characters are possible and should be handled. The
possible characters for balancing are {}, (), and []

Example Input:

‘{}’ -> True
‘{[]}’ -> True
‘{5}’ -> True
‘{[}’ -> False
‘[A]{}d()’ -> True
‘a’ -> True
‘a}’ -> False
‘([)]’ -> False
‘([])’ -> True
‘{‘ -> False
‘{{{{}}}’ -> False

The best way to solve this is to break down the problem at hand by writing in plain English.

  #split the string into an array of characters
  #loop through the array
  #if open symbol i.e. '{','[','(' then store them in a list
  #if closing symbol then remove last opening symbol in list
  # if everything matches then the remaining list should be empty, otherwise there is unbalanced symbol.

Therefore delving now into the code we have:

def is_balanced(input)
 #split the string into an array of characters
  array_chars = input.chars

  open_brackets = []
 #loop through the array
  array_chars.each do |char|
    #if open symbol i.e. '{','[','(' then store them in a list
    if char =~ /[\[|\{|\(]/
      open_brackets << char
    elsif char =~ /[\]|\}|\)]/
      #if closing symbol matches an its opening symbol then remove last opening symbol in list
      bracket_matching = { ']' => '[', '}' => '{', ')' => '('}
      bracket = bracket_matching[char]
      return false unless open_brackets.include?(bracket)
      open_brackets.pop
    end
  end
  # if everything matches then the remaining list should be empty, otherwise there is unbalanced parenthesis.
  open_brackets.empty?
end

is_balanced('{{}}’) #=> true
is_balance('[(])') #=> false

We notice in this code that there is always inserting and removing one element from the end of the array. What is entering last, it is actually coming out first.

The implemented solution to this problem is called a Stack data structure. Thinking again, I remember implemented something similar when I worked on a linked-list problem months ago. There you go. I learned something that has already an impacted on my programming skills and for that it made my day.

Role-Based Authorization with Rails 4 Enum

I have started creating an employee engagement application recently. Its purpose is to allow companies to engage their employees in volunteering activities around social projects. For this application I need to create 3 different roles and access levels.

I am using Ruby on Rails and I discovered that you could do this with gems such as ActiveAdmin and Rolify. But I decided to give Rails 4 Enum a try.

In my application each User will have one role: a super_admin(that takes care of the whole application), company_admin(an person that administers employee engagement with this application), and employee(user from a company that uses the application). Therefore these are single-defined roles. Now if the User had the possibility to have more than a role, for instance a company_admin could also be a super_admin then this would be a bit more complex. It is indeed multiple role based authorization and the gem Rolify would do a better job at this.

Anyways, below is one way one can implement three different access levels using Enum.

An enumerated-type or enum in Rails is a hash where the values reference to integers in the database. Example

User.access_level # => {"employee"=>0, "company_admin"=>1, "super_admin"=>2}

More info about enum methods here

Assuming that you installed Devise and have a User table or similar, first add the access_level column to the users table

 rails g migration AddAccessLevelToUsers access_level:integer
class AddAccessLevelToUsers < ActiveRecord::Migration 
 def change
   #adding the default to zero will automatically set the user access level to the first Enum attribute
   add_column :users, :access_level, :integer, default: 0
 end
end

Now in the User Model add:

class User < ActiveRecord::Base
  # you can also explicitly define enum as:  enum access_level: [:employee => 0, :company_admin => 1, :super_admin => 2}
  enum access_level: [:employee, :company_admin, :super_admin]
  
end

Migrate the changes to database and create three users in Rails console. Assign them access levels

 # by default the user access_level is employee
 user1.access_level #=> employee 
 # below we are assigning access_level to user2 and user3 rather the default employee
 user2.company_admin!
 user3.super_admin!

For sanity check, let’s use some conditionals on a page view of your choice to see if it worked.

<% if current_user.super_admin? %>
  <h3>Welcome Super Admin</h3>
<% elsif current_user.company_admin? %>
  <h3>Welcome, Company Admin</h3>
<% else %>
  <h3>Welcome</h3>
<% end %>

If you sign up as a user3 you should see “Welcome Super Admin” on that page.

This is a simple implementation of single-role-based authorization using Rails 4 Enum. I hope you learned something.

Postgresql Did Not Work After I Updated to OS X Yosemite(With Solution)

This morning, I tried to start up an application on Rails with a Postgresql server and had this error:

PG::ConnectionBad: could not connect to server: Connection refused
&gt;       Is the server running on host &quot;localhost&quot; (::1) and accepting
&gt;       TCP/IP connections on port 5432?
&gt;     could not connect to server: Connection refused
&gt;       Is the server running on host &quot;localhost&quot; (127.0.0.1) and accepting
&gt;       TCP/IP connections on port 5432?

Checked server.log and it showed me what directories it was looking for. I also went to where postgresql gets stored to confirm the suspicion.

cd /usr/local/var/postgres

The directories pg_tblspc pg_twophase pg_stat_tmp were missing. These directories are empty anyways but when you boot up your pg server the server looks for them. I think the Yosemite update got rid of these directories. So I created them again anyways.

mkdir pg_tblspc pg_twophase pg_stat_tmp

And added a .keep file in them so that I don’t have this problem in future OS updates.

touch pg_tblspc/.keep pg_twophase/.keep pg_stat_tmp/.keep

Voilá

Understanding URL Query Strings

URL, short for Uniform Resource Locator, is web address that you see on web browsers.

You may have seen urls that look something like this.

http://website.com/page?example=this

The part after the question mark is a query string. It appears at the end of a URL and provides a way to send additional information that a web server can use to control the output of its response.

Generally a query string is used to search a database for information, and return a single record.

For example, if you want to send a link to a youtube video but you wish to start the video at a particular time you can forward the link as such:

www.youtube.com/watch?v=iAJhtHDwcS4#t=39m29s

Where v=iAJhtHDwcS4 after the question mark identifies which video to show from the youtube server and t=39m29s after # is the minutes and seconds the video will start from. The character # is used here to further specify a subsection (or fragment) of the video.

Query strings can hold multiple value pairs. Simply add an ampersand, followed by another 
name, an equal sign and another value.

http://website.com/page?field1=value1&field2=value2&field3=value3...

There are some requirements for query strings. 
Most importantly, you can’t just use any symbol you want in a query string. 
Some characters like the ampersand(&), equal(=), space( ), and
 quote marks(“”) have special meaning in a URL. 
So if you send information that includes
 those special characters you need to encode them.
That is, translate them into a set of symbols that 
are safe and don’t conflict with their URL specific version. 
For example, ampersand is represented by “%26”. 
A space is converted to a plus(+). 
And a plus is converted to “%2B”.

URL encode and decode is a website that can decode url query string symbols in case you are curious: http://www.url-encode-decode.com/