Posts

Showing posts from 2010

Basic exception usage in php

Theory If you have not already, check the official php documentation on exceptions at http://php.net/manual/en/language.exceptions.php. Besides some php specifics, here you can find basic example how to use try catch blocks and how to work with exceptions. Example goes like this: function inverse($x) { if (!$x) { throw new Exception('Division by zero.'); } else return 1/$x; } try { echo inverse(5) . "\n"; echo inverse(0) . "\n"; } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Continue execution echo 'Hello World'; Through this example you can see that if a process finds itself in a problematic situation, it can throw an exception. This exception can be caught, and that way we will prevent system to run into some php fatal error. This are the theoretical basics, however, the real question is how and where to use exception handling in your  applications and scripts. Front Controller Front C

Convert XmlDocument to XElement

XmlElement x = objXmlDocument.documentElement; You might need this if you are creating a WCF service that accepts XElement as parameter but user has a dataset to be converted to Xelement XmlDocument xDoc = new XmlDataDocument(YourDataset); XmlElement x = xDoc.DocumentElement; example :  DataSet ds = new DataSet();  ds.Tables.Add("students"); ds.Tables[0].Columns.Add("Name");  DataRow dr1 = ds.Tables[0].NewRow(); dr1[0] = "Alan"; ds.Tables[0].Rows.Add(dr1);  XmlDocument xDoc = new XmlDataDocument(ds);  XmlElement x = xDoc.DocumentElement;

NOKIA N900 upgrade

There are 3 ways to upgrade your N900. OTA Over The Air. YES! Upgrade your phone online. Its easily but might cause problems after OTA. PC suite Use NOKIA OVI suite or NOKIA Software Updater. Upgrade your phone with PC suite and backup your file before you starting. That's the safest way to upgrade your N900! But all chinese support will be lost after upgraded. Rewrite with flasher Get the flasher with latest ROM file. Rewrite the ROM with latest version. You don't have to rewrite eMMC content unless the system crashed. Besides, if you've been upgrade your phone but ran into some problems, you'd better rewrite your ROM again with the same version. All chinese support also will be lost after upgraded. You can easily done with above way for upgrading. Enjoy yourself! ps. I already upgraded my N900 to PR 1.3. XD

Why exception handling is important in php?

    I work as a professional programmer for 10 years and in those 10 years I met a bunch of different developers. In plenty of them, especially in web / php developers, I could notice a lack of understanding of the concept of throwing and catching exceptions and what does it serves for. Of course, the first I noticed it at myself. In this blog I would like to point out a number of useful things that proper use of the exception can make, and which were slipping from my hands for a few years too.      Exceptions are providing a standardized way to control problematic processes and they are reducing the possibility of fatal errors in the application . If process throws exception, you are forced to handle situation in your application, and it will automatically reduce the possibility that some problem sleeps out whit out being processed. When you're working with exceptions, you are handling problems at low level, so it will not make you problems with your higher layers, e.g displaying

Chinese font can not be show correctly with JAVA application on FreeBSD

I ran into this problem as I installed the freemind. After searching with Google, the following steps can solve the problem. Create a directory named "fallback" in JRE path # cd /usr/local/jdk1.6.0/jre/lib/fonts # mkdir fallback Link a TrueType that I wanted to the new directory # cd fallback/ # ln -s /usr/local/lib/X11/fonts/TrueType/bsmi001p.ttf ./bsmi001p.ttf Restart the JAVA application After restarting, the JAVA application will show chinese font properly. ps. Many thanks for Tim's help.

Homebrew - Another package manager for Mac OS X

前陣子在 plurk 上看到 Rex 大提到 Homebrew,一開始也不曉得那是什麼? 慢慢才知道原來是另一種套件管理工具。 今天在看到 ihower 大大的 blog 文章後,索性就動起來手來,先把 MacPorts uninstall 掉,然後再依照 ihower 大大提供的步驟把 homebrew 裝了起來。(作法請參考 ihower 大大的 原文 ) Homebrew 是一套 ruby based 的套件管理程式,它的特性如下﹕ 不佔用系統空間 不重覆安裝 mac 系統中已內建的工具 ruby based 的 portfile,易於修改、自訂 使用者可很快的建立自己想要的套件 個人用了之後,覺得 MacPorts 更新較快、內容較多,但,Homebrew 則是標榜不重覆,簡易使用。 果真簡易!

MacPorts uninstall

Following the steps below: Uninstall ALL installed packages $ sudo port -f uninstall installed Remove related directories $ sudo rm -rf \ /opt/local \ /Applications/DarwinPorts \ /Applications/MacPorts \ /Library/LaunchDaemons/org.macports.* \ /Library/Receipts/DarwinPorts*.pkg \ /Library/Receipts/MacPorts*.pkg \ /Library/StartupItems/DarwinPortsStartup \ /Library/Tcl/darwinports1.0 \ /Library/Tcl/macports1.0 \ ~/.macports Now, its clear and all installed packages from MacPorts was disappeared.

