iOS Tutorials

After working on Android on a daily basis for almost 1 year, I started out my journey on iOS to discover the other major half of the mobile world. I followed a few different resources to help me understand different things on iOS dev, mainly Objective-C and the Xcode IDE. This blog post will include a list of tutorials I used and highlight what they are good for. This is to keep a note to myself of useful resources, and at the same time, I hope it will be useful to others too! 🙂

  • Official getting started guide
  • About Objective-C method and function
  • An Overview of Objective-C
    • Website: http://cocoadevcentral.com/d/learn_objectivec/
    • Remarks: Good overview of Objective-C. Also explains well on memory management. Objects creation can be confusing when you’re new to Objective-C. I saw 2 ways of making objects: “NSString* string1 = [NSString string];” and “NSString* string2 = [[NSString alloc] init];”. This guide will help you demystify it and learn more about memory management in Objective-C.

Some other guides I found but yet to finish:

That’s it for now, more to be added to this list as I study! bye!

 

Advertisements

Troubleshooting Postgres Error: Permission denied to create db

Today I tried to setup Postgres as my db for my Rails project, and met with this error:

Couldn't create database for {"adapter"=>"postgresql", "encoding"=>"unicode", "database"=>"my_cute_db", "pool"=>5, "username"=>"rongjun", "password"=>nil}
PG::Error: ERROR:  permission denied to create database

I want to write down how I solved it.

What I intended to do is the create a db called my_cute_db with rake command, rake db:setup. However, it’s giving error like shown above.

Here’s my database.yml

development:  
adapter: postgresql  
encoding: unicode  
database: my_cute_db  
pool: 5  
username: rongjun  
password:

My username is rongjun. And the error is telling me that “permission denied to create database“, so I have to go into psql command-line interface to find out the permission of my role.

my_terminal# psql postgres
postgres=# \du
                              List of roles
 Role name  |                   Attributes                   | Member of
------------+------------------------------------------------+-----------
 rongjun    |                                                | {}
 daodaowang | Create DB                                      | {}
 kai        | Password valid until infinity                  | {}
 tanjunrong | Superuser, Create role, Create DB, Replication | {}
 validator  |                                                | {}

\du command is listing down the role names and their privileges. We can see that rongjun is not having any privileges. On the other hand daodaowang is able to Create DB. Now we would like to enable rongjun to be able to Create DB just like daodaowang.

postgres=# ALTER ROLE rongjun WITH CREATEDB;

Then we run \du again to check:

postgres=# \du
                              List of roles
 Role name  |                   Attributes                   | Member of
------------+------------------------------------------------+-----------
 rongjun    | Create DB                                      | {}
 daodaowang | Create DB                                      | {}
 kai        | Password valid until infinity                  | {}
 tanjunrong | Superuser, Create role, Create DB, Replication | {}
 validator  |                                                | {}

rongjun is now having the correct privilege to Create DB. Let’s run rake db:create again, it will do the job without error now. You can check by running psql -l command to list down all databases you have.

After creating the db, you can grant more privileges to your user:

postgres=# GRANT ALL PRIVILEGES ON DATABASE my_cute_db to rongjun;

Reference:
For how to create database refer to: http://www.cyberciti.biz/faq/howto-add-postgresql-user-account/

For creating the user with ‘Create DB’ privilege directly without having to ALTER it later:

create user any_username with password 'any_password' createdb;

% notation in Ruby

Today I wanna share about the %notation I learned.

Any single non-alpha-numeric character can be used as the delimiter.

1.9.3-p327 :005 > %*lala lala "hehe"*
 => "lala lala \"hehe\""
1.9.3-p327 :006 > %&lala lala "hehe"&
 => "lala lala \"hehe\""

As you can see, * worked, & worked, so other symbol and friends will work too. Above example is using % notation to produce string, but % notation is actually more powerful than that, you can use it to produce array, regexp, shell command:


