Wednesday, January 21, 2015

Top 10 Reasons Why Test Driven Development in Ruby Course is Awesome

Test Driven Development in Ruby Course is a comprehensive online course that covers the basics of Test Driven Development in Ruby for beginners. This course aims to help beginners to overcome difficulty in learning TDD. Each lessons in the course has hands on exercises to reinforce the material. You will learn TDD by applying the concepts in the lessons. At the end of the class, students will have worked through some common interview problems and gained skills that can be used to answer questions in an interview.
TDD in Ruby
  1. This course is designed by a developer for developers
  2. It makes complicated concepts easy to understand
  3. It is hands on step-by-step guide to learning TDD
  4. It gives a solid foundation for a beginner to TDD
  5. You will be doing Test Driven Development in Ruby in less than 4 hours
  6. Access to the entire transcript that is not released to the public yet.
  7. Access to the transcript in audio form that is not released to the public yet.
  8. Lifetime access to 42 lectures and 8 quizzes
  9. 3.5 hours of high quality content
  10. Use the downloadable checklists to guide you when coding
This course is the result of teaching one-day TDD boot-camps and TDD tutorials for Silicon Valley Ruby Meetups. I have spent more than 500 hours and thousands of dollars to create this course. Click on the image below to enroll for this course now.


TDD in Ruby

TDD in Ruby

Friday, December 05, 2014

Upgrading from Rails 4.1.4 to Rails 4.1.8

Problem when upgrading from Rails 4.1.4 to Rails 4.1.8

rails -v
Bundler is using a binstub that was created for a different gem.
This is deprecated, in future versions you may need to `bundle binstub rails` to work around a system/bundle conflict.
Rails 4.1.8