CU: Serial terminal emulator

cu,個人覺得是一個簡單、方便的 serial console 連線工具。 第一次看到是在 debian 上,透過 apt-cache search 找到的工具,裝好就可以用了。後來,在 OpenBSD 上就沒找到 cu。一度以為沒有這個工具,也試著想找它的 source code 來在 OpenBSD 上自編譯、使用未果。 這幾天在試玩新的 OpenBSD 4.8 時,才發現原來早就內建在系統中,我真是後知後覺啊!! orz $ sudo cu -l /dev/cuaU0 -s [speed] 超方便,但功能不會陽春哩!

Rules of screenrc

$ vim .screenrc hardstatus on hardstatus alwayslastline hardstatus string "%{.bW}%-w%{.rY}%n %t%{-}%+w %=%{..G} %H(%l) %{..Y} %Y/%m/%d %c:%s " bind b encoding big5 utf8 bind u encoding utf8 utf8

Another chinese input methods in MacPorts

除了內建的和 Yahoo 輸入法之外,在 MacPorts 裡也找到其它可用的選項。 dhcp-22007:~ shawn$ port search "Chinese input method" gcin @1.2.1 (x11) a Chinese input method server. openvanilla @0.7.2 (aqua, textproc) package of popular Chinese input methods Found 2 ports. Wow, gcin 也放進來了! Great job!

MacPorts update & upgrade

To update MacPorts $ sudo ports selfupdate To upgrade outdated installed applications $ sudo ports upgrade outdated

My settings for X on ArchLinux

[shawn@arch2k5 ~]$ cat .xprofile #export LANG=zh_TW.utf8 export LC_CTYPE=zh_TW.utf8 export LANGUAGE=zh_TW.utf8 export GTK_IM_MODULE=ibus export XMODIFIERS=@im=ibus export QT_IM_MODULE=ibus ibus-daemon -d nm-applet & gnome-power-manager &

?? operator

x=1; string NumberIs = (x==1)?"One":"Not Known"; Above code checks if X is queal to One then return "One" to NumberIs variable else return "Not Known" There is another operator ?? which specifically checks for null DataRow dr = myRow ?? DataRow.EmptyRow This is same as: If (myRow == null) dr = myRow else dr = Datarow.EmptyRow ?? checks for left side is null or not. If it is null then it returns right part.

Accesssing TextBox value in Init Event

As per ASP.net Page Lifecycle, Events that actually wire up Server Controls and load their viewstate, take place, quite after Init. However, one thing to remember is that even in Init Request object is available. Hence, if you are aware of textbox control then you can access it using Request["textBoxName"]. Ideally you would use HTMLcontrol instead of ASP.net server control Like: <input type="text" id="myTextbox" value="<%=SomeValueFromServerSide%>"> This textbox then can easily be accessed in Init using var textBoxValue = Request["myTextBox"]

國小母校

Image
我的國小母校,桃園縣立成功國小,一所建立幾十年的老學校,據說在日據時代就已存在了。我媽、我老姐、我老婆和我都是校友! 雖然離家裡很近,但畢業後 2x 年都沒回去過幾次! 但,在小朋友二歲多的今天 (2010/8/28),跟老婆心血來潮,一起帶著小孩再度重回母校,看看 2x 年後的校園有了哪些改變! 進了校門後,我不自覺的將牽著的老婆的手握得更緊。一家人緩緩的進行校園巡禮後,我發現除了活動中心和行政大樓還在之外,其它的教舍都不復當年了! (OS: 2x 年不變的學校,很難吧!) 我還依稀記得當年的動物園座落在校園的哪個角落! 我還得當時蒸便當的位置在哪裡! 我還記得大象溜滑梯在哪棟大樓的後面! 我還記得賣著好吃的千力麵和涼麵的福利社,擠得水洩不通的樣子! 伴著垃圾場惡臭的側門外,有一個小雜貨店已不復存在! 揚著黃沙的操場已被 PU 跑道和場地取代! 第二排及第三排教舍已變成一片小朋友的樂園,滿是遊樂設施! 啊! 那個水泥做的斑馬還在! 只是少了支耳朵。水泥做的獅子也還在,只是不復當年的威風! 花豹和小鹿斑駁不堪! 大概只有駱駝才可以和斑馬一樣,清晰可辨! 我想,當年的班導師應該都退休了吧? 幾個曾經帶個的班導師,都讓我留下深刻的印象! 我老婆訝異著她早已忘懷多時的事物,我竟一路一一描述著當年的狀況! 或許,這是我少少的長處之一吧! 短短的 1.5 個小時,卻像是走回時光隧道那般的回味無窮! 我想我以後會常帶小朋友回來這裡走走,到操場跑跑,在他的童年裡回味著自己的童年!

