Saturday, December 24, 2011

[PostgreSQL][Mac] Modify root password (Forgot password)


  • sudo su postgres
  • supply your Mac password
  • modify /Library/PostgreSQL/9.x/data/pg_hba.conf
    • from local all all   md5
    • to local all all   trust
  • execute /Library/PostgreSQL/9.x/bin/pg_ctl restart -D /Library/PostgreSQL/9.x/data/
  • run psql
  • change postgres password
    • ALTER USER postgres WITH ENCRYPTED PASSWORD 'password';
  • modify pg_hba.conf back
  • restart again
Tested with PostgreSQL version 9.1 OSX Lion

Sunday, December 4, 2011

Learn some Ruby syntaxes from company source code

I think the fastest way to catch up Ruby and Rails idiomatic of my new company is to learn from it directly instead of learning from other available tutorials or books. Below is my note on this learning.

Rake

Exec shell command


  • use back-quote such as `ls`
  • return string from stdout
  • access Process object with $? such as $?.success
  • (not related to Ruby) `command 2>/dev/null` get rid of stderr

- string.chomp to remove new line in end of string

RSpec a lot of things on https://www.relishapp.com/rspec

Thursday, December 1, 2011

[MacOSX] How to modify enviroment.plist without any additional tools


  1. Convert enviroment.plist to XML format with plutil -convert xml1 environment.plist
  2. Edit it.
  3. Convert it back to binary format with plutil -convert binary1 environment.plist 

[RubyMine] invalid byte sequence in US-ASCII

I had this problem when I tried to bundle install. This causes from System Environment Variables which RubyMine is using is different from you shell and LANG is default to US-ASCII.

You can fix this (For 10.6+) by add LANG=en_US.UTF-8 to ~/.MacOSX/enviroment.plist

Please checkout How to modify enviroment.plist without any additional tools

Sunday, November 6, 2011

[VIM] Make newly created file(s) available for search with FuzzyFinder

Once your FuzzyFinder has loaded current files, if you create a new file, you have to tell it to reload it by execute:-

:FufRenewCache

Source: FuzzyFinder : buffer/file/command/tag/etc explorer with fuzzy matching
Thanks: @virasak

How to add helper method to Cucumber's World

Add this line to any files under features/supports/ directory
World({any_module_names})
Module's name here can be a predefined Rails's helper or your application helper or a new helper which is just created here.

Then you can access method inside the module in all of your Cucumber's step definitions.

Credit: #51 Integration Tests With Cucumber

Sunday, October 30, 2011

Upgrade Ruby version which is installed with RVM


  • Get latest Ruby version for RVM
    • rvm get latest
  • Find out current Ruby version
    • rvm current (the string between first '-' and '@')
  • Find out new Ruby version
    • rvm list known
  • Upgrade
    • rvm upgrade [current version] [new version]

Saturday, October 29, 2011

[Rails] Redirect to previous page

In controller, you can specify redirection to go back to previous page that call to this controller by using code below:
redirecto_to :back  
Note: Rails 3.1

[Rails] Route alias

You can execute "rake routes" to view display routes in your app.

The first column of output are route aliases which you can refer to in your app or test by append "_path" to that alias.

If you use resource in routes.rb, it will automatically generate CRUD routes and their alias for you.

But if you want to alias your other routes, you can do by append below after your routes
, :as => :{alias you want}
Note: Rails 3.1

Friday, October 28, 2011

[Heroku] Access Rails's model in migration, heroku rake db:migrate, uninitialized constant

I wanted to use Rails's migration to add new column to a table and fill this column with default value.
add_column :students, :student_id, :integer 
Student.all.each { |s| s.update_attributes!(:student_id => s.id+10000) }
I run this locally.
rake db:migrate
It worked without any problem.

Then I deployed to Heroku and run;
heroku rake db:migrate
I found this error.
 uninitialized constant AddStudentIdToStudents::Student
After googling for a while, I found this blog post Heroku Migration Fails to Update Attributes: reset_column_information

