Thursday, May 16, 2013

Matchismo on iOS



This is the first assignment for the course CS193P at Stanford 2013 winter session. It shows how the "MVC" structure works, and also includes really good coding style in objective-oriented programming.

http://www.stanford.edu/class/cs193p/cgi-bin/drupal/

Some interesting stuffs I would like to share is as below:

  1. Connecting the "View" related events or properties by dragging the object from GUI programming interface to text code. Cool.
  2. NIL pointer design, I've written things about this in last post.
  3. General initialisation design. Objects in objective-C mostly have the some usage in initialisations, setters/getters, function callings, etc. It's easy for the developers to learn some basic examples and apply on different occasions.
  4. Auto-complete editing design in Xcode. Although this feature, auto-complete while typing the code, is not new stuff, it's still the best auto-complete mechanism I've ever seen. It's fast, and smart. It allows you to jump to next blank in a very short time. While writing the program, you spent very little time on typing. Around 80%~90% of the code can be done by the auto-complete function, only the new names for object/function/etc are needed to be typed completely. At last, Xcode also generates those an annoying special characters in the code, like "", [], {}, etc.
Finally, the developing environment for iOS is not only including great designs but also so much fun.



Saturday, May 11, 2013

NIL Pointer in Objective C

In many programming languages, we do the checking if the pointer is null (equally, 0) or not before we start to grab the content. However, in Objective C, there's no need to do this. The design makes you no need to do so.

When a pointer has no object points to, it's automatically storing the value 0, which we call a NIL pointer. And, we can complete our other designs without checking the pointer is NIL or not because that function calls just do nothing on NIL pointers, and return 0.

Take one example I learned in the class,
if ([card.contents isEqualToString:self.contents] ){ score = 1; }
No need to card.contents is NIL or not. If it's NIL, isEqualToString just simply skip it and return 0, which may cause the if-statement failed, which is also the right thing we want.

Thursday, April 18, 2013

Why VIM?


" Vim不是「很難用的編輯器」,只是你不夠瞭解他 "

Vim中一般文字編輯器沒有功能

  1. 命令模式:每個按鍵變成指令,可在短時間內編輯你想要的東西,例如:「在行尾加句點(2 keys)」、「大小寫互換(1 keys)」、「複製目前這行九遍(4 keys)」、...。而做反覆的事情只需要加上數字便可以表示做幾次,另外甚至可以寫一整串的指令。
  2. 客制化:透過撰寫.vimrc這份檔案,可以把vim改成自己喜好的樣式,例如:「設定compile and run的快捷鍵」、「設定android開發時需要的指令成快捷鍵」、...
  3. 結合shell:Vim可以簡易的在編輯器中輸入外部系統指令,也可以讓外部容易的連上Vim編輯文件,相輔之下,讓人在寫程式快速穿梭在系統和文字編輯之間。

說服大家使用Vim的原因很多人都寫過(如上),我個人會喜歡舉一些簡單例子:

Q:欲在游標指向的這行,句首第一個字元從小寫改大寫,再在句尾加上一個句點(一個我們常常會遇到的情況)

「一般文字編輯器」方法:
  1. 連續按左箭頭到句首(或是用滑鼠小心點擊)
  2. 按delete刪掉本來的小寫字元
  3. 輸入大寫字元
  4. 再連續按右箭頭到句尾(或是移動手改用滑鼠)
  5. 按'.'輸入句點
「Vim」方法:
  1. 輸入:「^~A.」即可

最後,雖Vim需要經過學習,一開始使用也不會比較快,但學習之後可以快很多很多很多....

Saturday, April 6, 2013

Web Image Grabbing Robot Using Google Image API

This time, I am facing a problem to grab corresponding images from a keyword list. Most of the time, we do Google Image Search, and find out the image we want. However, this will be inefficient when it comes to few hundreds of keywords.

Therefore, the program I wrote here automatic read keywords from the list, and call the Google Image API to find out the first three images relating to this keyword. The images are showed in URL. The reason for showing the first three images is that not all the time Google give out the one we want in the first element of the results. I've also written a website in PHP which allow people to select the image from these three images, and automatically grab the one which is selected to the server. As a result, you only have to check through which image you want to store in the end, you don't have to do any search or any downloading.

Python Program:
#!/usr/bin/python
import urllib2
import simplejson

keyword = raw_input("Image Search >> ")
keyword_encoded = urllib2.quote(keyword, '')

url = ('https://ajax.googleapis.com/ajax/services/search/images?' +
       'v=1.0&q=' + keyword_encoded + '&userip=IP-INSERT-HERE-HERE')

request  = urllib2.Request(url, None, {'Referer': 'plate.nctucs.net'})
response = urllib2.urlopen(request)

results = simplejson.load(response)