%Q{one\ntwo\n#{ 1 + 2 }}
=> "one\ntwo\n3"

%q{one\ntwo\n#{ 1 + 2 }}
=> "one\\ntwo\\n#{ 1 + 2 }"

%r/#{name}/i
=> /nemo/i

%w{one two three}
=> ["one", "two", "three"]

%i{one two three} # after Ruby 2.0
=> [:one, :two, :three]

%x{ruby --copyright}
=> "ruby - Copyright (C) 1993-2009 Yukihiro Matsumoto\n"

The post is not an exhaustive guide, but an introduction. Here’s where I copied the material from: http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Literals#The_.25_Notation

Take a tour to % notation through the link if you haven’t, it is definitely beneficial!

If you’re familiar with test, you can try the examples written in minitest:
https://github.com/teohm/a-dip-in-ruby/blob/master/spec/percent_notation_spec.rb

It’s from this blog post: http://teohm.github.io/blog/2012/10/15/start-using-ruby-percent-notation/

It’s a tiring day… It’s time to get some rest! Good night 🙂

Ruby’s alias_method

Today I learned about an interesting method in Ruby alias_method, this method can be used to refer to an old method in a module. The documentation is here: http://apidock.com/ruby/Module/alias_method. But at first glance, I couldn’t understand what it’s used for. So this simple post will illustrate a little.

Let’s say we have a module initially:

module Mod
  def print_asdf
    puts "lalalala"
  end
end

We can use it like this:

irb> include Mod
 => Object
irb> print_asdf
  lalalala

Later we decided to reopen the module and overwrite the function to add something:

module Mod
  def print_asdf
    print_asdf
    puts "changed"
  end
end

It’s just like calling the superclass method when we’re doing inheritance in OOP, but for this case we can’t use super.print_asdf, if we call the above method, we’ll run into error:

irb> include Mod
irb> print_asdf
SystemStackError: stack level too deep
   from /Users/tanjunrong/.rvm/rubies/ruby-1.9.3-p327/lib/ruby/1.9.1/irb/workspace.rb:80
Maybe IRB bug!

That’s because it’s running recursively! This can be solved by alias_method:

module Mod
  alias_method :hey, :print_asdf

  def print_asdf
    hey
    puts "hehe"
  end
end

Now we can use it properly:

irb> include Mod
irb> print_asdf
  lalalala
  hehe

Simple post. Bye!

Git Cherry Pick

Today, I learned about git cherry-pick. The man page of cherry-pick states that:

Given one existing commit, apply the change the patch introduces, and record a new commit that records it. This requires your working tree to be clean (no modifications from the HEAD commit).

One of the use case I know of is to take a commit from one branch, and apply it on another. Given this,

- a - b - c - d - e - f (master)
            \
              g - h - i (dev)

and if I do this:

git checkout dev
git cherry-pick [SHA-1 hash of commit f]

I will have this:

- a - b - c - d - e - f (master)
            \
              g - h - i - f"(dev)

Now I will have another commit f” with a different SHA-1 hash from commit f.


However, take note that there are consequences of cherry-picking. The history in commit d and commit e will be lost. Consider a simpler tree:

- a - b - c (master)
    \
      d (dev)

Referring to the simple tree above, let’s say we introduce cheese_cake_recipe.txt in commit b with the content:

get_recipe() {
  return "cheese + flour + lime juice"
}

and changes the content of cheese_cake_recipe.txt in commit c into:

get_recipe() {
  return "cheese + flour + milk"
}

later I cherry-pick it from the (dev) branch like this:

git checkout dev
git cherry-pick [SHA-1 hash of commit c]

now I have this:

- a - b - c (master)
    \
      d - c" (dev)

But in commit c”, the content of cheese_cake_recipe.txt will be:

get_recipe() {
  return "cheese + flour + milk"
}

And we never know that lime juice ever exist in the older recipe, now our cheesecake won’t taste as nice and we won’t be able to find out why easily.

So use with care… Here are 2 posts talking about this:

http://stackoverflow.com/questions/880957/pull-all-commits-from-a-branch-push-specified-commits-to-another/881014#881014

http://stackoverflow.com/questions/881092/how-to-merge-a-specific-commit-in-git/881112#881112

Continue a task using Thread after render has returned

As rails is an opinionated framework, it uses the MVC pattern. Whenever it receives a request, it will go through a controller and the controller will render a page to be returned.

def index
    render :action => :index
end

However, sometimes we have to run a longer task.

def index
    # some time consuming task
    render :action => :index
end

When we met with this situation, this browser will be in the loading-forever mode, and the server might even timeout the connection. One of the way to solve it is to render a view for the user first, telling them “your request is running at the background”, then we continue on our long process. So this is how it’s done:

def index
    Thread.new do
        # some time consuming task
    end
    render :action => :index
end

This way, the web app will spawn another thread for the long task, so the view will be returned to the user first, and the long task will still be executed at the background.

However, if the long running task is too heavy, we can use delayed_job or resque to queue up the job for background execution.

How to Fetch Facebook Graph Data with Go

I wrote a script using Go to fetch information on Facebook through their Graph API. So I want to blog about how I do it. First of all, if you’re unfamiliar with Facebook graph, we can see the information using a browser: http://graph.facebook.com/android.

A Json object will be returned:

{
   "id": "350685531728",
   "name": "Facebook for Android",
   "description": "Keep up with friends, wherever you are.",
   "category": "Utilities",
   "subcategory": "Communication",
   "link": "http://www.facebook.com/apps/application.php?id=350685531728",
   "namespace": "fbandroid",
   "icon_url": "http://static.ak.fbcdn.net/rsrc.php/v2/yo/r/OKB7Z2hkREe.png",
   "logo_url": "http://photos-b.ak.fbcdn.net/photos-ak-snc7/v43/207/227200684078827/app_115_227200684078827_474764570.png",
   "company": "Facebook"
}

Let’s start with the Go code. First, we need to fetch the content using the http.Get method from  the “net/http” package. After that, we need to close the response body when it is done. More about defer can be found here

resp, err := http.Get("http://graph.facebook.com/android")
defer resp.Body.Close()

Then we read from the resp(response) into body. More about ReadAll.

body, err := ioutil.ReadAll(resp.Body)  

    fmt.Println("resp.Body: ", resp.Body)   
    fmt.Println("body: ",string(body))
    fmt.Println("err: ",err)

After that, we need to unmarshal the the bytes[] (body) of data into a data structure so that we can use the data. This is a little tricky, so let me explain a bit. For a Json object that look like this:

{
    Name: "Alice"
    Body: "Hello",
    Time: 1294706395881547000,
}

We need to prepare a data structure like this:

type Message struct {
    Name string
    Body string
    Time int64
}

Therefore, in our case, the graph API return a Json that look like this:

{
  "id": "350685531728",
   "name": "Facebook for Android",
   "description": "Keep up with friends, wherever you are.",
   "category": "Utilities",
   "subcategory": "Communication",
   "link": "http://www.facebook.com/apps/application.php?id=350685531728",
   "namespace": "fbandroid",
   "icon_url": "http://static.ak.fbcdn.net/rsrc.php/v2/yo/r/OKB7Z2hkREe.png",
   "logo_url": "http://photos-b.ak.fbcdn.net/photos-ak-snc7/v43/207/227200684078827/app_115_227200684078827_474764570.png",
   "company": "Facebook"
}

So we need to prepare a data structure like this:

type Graph struct {
    Id string
    Name string
    Description string
    Category string
    Subcategory string
    Link string
    Namespace string
    Icon_url string
    Logo_url string
    Company string
}

*Please take note of the upper case of the first letter, it is important! See Exported Identifiers.

Finally we can use the data structure for the unmarshalling:

    var g Graph
      err = json.Unmarshal(body, &g)
    if err == nil {
      fmt.Println("graph: ", g)
    } else {
      fmt.Println("graph error: ",err) // <---error at this line
    }

Now, we can use g whichever way we like after that! 🙂

Here’s the complete and running (but messy :P) code:
https://github.com/worker8/go-lab/blob/master/fetching_graph.go