The way to solve this issue(don't know why) is to open up the class inside migration file like this;
class AddStudentIdToStudents < ActiveRecord::Migration
  class Student < ActiveRecord::Base; end
  def change
    add_column :students, :student_id, :integer
    Student.all.each { |s| s.update_attributes!(:student_id => s.id+10000) }
  end
end
This works for me.

Note: Rails 3.1.0 

Sunday, October 16, 2011

My Note from "The Intro to Rails Screencast I Wish I Had"

I found that The Intro to Rails Screencast I Wish I Had is very good in demostrating some tricks that make Rails different to other web development frameworks.

Below are notes from my 2nd time watching this screencast. What I note are things that I've never known before or I can't really remember the way to use it.

  • Add -T in rails new to prevent rails from generating Test::Unit
  • Gems
    • turn (Pretty printing for test results)
    • guard-rspec (Autotest)
    • growl_notify
    • rb-fsevent
    • launchy
      • save_and_open_page (use along with Capybara statements)
  • Guard
    • guard init rspec
    • guard (start guard)
  • RSpec integration test
    • rails g integration_test {name}
  • Routes
    • rake routes
    • resources (auto routes)
  • Capybara (route_name comes from first column of rake route)
    • visit {route_name}_path
    • page.should have_content {string}
    • fill_in {id/name/label}, :with => {string}
    • click_button {id/name/label}
    • current_path.should == {route_name}_path
    • find_field('').value
  • ActiveModel
    • {Model}.create {value}
    • {model_instance}.update_attributes {fields hash}
  • ERB
    • form_for {object} do | f |
    • f.label :{name}
    • f.text_field :{name}
    • f.submit
    • render '{partial view(No _)}'  <- partial view file name must prefix with _ 
    • flash.each do | name, message | (come from params passed with redirect_to)
  • Controller
    • render :text => params.inspect
    • redirect_to :back (previous page)
    • (redirect_to) {:notice | :alert} => {string} (will be available in flash)


Saturday, October 8, 2011

Make Rails accept Non-English Characters

Put following line to the first line of the page that contain Non-English characters
# encoding: utf-8

Saturday, September 17, 2011

Monday, September 12, 2011

Clean up CodeIgniter's database (ActiveRecord) memory usage

As what I have found when I was researching there are 2 ways:
  • Prevent ActiveRecord from saving query
by
$this->db->save_queries = false;
credit: how can I free the memory used by $this->db->insert()

  • Free result memory - CodeIgniter will only reclaim memory when http query processing was returned. If you request is long, you have to free by yourself
by
$query = $this->db->query('SELECT title FROM my_table');
$query->free_result();
credit: last section of Generating Query Results

Friday, September 9, 2011

Useful VIM command that I still can't remember



  • “0p - pastes the last explicitly copied text
  • :reg - Show a list of registers
  • J - Merge current line With Next Line
  • =, == - Fix indention
  • u,U(in visual mode) - lower, uppercase
  • q: - list command history
  • q/ - list search history
  • Ctrl ^ - go to previous buffer
  • :w !sudo tee % - save readonly file
  • diw - delete a word
  • di(, da( - delete text inside/include ()
  • di", da" - delete text inside/include ""
For rails.vim
  • gf - open file from cursor
  • :R{view,model,controller,spec} {file}

Thursday, August 18, 2011

Git - Global gitignore

Some types of temporary files are spanding across project, such as .swp (VIM temporary file type).

To put *.swp to every project's repositories makes duplicate job.

One way to solve this issue is to put it to Global gitignore.

From this blog Git global ignores, i will copy to here, also.

- Create .gitignore file at somewhere, mostly at ~/
git config --global core.excludesfile ~/.gitignore


- An pattern of file, you want to do global ignore in to that file.

That's it.

Tuesday, August 16, 2011

[VIM] Mostly use FuzzyFinder and NERDTree shortkeys

Basic VIM
- Open new horizontal split :sp file
- Open new vertical split :vs file
- Switch between split pane: Ctrl-w + { h|j|k|l }
- Rotate pane down/right: Ctrl-w + r
- For more, see Vim documentation: windows

FuzzyFinder
- Open in vertical split: Ctrl-k
- Open in horizontal split: Ctrl-j

NERDTree
- Open in vertical split: s

Friday, August 12, 2011

[Solved] autoscan: not found

If you are in process of compiling something on Ubuntu and you get error similar to these
./bootstrap.sh: 24: autoscan: not found

You have to install autoscan program but you can not find autoscan with
sudo aptitude search autoscan

The package name you have to install is autoconf. I don't know why because I'm not an expert on C/Linux but after below command, the compilation works.
sudo apt-get install autoconf

Monday, August 1, 2011

Create simple Ubuntu(Debian?) start up script

- Create a file at /etc/init.d/<filename>
#!/bin/bash

case "${1:-''}" in
'start')
# put the command to start
;;
'stop')
# stop command here
;;
'restart')
# restart command here
;;
*)
echo "Usage: $SELF start|stop|restart"
exit 1
;;
esac