How to downgrade FreeBSD's Ports

su as root cd /usr/ports/ports-mgmt/portdowngrade; make install clean; rehash setenv CVSROOT :pserver:anoncvs@anoncvs.tw.FreeBSD.org:/home/ncvs cvs login portdowngrade www/p5-FastCGI portsdb -Uu portupgrade -f p5-FastCGI

Dropdown value when EnableViewstate = false

If EnableViewstate of a dropdown is set to false, you would need to bind the data at every post. Nothing new in this! But, you might face issues in retrieving value selected in dropdown before postback. It will always be "" To get the value, pre-populate dropdown in Page_Init instead of Page_Load (if you are doing so). This will give the right selected value.

順著天賦做事,逆著個性做人

我是個很幸運的人,因為我經常遇到貴人,不管這些貴人們曾經如何對我,我總能直接或間接的從他們身上汲取到一些經驗! 對此,我也由衷的感謝! 當然,標題的這句話也是從貴人們身上獲得的寶貴經驗! 最近我常會想起這句話,"順著天賦做事,逆著個性做人",從字面上解釋,就是發揮自己的長才,修飾或隱藏自己在個性上的缺點,使得為人處事都能圓滿! 或許會有人說,那不就是偽裝? 虛偽? 其實不盡然。 舉例來說,我的專長就是溝通,所以,我就應該好好發揮這個長處,使得人、事、物得以透過溝通、協調進而圓滿! 這就是 "順著天賦做事"! 而我的個性其實很懶散,從小被管到大的我,很討厭被約束,我也很討厭去約束別人! 因為 "己所不欲,勿施於人"! 但,當我的工作付予任務,即時有千百個不願意,為了工作,為了群體利益,我就會壓抑著自己在個性上的特質,想辦法去完成任務! 這就是 "逆著個性做人"! 當然,有人曾經問我,"何苦來哉? 這樣對待自己能有什麼好處?" 剛開始我總會試著去說明,後來就只是笑著不回應了。乍看之下,這樣做的確對自己沒什麼好處,做得汗流浹背,別人嫌到口水亂噴! 我的理由如下: 對自己負責,也對工作有交待,心安理得。 如果事情能順利做完,也對群體有正面的助益,雖然知道會很苦,何不試著樂觀面對? 做起來也開心。 有些事,在當下會很苦、很難熬! 但,咬牙撑過後,反而會有一番不同的感受,結果,我又成長了。 過往的歷練也驗證了這句話的價值! 我因為這句話,受益不少! 至少,當別人在批評草莓世代時,我很慶幸自己的抗壓性在不同階段都能每況愈上! 只是我還是沒有做得很好! 至少,目前還是! 還需要多努力、多加油! 謹以此文引以為愓!

The power of Intel Quad core * 2 + FreeBSD 8 amd64

Image
因工作上的需求,我必須處理 Subversion 因為 svn blame 造成的高系統負載問題。 作業環境如下: FreeBSD 7.2 Apache 2.x Subversion 1.x viewvc 1.x 在原來的硬體環境: CPU: Intel Xeon 3.06 GHz with HT RAM: 2GB HDD: SCSI FreeBSD/SMP: Multiprocessor System Detected: 4 CPUs cpu0 (BSP): APIC ID: 0 cpu1 (AP/HT): APIC ID: 1 cpu2 (AP): APIC ID: 6 cpu3 (AP/HT): APIC ID: 7 一旦使用者透過 viewvc 執行 annotate 的工作,只要一個! 且單一檔案內容超過萬行的情況下,就會造成系統高負載 (average load 破百) 的情況,最嚴重的狀況是連 console 操作都會 hang 住! 而且 httpd 和 svn 的 process 數量也 fork 很多出來! 深究其因,應該是 viewvc 造成的! 其次,CPU 僅是透過 HT 虛擬成 4 個 cpu,而並非真正 multiple core,因此運算能力也相對較弱! 以提供服務的角度來看,這個功能是使用者經常用到的! 因此,除了去 trace viewvc 外,唯一可解的就是硬體升級了! 新的硬體環境: CPU: Intel Xeon E5420 2.5 GHz RAM: 48 GB HDD: SAS FreeBSD/SMP: Multiprocessor System Detected: 8 CPUs FreeBSD/SMP: 2 package(s) x 4 core(s) cpu0 (BSP): APIC ID: 0 cpu1 (AP): APIC ID: 1 cpu2 (AP): APIC ID: 2 cpu3 (AP): APIC ID: 3 cpu4 (AP): APIC ID: 4 cpu5 (AP): APIC ID: 5 cpu6 (AP): APIC ID: 6 cpu7 (AP): APIC ID: 7 OS 改用 FreeBSD 8 amd64 的版本,將 /tmp 透過 md 掛載大小為 18G