for i in range(3):
 print results['responseData']['results'][i]['url']

Wednesday, April 3, 2013

Applying K-mean on CSV files using Python

What is K-mean?

K-mean is an easy to clustering the data, which knowing their features already. We call the input data entities as "observation", and the output groups as "cluster". Today, k-means is working for labeling n the observations into k clusters.

What is CSV?

CSV is a data storage format in plain text. This can be generate from excel, google form, etc. It's also easy to be applied in different languages, since it's simple syntax.

What Am I Writing Today?

I am writing a program can read the table from a CSV file which may be generated by excel or google drive form, and apply the k-mean algorithm. At last, it output the clusters as result showing the items in different clusters, also draw the points on the screen.


#!/usr/bin/python

# This program attend to read data from a csv file,
# and apply kmean, then output the result.

from pylab            import plot,show
from numpy            import vstack,array
from numpy.random     import rand
from scipy.cluster.vq import kmeans, vq, whiten

import csv

if __name__ == "__main__":

    # clusters
    K = 3

    data_arr = []
    meal_name_arr = []

    with open('meals2.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            data_arr.append([float(x) for x in row[1:]])
            meal_name_arr.append([row[0]])

    data = vstack( data_arr )
    meal_name = vstack(meal_name_arr)

    # normalization
    data = whiten(data)

    # computing K-Means with K (clusters)
    centroids, distortion = kmeans(data,3)
    print "distortion = " + str(distortion)

    # assign each sample to a cluster
    idx,_ = vq(data,centroids)

    # some plotting using numpy's logical indexing
    plot(data[idx==0,0], data[idx==0,1],'ob',
         data[idx==1,0], data[idx==1,1],'or',
         data[idx==2,0], data[idx==2,1],'og')

    print meal_name
    print data

    for i in range(K):
        result_names = meal_name[idx==i, 0]
        print "================================="
        print "Cluster " + str(i+1)
        for name in result_names:
            print name

    plot(centroids[:,0],
         centroids[:,1],
         'sg',markersize=8)

    show()

Wednesday, February 20, 2013

Basic Things About namespace in C++

這回是演算法課,老師提供一個Judge網頁(https://better.cs.nctu.edu.tw/2013_spring_algo_hw1/)給大家練習題目,可是它系統與之前用的解題系統略有不同,其中我們需要完成的是一份cpp檔案裡的一個namespace內的東西。所以藉這機會再瞭解一下namespace。

namespace顧名思義是指命名空間,底下可以有變數、函示的定義,使用時候可以在程式碼裡面加using namespace <name_of_the_namespace>即可,若是不加,則在要使用該namespace下的東西前面加來自的地方,例如:寫using namespace std; 之後,可以直接用cout;而若是沒寫,則可以用std::cout。

老師提供的空白檔內有一個稱為HOMEWORK的namespace,底下有三個函式,分別是NumberOfInversion(), Init(), Cleanup(),Init和Cleanup即是初始和結束要做的事情,NumberOfInversion是依照題目要求要完成的部分。

然而完成這份namespace之後要怎麼測試呢?可以寫個main.cpp如下(code.empty.cpp是定義namespace的檔案,也是題目要求我們要完成的):

#include <iostream> 
#include "code_empty.cpp"

using namespace std;

int main(){ 

    using namespace HOMEWORK;

    Init(); 

    int arr[] = {0,1,4,3,2}; 
    cout << NumberOfInversion(arr, 5) << endl;;

    Cleanup(); 

    return 0; 
}

*記得在編譯main.cpp時候要注意include code_empty.cpp的情形(視編譯環境)


Friday, February 1, 2013

Controlling Virtualbox From Command Line & SSH From Host to Client

Here, I got some virtual machines on my laptop. And I would like to learn how to control them via command line. The controls I am interested in includes, "start", "power off", "save current state", etc.

Take the "Fedora" virtual machine as example.

  • VBoxManage startvm "Fedora"
    • Turn on the virtual machine
  • VBoxManage startvm "Fedora" --type headless
    • Start the virtual machine without really start the window
  • VBoxManage controlvm "Fedora" savestate
    • Save the current state of the virtual machine and turn off the window
Setting up connection from host to client using ssh is also easy.
  1. on the setting page of the virtual machine
  2. click on network tab, and add a new adapter (usually, it's adapter 2)
  3. attached to "host-only adapter", with name "vboxnet0"
    • if virtualbox shows "invalid setting" in the lower part, go to the "preference" page of virtualbox, then find "network" tab, and add a new setting by pressing the button on the right hand side
  4. start the virtual machine, and click IP by typing "ifconfig"
  5. enable ssh server on the virtual machine, you may check it work or not by trying ssh to itself
  6. ssh to the IP you saw on the client with the right username