sudo update-rc.d <filename> defaults


sudo /etc/init.d/<filename> <start|stop|restart>


- To remove
sudo rm /etc/rc*/*<filename>


Credit: Ivan in How do I make sphinx restart when I reboot my Ubuntu server?

Thursday, July 28, 2011

Enable remote access to MySQL

In MySQL config file, such as my.cnf
- comment out skip-networking
- add bind-address = YOUR_HOST_IP
- restart mysqld
- log in to mysql from server machine
- do GRANT ALL ON DATABASE.TABLE TO USERNAME@'HOST_IP/NAME' IDENTIFIED BY 'PASSWORD'; (Quote is required.)
- on client machine log in with > mysql -u USERNAME -r PASSWORD -h YOUR_HOST_IP

P.S. If there is no config file you can copy/rename from my-*.cnf in mysql directory

Credit: How Do I Enable Remote Access To MySQL Database Server?

Monday, July 25, 2011

More advance commands for moving cursor and screen in VI

These are VI commands I have just learned today

F = reverse of f
t = f and step back 1 char
T = reverse of t
; = repeat f, F, t and T

H = Move cursor to first line of the screen
M = Move cursor to middle of the screen
L = Move cursor to last line of the screen

z. || zz = Move screen to make cursor to middle of the screen
zt = Move screen to make cursor to top of the screen
zb = Move screen to make cursor to bottom of the screen

Ctrl+f = Scroll down 1 screen (Ctrl+d only half screen)
Ctrl+b = reverse of Ctrl+f

Ctrl+e = Move screen down 1 line with the cursor try to stay at the sameline
Ctrl+y = reverse of Ctrl+y

Thursday, July 14, 2011

How to install PHPUnit to Mac OSX

- Install PEAR
curl -O http://pear.php.net/go-pear.phar
php -d detect_unicode=0 go-pear.phar


- Install PHPUnit
sudo pear channel-discover pear.phpunit.de
sudo pear channel-discover pear.symfony-project.com
sudo pear channel-discover components.ez.no
sudo pear install --force --alldeps phpunit/PHPUnit


- Set phpunit bin path to System Environment Variables

Credit
Getting and installing the PEAR package manager
PHPUnit Installed on Mac OSX

Monday, July 11, 2011

[Solved] Ubuntu can not use webcam for video call, while Cheese is working properly

This post is not for people who is facing Linux webcam driver issue, it is for people who can get webcam working (with some application, such as Cheese) but webcam is not working for video calling like Skype or Google video call.

I also don't know the cause but for solution is to set this to environment variable before running video call application
LD_PRELOAD=/usr/lib/libv4l/v4l1compat.so


For convenient, you can rename the original application bin file to other name and making below script naming as bin file.

For example, I did rename my /usr/bin/google-chrome to /usr/bin/google-chrome.real and create a script at /usr/bin/google-chrome with below content
#!/bin/sh
LD_PRELOAD=/usr/lib/libv4l/v4l1compat.so /usr/bin/google-chrome.real


Now Gmail video call on my Google Chrome should work. (Skype also can do the same way)

Tested with Ubuntu 10.04 on 32-bits machine.
Credited to some forums in internet. Sorry for forgotten.

Tuesday, June 21, 2011

Thursday, February 24, 2011

[Git] Rebase

So far I have used git rebase for 3 scenarios.
  1. Want to add more change in the commit that is not the last commit of any branch. Use git rebase -i
  2. Want to move whole different branch to base on another branch.
          A---B---C topic
    /
    D---E---F---G master
    to
                  A'--B'--C' topic
    /
    D---E---F---G master
    git checkout <branch-to-move>
    git rebase <base-branch>
  3. Want to move part of different branch to base on another branch.
        o---o---o---o---o  master
    \
    o---o---o---o---o next
    \
    o---o---o topic
    to
    o---o---o---o---o  master
    | \
    | o'--o'--o' topic
    \
    o---o---o---o---o next
    git rebase --onto <new-base-branch> <old-base-branch> <move-branch>


Wednesday, February 23, 2011

[Git] delete/remove remote tag

To delete/remove remote branch in Git, you use
git push <remote*> :<branch-to-remove>

Also to delete/remove tag in remote server, you can use
git push <remote> :refs/tags/<tag-to-remote>

These commands might seem weird and hard to remember. To be able to remember them easier, I suggest you to see this full git push command
git push <remote> <local-branch-name>:<remote-branch-name>

Then to delete is to push empty branch to expected branch on remote. That's all why.


 *remote is an alias of other repository see git remote
Credit: How to: Delete a remote Git tag

==

Update
The current version of git now support argument --delete for push. So now you can delete branch hello from origin with this command
git push --delete origin hello

Wednesday, February 16, 2011

[Git] Ignore change of a file that is in an index

There is a command git update-index --assume-unchanged <file> for ignore.
And there is a command git update-index --no-assume-unchanged <file> for unignore.

For listing assume-unchanged files use git ls-files -v and see lower h in front of file name.
You can combine this with grep "h ". And you can also use git ls-files -v if you are interesting only a file.

[Git] partially add some changes in a file to index

- Use git add -i (<filename>)
- Select 5 (or p) then enter to see changes for selection.
- Choose files by type number in front of each file name and enter.
- Enter again to start.
- Type y or n to choose or not choose changes.
  Type s to divide changes to smaller sectioin.
  Type e to manually choose change.
- After back to main prompt choose 7 (or q) and enter to leave.

Tuesday, February 8, 2011

Ant OS specific value

<condition property="os.dep.value" value="value for MacOSX">
  <os family="mac" />
</condition>

<condition property="os.dep.value" value="value for Windows">
  <os family="windows" />
</condition>

<condition property="os.dep.value" value="value for Unix" >
  <os family="unix" />
</condition>

Use as "${os.dep.value}"

Creadit: Can I make the Ant copy task OS-specific? - Stack Overflow, How to make a conditional decision in an Ant build script based on operating system | java ant | devdaily.com

Wednesday, February 2, 2011

Generate current Git version in Ant for Hudson

At the time I wrote this blog there is no Git Ant task. Workaround for getting current commit version is to use exec directly invoke git describe as below.
<exec executable="git" outputproperty="build.commit">
    <arg value="describe"/>
    <arg value="--tags"/>
    <arg value="--abbrev=20"/>
</exec>

Now you can get result value of git describe from ${build.commit}.
Credit: How to lookup the latest git commit hash from an ant build script - Stack Overflow

But there is also some problems with Hudson's git plug-in which it always tags build revision that causes our git describe return the wrong result. There was someone send patch to fix this but this is not build to the plug-in yet. Currently workaround is provided in that patch page, add paramter to git describe, "--match=[^(hudson)]*", to ignore tag from Hudson. So we have to add more arg line to Ant's exec task:
<arg value="--match=[^(hudson)]*">

That's all.

Disable SSH host key checking

I summarized this from Linux Commando: How to disable SSH host key checking

He suggested 3 approaches
  1. $ sed -i 3d ~/.ssh/known_hosts
  2. Use parameters
    * StrictHostKeyCheckin
    * UserKnownHostsFile
    ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no username@hostname
  3. Config file ~/.ssh/config (or /etc/ssh/ssh_config for global) & restart ssh
    Host 192.168.0.*
    StrictHostKeyChecking no
    UserKnownHostsFile=/dev/null

Config number of file descriptors on Linux

Check file descriptor limit for a process. Vary depending on owner of the process $ cat /proc/{process-id}/limits Check current number of...