Fix:
$rm -rf bin/*
$bundle exec rake rails:update:bin
zepho-mac-pro:lafon zepho$ rails -v
Rails 4.1.8


Monday, November 24, 2014

Deploying a Rails App on Google App Engine

Deploying a Rails Webapp on GAE should be a piece of cake right? Due to lack of good documentation, it is not that easy. I had to dig around to find the versions of the software installed for Ruby Stack One-Click Deploy.

Here is some useful information to access installed software components.
Apache web server:  

Configuration directory: /etc/apache2
Default website directory: /var/www
Command to start Apache web server: sudo service apache2 start
Command to stop Apache web server: sudo service apache2 stop

Passenger:

Help command: passenger --help
Install directory: /usr/local/rvm/gems/ruby-2.1.1/gems/passenger-4.0.48

MySQL:

Command to access MySQL: mysql -u root -p
Command to start MySQL service: sudo service mysql start
Command to stop MySQL service: sudo service mysql stop

RVM, Ruby and Rails:

RVM Help command: rvm
Rails help command: rails -h
RVM install directory: /usr/local/rvm
Ruby install directory: /usr/local/rvm/src/ruby-2.1.1
Rails install directory: /usr/local/rvm/gems/ruby-2.1.1/gems/rails-4.1.4

Git:
Help command: git --help

Saturday, November 22, 2014

bin/rails:6: warning: already initialized constant APP_PATH

I was getting this error in Rails 4.2 beta when I started the rails server. Solution: run : rake rails:update:bin from rails project directory.

git Illegal instruction: 4 mac 10.7.5

Download the git for Mac 10.7.5  and restart your terminal.

Friday, November 14, 2014

Stripe API Capybara Test Failures

I was getting Stripe::InvalidRequestError: You must supply either a card or a customer id error. To fix this, make sure js is true in your integration test like this:

feature 'Guest Checkout' do
  scenario 'Complete purchase of one product', js: true do
    visit products_show_path
    click_link 'Buy Now'
   
    fill_in "Card Number", with: '4242424242424242'  
    page.select '10', from: "card_month"
    page.select '2029', from: 'card_year'
    click_button 'Buy Now'
   
    expect(page).to have_content('Receipt')
  end
end

Thursday, November 13, 2014

Base Ball Player Statistics

Overview:  For this scenario, we have been asked to write an application that will be used to provide information about baseball player statistics.  Approach this problem as if it is an application going to production.  We don't expect it to be perfect (no production code is), but we also don't want you to hack together a throw-away script.  This should be representative of something that you would be comfortable releasing to a production environment.  Also, spend whatever amount of time you think is reasonable.  If you don't get all the requirements completed, that's ok.  Just do the best you can with the time that you have available.  You may use whatever gems, frameworks and tools that you think are appropriate, just provide any special setup instructions when you submit your solution.

Assumptions:  All requests currently are based on data in the hitting file.  Future requests of the system will require data from a pitching file as well.  Consider this in the design.

Requirements: When the application is run, use the provided data and calculate the following results and write them to STDOUT.

1) Most improved batting average( hits / at-bats) from 2009 to 2010.  Only include players with at least 200 at-bats.
2) Slugging percentage for all players on the Oakland A's (teamID = OAK) in 2007. 
3) Who was the AL and NL triple crown winner for 2011 and 2012.  If no one won the crown, output "(No winner)"

Formulas:
Batting average = hits / at-bats
Slugging percentage = ((Hits – doubles – triples – home runs) + (2 * doubles) + (3 * triples) + (4 * home runs)) / at-bats
Triple crown winner – The player that had the highest batting average AND the most home runs AND the most RBI in their league. It's unusual for someone to win this, but there was a winner in 2012. “Officially” the batting title (highest league batting average) is based on a minimum of 502 plate appearances. The provided dataset does not include plate appearances. It also does not include walks so plate appearances cannot be calculated. Instead, use a constraint of a minimum of 400 at-bats to determine those eligible for the league batting title.


Data:  All the necessary data is available in the two csv files attached:

Batting-07-12.csv – Contains all the batting statistics from 2007-2012.  
Column header key:
AB – at-bats
H – hits
2B – doubles
3B – triples
HR – home runs
RBI – runs batted in

Master-small.csv – Contains the demographic data for all baseball players in history through 2012.


Please note: We are looking for you to demonstrate you knowledge related to common software practices to include reusability, portability, and encapsulation – to name a few. Work submitted should be in project form and implemented as you were implementing any production solution.


Tuesday, November 11, 2014

How to share files between Virtual Box Ubuntu with Mac OS host computer

1. Create a folder in your Mac home directory, let's say ubuntu-sf.
2. Install guest additions. Click Devices -> Guest Additions and run the installer.
3. Reboot VM
4. Select the Ubuntu image on VM, go to Settings -> Shared Folders
5. Browse to the folder on your Mac you want to share (ubuntu-sf). Name the shared folder (ubuntu-sf)
6. On Ubuntu terminal, run : sudo adduser your-username vboxsf
7. On Ubuntu terminal run: sudo mount -t vboxsf ubuntu-sf /home/bparanj/ubuntu-sf
   Here ubuntu-sf is the name of the shared folder we created in step 5. /home/bparanj/ubuntu-sf is the folder in the
   Ubuntu.


References

How to share files between Virtual Box Ubuntu and host computer
How to automatically mount a folder and change ownership from root in virtualbox


some of the partitions you created are too small ubuntu 12.04 LTS Precise Pangolin

I was getting this error during installation of Ubuntu on Virtual Box. Solution: Increase the hard disk size from default 8GB to something higher. It worked for 45GB.

Tuesday, November 04, 2014

How to get web_console working in Rails 4.2.beta4 project

1. Add the gem to Gemfile.

group :development do
  gem 'web-console', '2.0.0.beta3'
end

2. bundle

3. You can go to the web console by going to the URL : http://localhost:3000/console

You will also see the web console on the bottom of the browser. You can experiment with the Rails environment loaded.

4. You can add "<%= console %>" to any views and play with the web console.

If you restart the server. You need to reload the page to get a new active console session.

For more details : Web Console Ruby Gem

Problem installing nokogiri on Mac OS 10.7.5

Problem: Make sure that `gem install nokogiri -v '1.6.3.1'` succeeds before bundling.

Solution: bundle config build.nokogiri --use-system-libraries
Then run : bundle

libv8 and therubyracer installation problems on Mac OS 10.7.5

The error message is : Make sure that `gem install libv8 -v '3.16.14.7'` succeeds before bundling.
Solution: gem install libv8 -v '3.16.14.7' -- --with-system-v8

Make sure that `gem install therubyracer -v '0.12.1'` succeeds before bundling.
Solution : Change the Gemfile to specify the libv8 version:

gem 'libv8', '3.11.8.13' 
and run bundle

Sunday, October 19, 2014

Copy to Clipboard in Linux

1. Install xclip : sudo apt-get install xclip
2. Copy test.txt to clipboard : cat test.txt | xclip
3. Acess the text from the clipboard: xclip -o

Reference:

1. Copy Output of a Command to Clipboard

Wednesday, September 24, 2014

Changing PDF Meta Data in Ruby

According to the home page of pdf-toolkit gem :

pdf-toolkit allows you to access pdf metadata in read-write in a very simple way, through the pdftk commandline tool.

1. Install pdftk version 2.02

$ pdftk -version

pdftk 2.02 a Handy Tool for Manipulating PDF Documents
Copyright (c) 2003-13 Steward and Lee, LLC - Please Visit: www.pdftk.com
This is free software; see the source code for copying conditions. There is
NO warranty, not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

2. gem install pdf-toolkit

3. Read or Write pdf meta data.

require 'pdf/toolkit'

pdf = PDF::Toolkit.open('tmux_p3_0.pdf')
#puts pdf.public_methods(false).sort

puts pdf.author
pdf.author='Daffy Duck'
if pdf.save
  'PDF meta-data saved successfully'
else
  'Failed to save pdf meta-data'
end
# save! to raise exception on failure

puts "after change"
puts "Author"
puts pdf.author
puts 'Title'
puts pdf.title
puts 'Subject'
puts pdf.subject
puts 'Page count'
puts pdf.page_count
puts 'Creator (Publisher)'
puts pdf.creator
puts 'Created At'
puts pdf.created_at
puts 'keywords'
puts pdf.keywords
puts 'producer'
puts pdf.producer
puts 'version'
puts pdf.version
puts 'Updated at'
puts pdf.updated_at

4. Verify the meta-data in Preview -> Tools -> Show Inspector. You will see the author, title, subject, producer, creator, creation date, updated date, number of pages etc.

5. Read the tests in the pdf-toolkit source code to see the available methods.

Tuesday, September 23, 2014

Fast Typing, IDE shortcuts, Fast Coding

It does not matter how fast you type in the keyboard, know every short-cut in the IDE, never use the mouse or how fast you can code. Remember : It's garbage in, garbage out.

The quality of software depends on:

1. Quality of your thinking.
2. Learning from your mistakes. Did you learn from your own mistakes?
3. Are you making new mistakes or oblivious and making the same old mistakes over and over again?
4. Are you learning from the mistakes of others to minimize making mistakes in the first place?
5. Are you learning to master the best practices?
6. Are you reading books by : Martin Fowler, Alaister Coburn, Eric Evans, Robert Martin etc? Are you applying it to your projects?



Friday, September 19, 2014

wrong number of parameters 2 for in stylesheet_link_tag rails

This error occurs with an ambiguous error message. It does not show the line number of the source where the cause of the problem resides. This happened due to sass-rails dependency on sass gem. Since the sass gem was not declared in the Gemfile, the sass-rails upgraded sass gem to 3.4.4 which broke the application layout. By locking the sass gem to a lower version in the Gemfile:

gem sass, "~ 3.2.1"

The sass-rails picked up this version that works.

Monday, September 01, 2014

The Scientific Method of Troubleshooting

Notes from the presentation by Blithe Rocher.

Set of Techniques for Acquiring Knowledge.
Methodical
Systematic

1. Define the Problem
Expected behavior
Actual behavior
Criteria for success

2. Do Your Research
Know your environment
Read the literature
Discussions
Make it fail

3. Establish a Hypothesis
4. Design the Experiment
Divide and conquer
Limit the variables
Try something weird
Hierarchy of Blame

4. Gather Data
Current status
Read the error message

5. Analyze Your Results
 Problem Solved?
Learn anything?
Understand the Why
Future Experiments
Embrace the Success

6. Keep a Good Lab Notebook
You won't remember
Logs aren't enough
Commit messages
Update the docs
Contribute
Blog it
Share the knowledge



Friday, August 22, 2014

How to play with ActiveModel validators in the rails console

1. bundle open activemodel
2. Open the validator.rb file.
3. You can see the comments that shows you how to mixin the validators. Once you mixin, you can add any validator and define a dummy method for the attribute to play with it in the irb:

class Person
  include ActiveModel::Validations
  SSN_REGEX = /your ssn regex goes here/
  validates_format_of :ssn, with: SSN_REGEX
 
 
  def ssn   
    111-11-1111
  end
end

4. Change the ssn method to invalid ssn to test your regex.
 

Thursday, August 21, 2014

How to install Exception Notification gem in Rails 4.1

1. Add the gem to Gemfile:

gem 'exception_notification'



bundle install

2. In config/environments/production.rb:

Whatever::Application.config.middleware.use ExceptionNotification::Rack,
  :email => {
    :email_prefix => "[Whatever] ",
    :sender_address => %{"notifier" },
    :exception_recipients => %w{exceptions@example.com}
  }

3. Configure ActionMailer, in config/environments/production.rb:

I am using Sendgrid SMTP API so:

config.action_mailer.delivery_method = :smtp

If you have sendmail installed on the production server:

config.action_mailer.delivery_method = :sendmail

4. In production.rb:
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true

How to install pdftk on Mac OS

You can download the installer from https://www.pdflabs.com/tools/pdftk-server/

After installation, open a new terminal and check installation:

$ pdftk --version

pdftk 2.02 a Handy Tool for Manipulating PDF Documents
Copyright (c) 2003-13 Steward and Lee, LLC - Please Visit: www.pdftk.com
This is free software; see the source code for copying conditions. There is
NO warranty, not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$

Wednesday, August 20, 2014

How to create .ruby-version and .ruby-gemset in RVM

rvm --create --ruby-version use ruby-2.1.2@r42
Reference: Create .ruby-version and .ruby-gemset

How to install latest version of Rails

gem install rails --version=4.2.0.beta1

How to check if ElasticSearch is running

By default elastic search runs on port 9200.

$ curl http://localhost:9200
{
  "ok" : true,
  "status" : 200,
  "name" : "White Pilgrim",
  "version" : {
    "number" : "0.90.13",
    "build_hash" : "249c9c5e06765c9e929e92b1d235e1ba4dc679fa",
    "build_timestamp" : "2014-03-25T15:27:12Z",
    "build_snapshot" : false,
    "lucene_version" : "4.6"
  },
  "tagline" : "You Know, for Search"
}

1. gem install rest-client

require 'rest-client'
RestClient.get('http://localhost:9200')


$ irb
> require 'rest-client'
 => true
> x = RestClient.get('http://localhost:9200')
 => "{\n  \"ok\" : true,\n  \"status\" : 200,\n  \"name\" : \"White Pilgrim\",\n  \"version\" : {\n    \"number\" : \"0.90.13\",\n    \"build_hash\" : \"249c9c5e06765c9e929e92b1d235e1ba4dc679fa\",\n    \"build_timestamp\" : \"2014-03-25T15:27:12Z\",\n    \"build_snapshot\" : false,\n    \"lucene_version\" : \"4.6\"\n  },\n  \"tagline\" : \"You Know, for Search\"\n}\n"
> x['ok']
 => "ok"
> JSON.parse(x)
 => {"ok"=>true, "status"=>200, "name"=>"White Pilgrim", "version"=>{"number"=>"0.90.13", "build_hash"=>"249c9c5e06765c9e929e92b1d235e1ba4dc679fa", "build_timestamp"=>"2014-03-25T15:27:12Z", "build_snapshot"=>false, "lucene_version"=>"4.6"}, "tagline"=>"You Know, for Search"}

Tuesday, August 19, 2014

How to configure the secret_key_base in Rails 4.1

1. Define an environment variable in .bashrc or .profile on the server:

export SECRET_KEY_BASE='a long string generated by running rake secret'

2. In secrets.yml file :
secret_key_base=<%= ENV['SECRET_KEY_BASE'] %>

3. MyBlog::Application.config.secret_key_base = Rails.application.secrets.secret_key_base

Remember: After deployment all the old sessions will become invalid.

Monday, August 18, 2014

How to add lib directory to the load path in Rails 4.1

   Uncomment the line :  config.autoload_paths += %W(#{config.root}/lib) in application.rb

Thursday, August 07, 2014

Installing Redis on Mac

~ $brew install redis
==> Downloading https://downloads.sf.net/project/machomebrew/Bottles/redis-2.8.9.mavericks.bottle.tar.gz
######################################################################## 100.0%
==> Pouring redis-2.8.9.mavericks.bottle.tar.gz
==> Caveats
To have launchd start redis at login:
    ln -sfv /usr/local/opt/redis/*.plist ~/Library/LaunchAgents
Then to load redis now:
    launchctl load ~/Library/LaunchAgents/homebrew.mxcl.redis.plist
Or, if you don't want/need launchctl, you can just run:
    redis-server /usr/local/etc/redis.conf
==> Summary
 /usr/local/Cellar/redis/2.8.9: 10 files, 1.3M

Wednesday, July 30, 2014

Saturday, July 26, 2014

Installing a specific version of elastic search


brew search elasticsearch

$ brew install homebrew/versions/elasticsearch090
Cloning into '/usr/local/Library/Taps/homebrew/homebrew-versions'...
remote: Reusing existing pack: 2230, done.
remote: Total 2230 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (2230/2230), 714.24 KiB | 12.00 KiB/s, done.
Resolving deltas: 100% (1260/1260), done.
Checking connectivity... done.
Tapped 149 formulae
==> Downloading https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-0.90.13.tar.gz
######################################################################## 100.0%
==> Caveats
Data:    /usr/local/var/elasticsearch/elasticsearch_bparanj/
Logs:    /usr/local/var/log/elasticsearch/elasticsearch_bparanj.log
Plugins: /usr/local/var/lib/elasticsearch/plugins/

To have launchd start elasticsearch090 at login:
    ln -sfv /usr/local/opt/elasticsearch090/*.plist ~/Library/LaunchAgents
Then to load elasticsearch090 now:
    launchctl load ~/Library/LaunchAgents/homebrew.mxcl.elasticsearch090.plist
Or, if you don't want/need launchctl, you can just run:
    elasticsearch --config=/usr/local/opt/elasticsearch/config/elasticsearch.yml
==> Summary
🍺  /usr/local/Cellar/elasticsearch090/0.90.13: 31 files, 19M, built in 6.8 minutes

Thursday, July 24, 2014

Installing Javascript Runtime

1. Uninstalled manually installed nodejs on Ubuntu 12.04. Since my server is managed by Moonshine. Manual installation is a bad idea.

sudo apt-get remove nodejs 

2. Add :

gem 'execjs'
gem 'therubyracer'
to the Gemfile

3. Bundle and deploy.

Installing ElasticSearch using brew

$ brew install elasticsearch
Error: elasticsearch-0.90.9 already installed
To install this version, first `brew unlink elasticsearch'
$ brew unlink elasticsearch
Unlinking /usr/local/Cellar/elasticsearch/0.90.9... 3 symlinks removed
$ brew install elasticsearch
==> Downloading https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.2.1.tar.gz
######################################################################## 100.0%
==> Caveats
Data:    /usr/local/var/elasticsearch/elasticsearch_bparanj/
Logs:    /usr/local/var/log/elasticsearch/elasticsearch_bparanj.log
Plugins: /usr/local/var/lib/elasticsearch/plugins/

ElasticSearch requires Java 7; you will need to install an appropriate JDK.

To reload elasticsearch after an upgrade:
    launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.elasticsearch.plist
    launchctl load ~/Library/LaunchAgents/homebrew.mxcl.elasticsearch.plist
==> Summary
🍺  /usr/local/Cellar/elasticsearch/1.2.1: 31 files, 21M, built in 5.6 minutes

Tuesday, July 22, 2014

Missing `secret_key_base` for 'production' environment, set this value in `config/secrets.yml`

1. Specify the secret_key_base by using figaro gem. Search on this blog for how to do that.

Installing Phusion Passenger 4.0.45 using Moonshine in Ubuntu 12.04

1. Login to phusion passenger account.
2. Download the license
3. Move the license file to vendor/plugins/moonshine/lib/moonshine/manifest/rails/templates file. The name of the file is the same as the downloaded file name which is passenger-enterprise-license
4. Add the following to the moonshine.yml file:

:passenger:
  :max_pool_size: 3
  :version: 4.0.45 # This is 2 versions behind because according to the moonshine source code, this is the blessed version.
  :enterprise: true
  :download_token: copy-your-download-token-from-passenger-account-here
  :rolling_restarts: true
   
5. Check in the code to bitbucket and do :
   cap deploy

No such file to load -- shadow puppet (LoadError) moonshine error

Copy the following lines to application.rb file.

    # don't attempt to auto-require the moonshine manifests into the rails env
    config.paths['app/manifests'] = 'app/manifests'
    config.paths['app/manifests'].skip_eager_load!

Installing NodeJS using Moonshine Plugin

1. plugger install git://github.com/iros/moonshine_nodejs.git
2. Add
recipe :nodejs
 
to the application_manifest.rb 
 
This will fail gloriously. 
 
Install it by:
 
apt-get install python-software-properties
apt-add-repository ppa:chris-lea/node.js
apt-get update
apt-get install nodejs
node -v
 
should show : v0.10.20
 
Reference : NodeJS installation on Ubuntu 12.04     

How to display flash messages using Twitter Bootstrap 3 in Rails 4.1

1. Copy the following helper method to app/helpers/application_helper.rb

  def bootstrap_class_for(flash_type)
    case flash_type
    when "success"
      "alert-success"   # Green
    when "error"
      "alert-danger"    # Red
    when "alert"
      "alert-warning"   # Yellow
    when "notice"
      "alert-info"      # Blue
    else
      flash_type.to_s
    end
  end

2. Create a shared folder in app/views

3. Copy the following code to app/views/_flash_messages.html.erb

<% flash.each do |type, message| %>
 

   
    <%= message %>
 

<% end %>

4. In your layout, add the line :         <%= render '/shared/flash_messages' %>
   above the yield call.

5. Set the flash messages in any of your controllers and you will see the flash messages displayed.

Reference : Stolen from gist.

Final Cut Pro 10.1.2 Crash Course in 10 Minutes

Recording Voice Over

Step 1 : Detach the audio from the video

1. Select the clip from the timeline window.
2. Go to Clip --> Detach audio
3. Select the audio and click delete.

Step 2 : Record Voice Over

1. Click the timeline where you want to start recording the voice over.
2. Go to window, Record Voice Over.
3. Click Record
4. Click the red button to stop recording.

If you make a mistake select the audio track in TL and delete.

Speeding up the Video

1. Select Blade from the dropdown.
2. Select the start and end of the video by using the blade.
3. Modify --> Retime --> 4x
4. Go back to the drop down and select the pointer.

Note : Select before you change the timing so that the rest of the video is unaffected.

Deleting Part of the Clip

1. Select the blade from the drop down.
2. Pick the starting and the end point of the clip
3. Select the pointer from the drop down.
4. Select the clip to reject and click delete.

Audio Enhancement

1. Select the audio
2. Modify --> Auto Enhance Audio
3. Right window, click on Audio Enhancements for any problems

Noise Reduction

1. Select the audio clip
2. Click the wizard inspector
3. Select audio enhancements
4. Background noise removal and hum removal to remove noise

Refer Enhance Audio section in the Help window of FCP.

Preroll

1. Import both videos
2. Drop the title video into the TL and then the video to be processed.

Exporting the Edited Video

1. File --> Share --> Master File

This will export the video in quick-time format.



Recovering from Mistakes

Undo : Command+Z

Thursday, July 17, 2014

Using Figoro Gem with Moonshine

1. Add gem 'figaro' to Gemfile

2. rails g figaro:install

Creates config/application.yml and adds it to .gitignore.

3. Here is the syntax for environment specific configuration

# config/application.yml

pusher_app_id: "2954"
pusher_key: "7381a978f7dd7f9a1117"
pusher_secret: "abdc3b896a0ffb85d373"
google_analytics_key: "UA-35722661-5"

test:
  pusher_app_id: "5112"
  pusher_key: "ad69caf9a44dcac1fb28"
  pusher_secret: "83ca7aa160fedaf3b350"
test:
  google_analytics_key: ~
 
4. Use rake secret to generate a secret for any of your keys

5. Access the values in the code:

 ENV['pusher_secret']

 or

 Figaro.env.pusher_secret

6. Specify required keys in config/initializers/figaro.rb

Figaro.require("pusher_app_id", "pusher_key", "pusher_secret")

7. Add config/application.yml to local directive in Moonshine. Edit moonshine.yml :shared_config: directive.

8. Deploy the application



Monday, July 14, 2014

How to create .ruby-version and .ruby-gemset in a Rails 4.1 project

$rvm use ruby-2.1.2
Using /Users/bparanj/.rvm/gems/ruby-2.1.2
~/projects/openbay $rvm gemset use openbay
Using ruby-2.1.2 with gemset openbay
$cat .ruby-version
cat: .ruby-version: No such file or directory
$rvm --ruby-version use 2.1.2
Using /Users/bparanj/.rvm/gems/ruby-2.1.2
$rvm --ruby-version use 2.1.2@openbay
Using /Users/bparanj/.rvm/gems/ruby-2.1.2 with gemset openbay
.ruby-version is not empty, moving aside to preserve.
~/projects/openbay $cat .ruby-version
ruby-2.1.2
$cat .ruby-gemset
openbay

Thursday, July 10, 2014

How to get controller and action name in Rails helper method

In Rails 4 :

    params[:controller]
   
    params[:action]






will give you the name of the controller and the name of the action respectively.

Ternary Operator in Ruby

(Some condition) ? true-case-value : false-case-value

Wednesday, July 09, 2014

How to update all packages in Ubuntu 12.04

If you are logged in as root:

$ apt get-update
$ apt get-update dist-upgrade

otherwise run them as sudo.

$ reboot

This will make the changes to be picked up.

Reference:

How to update all packages in Ubuntu 12

Tuesday, July 08, 2014

rvm rvmrc to [.]ruby-version

WTF? What do we need to do to get rid of this BS? From the root of your Rails project, run:

$ rvm rvmrc to .ruby-version

Thursday, June 26, 2014

How to use Ruby 2.1 as the default Ruby in Textmate

1. $ rvm get head
2. $ which rvm-auto-ruby | pbcopy
3. Go to Textmate preferences and Variables tab, add a new variable by clicking the + button. The name of the variable is TM_RUBY and copy the path to the ruby from step 2 as the value.

Wednesday, June 25, 2014

Why using Interactor Gem is a Very Bad Idea

Using interactor gem is a horrible idea. Here are the reasons:

1. It results in anemic classes, classes that don't have any behavior.

Their only purpose is to organize. You can organize using a DSL, something like rspec syntax: organize "Use Case" { specify the sequence of actions to take }. This does not have to be a class, the DSL is just a way wire different classes together.

2. The hash that gets passed around is nothing but a glorified global variable.

If you apply Domain Driven Design, you will use application specific data types instead of built-in data structures. This makes the concepts of your domain explicit. You can achieve 'Ubiquitous Language' in your team.

3. This results in "Hash Oriented Programming" not OO.

4. Failures are silent, which means there is no clear transparency into the system.

5. Class names are verbs. Are you kidding me? Why do you want to ignore the basics of good OO design?

What is the alternative then? Learn about Hexagonal Architecture and Domain Driven Design. Apply those principles religiously. When you apply these good design principles, your use cases become the core of your application which is not dependent on any technology. They become testable and compose able. It's like legos that gives you basic building blocks that can be combined in different ways to be used in different external and internal adapters.





Creating Paper Prototype to Design a Web Page

If you are getting lost in details and overwhelmed by the amount of data you have to deal with, this post will bring some sanity to your webpage design process.

Tools Required

Wall pads, scissors, colored pens, tape

What to Do

1. Buy a Post-it-Self-Stick-Wall-Pads from any office supply store.
2. Get all of your notes and lay them out into the big ass paper.
3. Arrange and categorize the notes into sections.

Structure

Focus on structure and copy existing design of a website that you like. In this phase you only worry about where different elements go in the layout. For instance, where does the screenshot of a feature go? Where does the headline and paragraphs go?

You can take screenshots of a website that you like and use Skitch to label different elements on the page. These labels could be just numbers. You can also blur or strike-out elements you don't want in your design in this phase.

You have to let your structure evolve over time by letting it marinate. Post it on the wall where you can look at it everyday and make quick corrections using red pen, using small sticky notes and pasting over the existing structure to note down some notes for yourself. Things does not have to be perfect the first time. The draft version can be approximate. It will be refined by revising it over a period of one to two weeks.

Content

Write down the content is smaller size paper and you can start pasting them over the existing structure.

Form

In this phase you focus on the font color, font size, font style, background grid colors etc. You make it more real.

Conclusion

This allows you to reduce confusion and clarify ideas before you can handover your design to a graphic designer. You can get a PSD file and hand it over to a front-end developer to create the HTML and CSS for the web page.

Saturday, June 21, 2014

Godel : Consistency or Complete

Less software as a design technique, not a goal. Thinking about decisions as potential energy vs kinetic energy. Decisions take energy and creates stress. It uses mental processing power.

Defer decision as much as possible

1. Estimating work.
2. Pure development time vs Fighting fires
3. Premature speculation (promises)
4. Requirement vs Schecule (out of sync)
5. Not planning for change.

Wednesday, June 11, 2014

Hello Docker 1.0

1. Download boot2docker osx-installer
2. Install it.
3. Check version
     $ docker -v
     Docker version 1.0.0, build 63fe64c
4. Upgrade VM and start docker
$ boot2docker stop
$ boot2docker download
$ boot2docker start

  $ docker run ubuntu echo hello world

 Unable to find image 'ubuntu' locally
 Pulling repository ubuntu
 ad892dd21d60: Download complete
 511136ea3c5a: Download complete
 e465fff03bce: Download complete
 23f361102fae: Download complete
 9db365ecbcbb: Download complete
 hello world

 $ docker run ubuntu echo hello world
  hello world

Sunday, June 08, 2014

Ruby Science Code Review

This article is a discussion of the chapter on Replace Conditional with Null Object. Null object does not solve any problems in most cases. For instance here is the sample code from the book:

if user.nil?
  nil
else
  user.name
end

If I cannot use Null Object (which creates unnecessary small objects). What is the right way to fix this? You need to apply the basics of Object Oriented Programming.  Ask yourself:


  • What does it mean to have a user variable with nil value?
  • If user does not exist in our system what do you want to display instead of their name? 
  • Is blank value acceptable in this case?


 If the above code snippet is part of a method, then the precondition for the method is that user object cannot be nil. It is a contract between the client and the API. As l long as I provide a valid user the method will be able to do it's job (fulfill the contract in Design by Contract terminology) and provide me the name. It's the responsibility of the client code to provide the method a valid user. In this case the solution would be:

Client Code

if user.nil?
  'User not found'
else
   user_name_for(user)
end

API

def user_name_for(user)
  user.name
end

Ideally I would look for the ActiveRecord call that throws an exception instead of returning nil for a record that is not found. I would handle the ActiveRecord::NotFound exception and translate it to business specific exception like MyApp::UserNotFound class that takes the message indicating the context of the application as the exception message. So there would be no nil check required in this case.

Sunday, June 01, 2014

Ruby Science Book Notes

Code Reviews

1. Use git diff and --patch to examine code before commit.
2. Push your feature branch and invite your teammates to review the changes via git diff origin/master..HEAD
3. Share your best refactoring ideas with them.
4. Refactor for readability first.

Metrics

1. Flog : Detect complexity

Example :
$ flog app lib

flog score of 10 or higher : Method may be too long
A class with a flog score of 50 is a large class that might need refactoring.

$ flog -a app/models/question.rb

2. Flay : Find duplication
3. Reek : Find bad code
4. Churn : Find files with high churn rate
5. MetricFu : Analyze application

Take a look at Code Climate.


Tuesday, May 27, 2014

Upgrading Ruby to 2.1.2 with Moonshine

I was able to upgrade Ruby to 2.1.2. Since I am using Rails 3, I upgraded Moonshine by running:

script/rails plugin install git://github.com/railsmachine/moonshine.git --force

I did not run 
 
script/rails generate moonshine

I am retaining the old generated files.

WARNING: Nokogiri was built against LibXML version 2.8.0, but has dynamically loaded 2.7.6

I had to run: 

sudo gem install nokogiri --   --with-xml2-include=/usr/include/libxml2   --with-xml2-lib=/usr/lib   --with-xslt-include=/usr/include/libxslt   --with-xslt-lib=/usr/lib
 
on the server from the directory:
 
/usr/lib/ruby/gems/2.1.0/gems
 
Note: This server is managed by Moonshine. I could not get rid of this warning any other way.
 
Reference:
 
How to fix Nokogiri on Ubuntu 

Getting mate command to work on Mavericks

After trying different suggestions from superuser.com on how to setup the shortcut, I had to define an alias in ~/.bash_profile as a workaround:
alias mate='/Applications/TextMate.app/Contents/Resources/mate '

Monday, May 26, 2014

Migrating from Github to Bitbucket

1. git remote show origin or git config --get remote.origin.url
2. git remote add origin ssh://git@bitbucket.org/your-user-id/your-project.git
3. Add the ssh key of the server to bitbucket SSH keys.
4. Login to the server and from the rails project current directory change the git remote by running the command in step 2.

Since I am using Moonshine, I had to delete the cached-copy folder on the server. Because it points to github and creates problem when cap deploy is run.

Monday, April 21, 2014

Essential Skills for TDD Terminology

Domain

A specified sphere of activity or knowledge. Example : Visual communication is the domain of the graphic designers.

Visual Communication
 - Contour
 - Contrast
 - Opacity
 - Form

Finance
 - Equity
 - Debt
 - Gross Margin
 - Net Income

Math
 - Parallel
 - Ordinate
 - Arc
 - Angle

Problem Domain

Problem domain refers to real-world things and concepts related to the problem.

Problem Domain Analysis

Problem Domain Analysis is the process of creating a mental model that describes the problem. The focus is on understanding the problem domain.

Solution Domain 

Solution Domain refers to real-world things and concepts related to the solution.

Solution Domain Analysis

Solution Domain Analysis is the process of arriving at a solution. It describes the sequence of steps used to solve a given problem. Finding abstractions helps us to solve problems.

Tuesday, April 08, 2014

Destroy All Software - Episode Fast Tests With and Without Rails Review

The specs in the final solution abuses mock by mocking the ActiveRecord API. The expectation mocks update_attributes. He says the solution only depends on RSpec and specs run outside of Rails, so the specs run fast. The problem is that the dependency on Rails exists because of the coupling created by the mocking of ActiveRecord. The tests are now brittle and can break when you upgrade Rails if the active record API changes.

Monday, April 07, 2014

Growing a Test Suite Screencast Review

This is the review of the solution discussed in Growing a Test Suite Screencast.

Here is a list of things that the solution violates:

1. Separate Command from Query.
     digest method is a command. digest method should not return any value
2. Allocate responsibilities to the right class.
    digest method does not belong to the Cheese class.
3. Law of Demeter.

Here is my solution:

class Walrus
  attr_reader :energy
 
  def initialize
    @energy = 0
  end
 
  def eat(food)
    digest
    @energy += food.energy
  end
 
  private
 
  def digest
    p 'Digesting...'
  end
end

class Cheese
  def energy
    100
  end
end


cheese = Cheese.new
w  = Walrus.new

p "Energy before eating is : #{w.energy}"

w.eat(cheese)

p "Energy now is : #{w.energy}"

Friday, March 28, 2014

Checking if a number is prime in Ruby

Go to irb :

 > require 'prime'
 => true
 > Prime.prime?(2)
 => true
 > Prime.prime?(3)
 => true
 > Prime.prime?(10)
 => false

Wednesday, March 26, 2014

Configuring Guard to Display output in Red Green Colors

Change the Guard file guard method to:

guard :rspec, cmd: 'rspec --color --format doc' do
... contents unchanged

end

From the root of the project run: guard
You will now see the colors in the terminal whenever the test is run.

Friday, March 21, 2014

Alternative to using take and drop methods in Array class

The take method takes elements from the beginning whereas the drop takes the elements from the end of the array. These methods require some mental mapping of the method names to what it does. I was thinking about reducing this gap. Here is the experiment in the IRB:

2.0.0 > a = [1,2,3,4]
 => [1, 2, 3, 4]
2.0.0 > a.first(2)
 => [1, 2]
2.0.0 > a
 => [1, 2, 3, 4]
2.0.0 > a.last(2)
 => [3, 4]
2.0.0 > a
 => [1, 2, 3, 4]

It just works! This is one of the reason why I love Ruby.

Monday, March 17, 2014

How to count number of files in a bucket in S3 recursively

1. git clone https://github.com/s3tools/s3cmd
2. cd s3cmd
3. s3cmd --configure
Enter the Amazon credentials.
4. ./s3cmd ls --recursive s3://your-bucket/another-bucket/foo

This will recursively find all the folders under foo and list all the files.

5. You can pipe it to wc to get the number of files like this :
     ./s3cmd ls --recursive s3://your-bucket/another-bucket/foo | wc -l

   

Loading rubyzip gem in irb

LoadError: cannot load such file -- rubyzip

Instead of : require 'rubyzip' use require 'zip'

Turn off Bonjour Notifications in Cyberduck


On Mac OS, run the following command in a terminal:

defaults write ch.sudo.cyberduck rendezvous.enable false

Reference:

Diable Bonjour in Cyberduck

Using MIME types outside of Rails 4

In a IRB session:

require 'action_dispatch/http/mime_type.rb'
 => true
> MIME::Types.type_for('a.pdf')

Thursday, February 20, 2014

SimpleDelegator in Ruby

require 'delegate'

class User
  def born_on
    'July 21'
  end
end

class UserDecorator < SimpleDelegator
  def birth_year
    born_on
  end
end

decorated_user = UserDecorator.new(User.new)
p decorated_user.birth_year  #=> July 21

Friday, February 14, 2014

psych.rb in `parse': found a tab character that violate intendation while scanning a plain scalar at

You will not be able to go the rails console. Go to the root directory of the rails project and fire up an irb session:

1. require 'yaml'
2. YAML::ENGINE.yamler = 'psych'
3. YAML.load_file('config/your-config-file.yml')

Autocorrect yaml file syntax errors: s.gsub!(/\t/, ' ')

This will reproduce the problem. See the line number of row to find the syntax error. Fix it by changing the tab to space.

Wednesday, January 15, 2014

RVM is not a function, selecting rubies with 'rvm use ...' will not work.

To fix this in Ubuntu 12.04, go to : Profile --> Preferences, Title and Command tab and check the box for 'Run command as a login shell'

Installing RVM on Ubuntu 12.04

1. sudo apt-get install curl
2. \curl -L https://get.rvm.io | bash -s stable
3. source ~/.rvm/scripts/rvm

Do not run OS updates in parallel when installing RVM.



Reference:
Install Ruby on Rails on Ubuntu 12.04

how to setup Textmate 2 to run mate from command line

Go to preferences --> Terminal and click 'Install' to install shell support.

If you get the error 'To open a bundled gem, set $EDITOR or $BUNDLER_EDITOR'
Add the following line to ~/.bash_profile:

export BUNDLER_EDITOR=mate

Tuesday, January 14, 2014

Setup Textmate 2 to use RVM

1. $ which rvm-auto-ruby
2. Add the following to ~/.tm_properties

TM_RUBY="/path/to/rvm-auto-ruby/from/step1/"

3. Restart Textmate 2
4. Run : puts RUBY_VERSION as a ruby file.

Monday, December 16, 2013

Ruby on Rails - Enterprise Application Development Notes

Business Processes

In building small business apps, a developer is endeavoring to model or support a business process.

To realize the maximum potential for small business application development, the developer needs to take on the role of analyzing the business process.

To keep up a supply of new work, the developer needs to identify potential new projects and development opportunities.

The key skill to being able to identify opportunities for new apps is an understanding of how businesses work. Study business processes.

Take courses on business management and management accounts. Checkout SBIC library and other libraries. It helps you to identify the best opportunities to improve business processes.

To be successful, build successful business apps. A business application is successful when an application generates a profit. Demonstrate that you can increase their profits. How do small applications generate profit? There are three ways to generate more profit within a business.

1. Increase sales by either increasing the number of sales or increasing the revenue from each sale (or less easily, both)
2. Reduce what it costs you to sell.
3. Spend as little as you can on the parts of the business that generate the least profit and minimize any resources given over to loss making activities.

Business apps can address all of these profit opportunities. Most businesses try to increase profits by increasing sales. It is usually far easier to increase profits by reducing costs and minimizing the time spent on loss making activities. It is in these areas that most opportunities for small business apps arise.

Here is some areas where opportunities for small applications arise:

1. Automate Simple Repetitive Jobs

A simple way to reduce costs is to reduce the time it takes to carry out repetitive tasks. Ex: CFO was spending 4 hours running reports. I created an application which generated the report in 5 minutes. That single simple application has saved 100s of hours of work, thereby freeing up the CFO to do more revenue generating work.

2. Rapid and Detailed Reporting

Actively go out and identify the opportunities that can be found within any business. Develop the skills to identify the opportunities for new apps. To do that successfully and repeatedly, you must learn to identify business processes that can be simplified, made more effective and efficient via a small app.

Friday, December 13, 2013

Cucumber Features


http://wiki.github.com/dchelimsky/rspec/rails

Feature: CSR account management
 In order to manage dispute calls
 As a CSR
 I want to create an account to login to the system

 Scenario: Successful account creation
     Given a login with "csr@somedomain.com" and password "secret"
     And login is the same as email address
     When I provide my login and desired password
     Then I should receive an account activation email at "csr@somedomain.com"

 Scenario: Successful account activation
   Given a valid activation link "http://www.somedomain.com/activation-string-for-csr"
   When I follow the activation link
   Then my account should be activated
   And I should be able to login using the login credentials provided during registration
 
 Scenario: Successful login
   Given a valid user name "csr@somedomain.com" and password "secret"
   When I provide my login credentials
   Then I should be logged in to my account with CSR role
   And I should be able to add additional users with CSR role

 Scenario: Forgot password
   Given a valid user name "csr@somedomain.com"
   And I follow forgot password link
   When I provide my email that I used during account registration
   Then I should receive a link to reset my password
   And I should be redirected to password recovery instructions page

 Scenario: Reset Password
   Given a valid reset password link "csr@somedomain.com" for my account in the password reset email
   When I follow the reset password link
   Then I should be able to provide a new password and confirm password
   And I should be able to login with my new password
   And the system sends password reset confirmation link for security purpose

 Scenario: Change the login id for logging into the system  
     Given a valid login id "csr@somedomain.com"
     When I provide my new desired login id "csr@newdomain.com"
     Then I should be able to login using my new login id "csr@newdomain.com"

 Scenario: Add new CSR account
   Given a CSR is logged-in
   When I provide new account details with valid login "newbie@something.com", password "verysecret" and confirm password "verysecret"
   Then the system should send account activation email to the new csr's email address (login id)
 
 Scenario: Successful logout
   Given a valid user name "csr@somedomain.com" and password "secret"
   When I logout
   Then the system should log me out of the system
   And I should not be able to use the features available only to logged in users
 
 Scenario: Features only available to logged in users
   Given a user is logged in
   When I go to my dashboard
   Then I should be able to add new account, update my login id, search, forgot password and logout

 Scenario: Features not available to users who are not logged in
   Given a user is not logged in
   When they access the CSR application
   Then I should not be able to add new account, update login id, search and logout
   And I should be able to login and also use forgot password feature

 Scenario: Failed account creation
   Given a login with characters that is not in the whitelist
   When I provide my login (email address) and password
   Then I should not receive an account activation email
   And I should get an error message stating the password policy (8 to 40 characters in length with list of allowed characters)
   And the system prevents SQL inject attacks
 
 Scenario: Automatic login
   Given a valid login and the user enables remember me feature
   When I login
   Then I should be logged in automatically on subsequent visits to the site
 
 Scenario Outline: Failed Login
   Given the login id is "" and password is ""
   When I enter "" and ""
   Then the error message should be ""
 
 Scenarios: wrong login credentials
   | login         | password              | error                                         |
   | wrong email     | correct password | Email not found                            |
   | correct email | wrong password   | Wrong password                             |
   | wrong email     | wrong password   | Login and Password does not match  |
   

     

Saturday, December 07, 2013

Including lib directory in the path in Rails 4

1. Add the line:

config.autoload_paths += %W(#{config.root}/lib)

to application.rb

2. Add your class to lib folder.

Rails 4 will now load the classes in the lib folder.

Sunday, December 01, 2013

Syntax Highlighting for Rails

1. Add rouge and redcarpet gems to Gemfile.

gem 'rouge'

gem 'redcarpet'

2. Install rouge gem.

$ bundle

3. Create initializer in config/initializers/rouge.rb
require 'rouge/plugins/redcarpet'

class CustomHtml < Redcarpet::Render::HTML
  include Rouge::Plugins::Redcarpet # yep, that's it.
end

4.  Use the HTML class as a renderer in markdown method in app/helper/application_helper.rb:

def markdown(text)
  render_options = {
    filter_html:     true,
    hard_wrap:       true, 
    link_attributes: { rel: 'nofollow' }
  }
  renderer = CustomHtml.new(render_options)

  extensions = {
    autolink:           true,
    fenced_code_blocks: true,
    lax_spacing:        true,
    no_intra_emphasis:  true,
    strikethrough:      true,
    superscript:        true
  }
  Redcarpet::Markdown.new(renderer, extensions).render(text).html_safe
end

5.  For styling the output using Rouge built-in styles, create app/assets/stylesheets/rouge.css.erb with the following code:

<%= Rouge::Themes::ThankfulEyes.render(:scope => '.highlight') %>
or
<%= Rouge::Themes::Colorful.render(:scope => '.highlight') %>
or
<%= Rouge::Themes::Base16.render(:scope => '.highlight') %>

6. In your view app/views/articles/show.html.erb where you have markdown and code mixed, use the markdown helper:
 
  <%= markdown @article.content %>

References
2. You can even use it with RedCarpet

Taking Passion to the Bank

Passion

Develop Web Applications that can become successful SaaS business.

Skill

Learn Full Stack Web Development using Rails.
Has a proven teaching system based on successful teaching methods.

Problem

Developers want to become Full Stack Rails Developer but are not able to learn quickly from existing resources.

Opportunity

Creates effective teaching material by making complicated concepts simple. Developers are able to master the material quickly.

Good businesses provide solutions to problems, in this case : 'How can I easily learn Web Application Development?'

Saturday, November 02, 2013

Focusing on a specific geographical location

To focus my Google Adwords campaign for promoting lead generator ebook, I found all the unique IPs for the downleads by doing (rails 3.2 webapp):

ips = Download.select('DISTINCT ips')

list = ips.collect(&:ip)

Paste the ip list as a single column on the  Convert IP to Country website. Very interesting fact:

50% of the downloads is from USA. So it is better to follow the Google Ad support person's advice of targeting to one or two geographical locations.

Monday, October 28, 2013

Source code formatter for Blogspot

Very useful source code formatter for blogspot

Rails Best Practices

1. gem install rails_best_practices
2. gem install ripper
3. From the root of the project run: 
rails_best_practices -f html .
to generate the report.

Invalid command 'SSLEngine', perhaps misspelled or defined by a module not included in the server configuration

This error is caused if mod_ssl is not installed. On Cent OS : sudo yum install mod_ssl

Imperative Vs Declarative Programming

Imperative Programming

Imperative programming is the oldest programming paradigm. It is based on the Von Neumann-Eckley model of a computer. Programs written in imperative programming languages consist of a program state and instructions that change the program state through assignment statements. Program instructions are imperative in the sense of imperative verbs that express a command.

Examples of imperative languages are assembly, Fortran, Algol, Cobol, Java, C/C++. These languages specify a sequence of operations for the computer to execute.

Procedural abstraction and structured programming are its design techniques.

Imperative Program = Algorithms + Data Structures
-- Nicholas Wirth

Imperative Programming + Procedures = Procedural Programming

Procedural abstraction allows the programmer to be concerned mainly with the interface between the procedure and what it computes, ignoring the details of how the computation is accomplished. Abstraction allows us to think about 'what' is being done, not 'how' it is implemented. Imperative language constructs : assignment, conditionals, looping and data structures.

Flowchart can be used to model imperative programs. For example flowchart for computing Fibonacci numbers.

Declarative Programming

Functional languages and logic languages are declarative. Declarative languages such as SQL, Haskell, Prolog describe the solution space. They provide the knowledge required to get there. They don't describe the steps needed to get there.


Reference :  Presentation by Computer Science Assistant Professor Mary Ellen Weisskopf 

Thursday, October 24, 2013

Solving Problems in Software Development

As software developers we are in the business of solving problems. A problem can be described using multiple representations such as text, diagrams and equations. If you understand the relationship between different representations of a given problem, you will be able to translate one representation to the other. If you are dominant in one representation and when you are given a problem to solve in your weaker representation you can translate into your dominant representation and solve the problem.

1. Understand the Problem

   - What do you need to find?
   - What are the unknowns?
   - What information do you obtain from the problem?
   - What information, if any, is missing or not needed?

2. Devise a Plan

   - Look for a pattern
   - Make a table
   - Draw a diagram
   - Write an equation
   - Work backwards
   - Identify a subgoal
   - Examine related problems and determine if the same technique can be applied
   - Examine a special case of the problem to gain insight into the solution of the original problem.

3. Carry Out the Plan

   - Implement the strategies from the plan and perform the computations.
   - Check each step of the plan as you proceed.

4. Look Back

   - Determine whether there is another method of finding the solution
   - Determine if there are more general problems for which the techniques will work.

References:

1. Billstein, Libeskind and Lott have adopted these problem solving steps in their book "A Problem Solving Approach to Mathematics for Elementary School Teachers (The Benjamin/Cummings Publishing Co.).
2. Technically Speaking: Making Complex Matters Simple by Steven Rudich

Polya's Problem Solving Technique

Polya's First Principle: Understand the problem

- Do you understand all the words used in stating the problem?
 - What are you asked to find or show?
- Can you restate the problem in your own words?
- Can you think of a picture or diagram that might help you understand the
problem?
- Is there enough information to enable you to find a solution?

Polya's Second Principle: Devise a plan

Polya mentions that there are many reasonable ways to solve problems. The skill at choosing an appropriate strategy is best learned by solving many problems. You will find choosing a strategy increasingly easy. Here is a partial list of strategies:

  - Draw a picture
  - Look for a pattern
  - Consider special cases  
  - Solve a simpler problem
 - Make an orderly list
  - Use a formula
  - Solve an equation
  - Guess and check
 - Eliminate possibilities
 - Use symmetry
  - Use a model
  - Work backwards
 - Use direct reasoning
 - Be ingenious

Polya's Third Principle: Carry out the plan

This step is usually easier than devising the plan. In general, all you need is care and patience, given that you have the necessary skills. Persist with the plan that you have chosen. If it continues not to work discard it and choose another. Don't be misled, this is how mathematics is done, even by professionals.

Polya's Fourth Principle: Look back

Polya mentions that much can be gained by taking the time to reflect and look back at what you have done, what worked, and what didn't. Doing this will enable you to predict what strategy to use to solve future problems.

Here is a summary of strategies for attacking problems in mathematics class. This is taken from the book, How To Solve It, by George Polya, 2nd ed., Princeton University Press, 1957, ISBN
0-691-08097-6.

1. UNDERSTAND THE PROBLEM

- First. You have to understand the problem.
- What is the unknown? What are the data? What is the condition?
- Is it possible to satisfy the condition? Is the condition sufficient to determine the unknown? Or is it insufficient? Or redundant? Or contradictory?
- Draw a figure. Introduce suitable notation.
- Separate the various parts of the condition. Can you write them down?

2. DEVISING A PLAN

- Second. Find the connection between the data and the unknown. You may be obliged to consider auxiliary problems if an immediate connection cannot be found. You should obtain eventually a plan of the solution.
- Have you seen it before? Or have you seen the same problem in a slightly different form?
- Do you know a related problem? Do you know a theorem that could be useful?
- Look at the unknown! Try to think of a familiar problem having the same or a similar unknown.
- Here is a problem related to yours and solved before. Could you use it? Could you use its result? Could you use its method? Should you introduce some auxiliary element in order to make its use possible?
- Could you restate the problem? Could you restate it still differently? Go back to definitions.
- If you cannot solve the proposed problem, try to solve first some related problem. Could you imagine a more accessible related problem? A more general problem? A more special problem? An analogous problem? Could you solve a part of the problem? Keep only a part of the condition, drop the other part; how far is the unknown then determined, how can it vary?
Could you derive something useful from the data? Could you think of
other data appropriate to determine the unknown? Could you change the
unknown or data, or both if necessary, so that the new unknown and the
new data are nearer to each other?
- Did you use all the data? Did you use the whole condition? Have you
taken into account all essential notions involved in the problem?

3. CARRYING OUT THE PLAN

- Third. Carry out your plan.
- Carrying out your plan of the solution, check each step. Can you see clearly
that the step is correct? Can you prove that it is correct?

4. LOOKING BACK

- Fourth. Examine the solution obtained.
- Can you check the result? Can you check the argument?
- Can you derive the solution differently? Can you see it at a glance?
- Can you use the result, or the method, for some other problem?


Reference : http://math.berkeley.edu/~gmelvin/polya.pdf

Saturday, October 19, 2013

What vs How in Test Driven Development

Example #1 for What vs How

Music sheet is not music. It is description of music. This is the 'What' or Logical Design.

Music is played using musical instruments. This is the 'How' or the Physical Design. There are many physical designs for a given logical design.

Example #2 for What vs How

John Lennon wrote the song Come Together. This is the 'What'. The examples of 'How' in this case are the performances of :

- Beatles
- Aerosmith
- Michael Jackson

to the same song Come Together.

Separate Logical Design from Physical Design 

How do you separate What from How in our code? Chris Stevenson's TestDox style expresses the subject in the code as part of a sentence.

- A Sheep eats grass
- A Sheep bleats when frightened
- A Sheep produces delicious milk
- A Sheep moves away from sheep dogs

This can be automatically converted to specifications in code :

describe Sheep do
  it 'eats grass'
  it 'bleats when frightened'
  it 'produces delicious milk'
  it 'moves away from sheep dogs'
end

When you think about the system from outside-in fashion you focus on intent. You focus on what you are doing rather than the implementation which is the 'how'.

References

1. Test Driven Development: Ten Years Later by Michael Feathers and Steve Freeman on

Fun Stuff

Search YouTube and watch the videos for Come Together performed by The Beatles, Michael Jackson, Aerosmith and Elton John

Test Driven Development Background


What is Test Driven Development?

You write a test first before you write the code. You use the tests to drive the design.

It uses one of the XP concepts : Test-First programming to achieve another XP concepts : Emergent Design.

In Emergent Design you start delivering functionality that has business value and let the design emerge. You will deliver functionality A with unit tests and then build functionality B. Then refactor to reduce duplication due to A and B and let the design emerge.

Origins of Test Driven Development

Extreme Programming Explained - Embrace Change by Kent Beck
Refactoring by Martin Fowler

Why TDD ?

- It results in simple design and minimal code.
- Higher quality code due to less defects
- Lower cost to maintain
- Brings fun back to programming

When is TDD not applicable?

- Multi-threading
- Asynchronous Code
- Prototyping
- Exploratory work such as Architectural spike
- Checking the structure of user interfaces such as HTML
- Testing usability of user interfaces

What makes TDD difficult

- Doing TDD without pair programming. TDD and pair programming are complementary.
- Existing code base with no tests

Wednesday, October 09, 2013

Flog Scoring


Score of    Means
0-10        Awesome
11-20       Good enough
21-40       Might need refactoring
41-60       Possible to justify
61-100      Danger
100-200     Whoop, whoop, whoop
200 +       Someone please think of the children