Indexers in C# and VB.net

What are Indexers? Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters. A class can have only one Indexer In VB.net, default keyword is required to make it indexer Index can be accessed either by a numeric index or even string How to Use (C#)? using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSconsole { class NamesList { public int Length { get { return objList.Count; } } List < String > objList = new List < string >(); public string this [ int index] { get { return objList[index]; } set { objList.Add ( value ); } } } public class TestIndexers { public static void Main () {

Convert nrg file to iso

There are 2 options on Debian/Linux: nrg2iso iat I tried nrg2iso at first, it told me the nrg file is already in ISO9660 format and did not covert. And I tried iat then that. It works fine! $ iat image.nrg image.iso Iso9660 Analyzer Tool v0.1.3 by Salvatore Santagati Licensed under GPL v2 or later Detect Signature ISO9660 START at 32768 Detect Signature ISO9660 END at 36864 Image offset start at 0 Sector header 0 bit Sector ECC 0 bit Block 2048 Done The outputed iso can be used with no wrong.

Handling Dropdownlist inside gridview

Often there is a need to handle OnSelectedIndexChanged event of a dropdown residing inside a GridView. This can be handled as following: 1. Specify an event handler from dropdown in ASPX < asp : GridView ID ="GridView1" runat ="server" AutoGenerateColumns ="False"> < Columns > < asp : TemplateField > < ItemTemplate > < asp : DropDownList OnSelectedIndexChanged ="ddl_Change" DataTextField ="UserName" AutoPostBack ="true" DataValueField ="userId" ID ="ddl" runat ="server"/> 2. Add event handler in ASPX.cs Protected Sub ddl_Change( ByVal sender As Object , ByVal e As EventArgs) 'You can retrieve Dropdown as: Dim DropDownControl As DropDownList = CType (sender, DropDownList) 'You can retrieve Parent GridRow as: Dim gridRow As GridViewRow = CType ( CType (sender, DropDownList).NamingContainer, GridViewRow) &

Whats new in C# 2.0 3.0 4.0

What's new in C# 2.0 1. Generics 2. Nullable Types 3. Iterators 4. Partial Class Definitions 5. Anonymous Methods 6. The :: Alias Qualifier 7. Static Classes 8. Covariance and Contravariance 9. Fixed-Size Buffers 10. Friend Assemblies 11. extern Aliases 12. Method Group Conversion 13. Accessor Access Control 14. The #pragma Directive What's new in C# 3.0 1. Lambda expressions 2. Extension methods 3. Implicitly typed local variables 4. Query comprehensions 5. Anonymous types 6. Object initializers 7. Implicitly typed arrays 8. Automatic properties 9. Partial methods 10. Expression trees What's new in C# 4.0 1. Named and Optional Parameters 2. Dynamic Support 3. Variance 4. COM Interop

Memory based file system (ramdisk) on FreeBSD

To create a ramdisk for /tmp and detach it on FreeBSD 8 # /sbin/mdmfs -M -S -o async -s size md0 /tmp Don't forget to chmod +w for read/write # chmod +w /tmp Detach it and delete from /dev/md0 # /sbin/mdconfig -d -u 0 There is a shell script for the operation %cat ramdisk.sh #!/bin/sh case "$1" in create) /sbin/mdmfs -M -S -o async -s 18432m md0 /tmp /bin/chmod 777 /tmp echo "18G ramdisk created on md0 and mounted on /tmp" exit 0 ;; destory) /sbin/umount /tmp /sbin/mdconfig -d -u 0 echo "ramdisk umounted from /tmp and destory from md0" ;; *) echo "Usage: `basename $0` {create|destory}" >&2 exit 64 ;; esac Caution ! This is for specificed purpose only! You have to modify the parameters if you want to use it.

Install Pidgin 2.6.4 from source on OpenBSD 4.6

At first, following content is just my experience to install a newer version from source, it may not works as well as you guys used on LINUX. Do following steps: You have to install following packages before you start to compile pidgin! gmake gstreamer gnutls libnss python cyrus-sasl2 tcl/tk farsight Well, a GTK based desktop environment is needed! (I use XFCE4, Gnome is the best!) Download the source from Pidgin's official site Extract the source Run configure with parameters # ./configure --disable-vv --disable-meanwhile --disable-nm --with-gnutls-includes=/usr/local/include --with-gnutls-libs=/usr/local/lib --with-tclconfig=/usr/local/lib/tcl8.5 --with-tkconfig=/usr/local/lib/tk8.4 Compile # gmake Install as root # sudo gmake install If all the procedures are work properly, you can just start pidgin and enjoy it on OpenBSD 4.6 now! :)