Java: copy from InputStream to OutputStream

The following utitlity class: contains function to copy streams.

public class StreamUtil {

    public static final int BUFFER_SIZE = 8192;

    public static long copy(final InputStream input, final OutputStream output)
            throws IOException {

        return copy(input, output, BUFFER_SIZE);


    public static long copy(final InputStream input, final OutputStream output,
            int bufferSize) throws IOException {

        final byte[] buffer = new byte[bufferSize];
        int n = 0;
        long count = 0;
        while ((n = > 0) {
            output.write(buffer, 0, n);
            count += n;
        return count;


BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File("/tmp/input.txt")));
BufferedOutputStream out = new BuefferedOutputStream(new FileOutputStream(new File("/tmp/output.txt")));
try {
    StreamUtil.copy(in, out);
} catch(Throwable e) {
} finally {

Java: set file permissions

File f = new File("/tmp/");

Run a matlab script without desktop

Run the following command in Terminal:
export MATLABPATH=/usr/local/spm5; /Applications/ -nodesktop -r spm
or save it as shell script. It will start your matlab script (in /usr/local/spm5) without the matlab desktop gui.

See also

Java: break out nested loops

  • Method 1: Use label:
        whileloop: {
          while(true) {
            for(String s : strings) {
                break whileloop;
  • Method 2: Use a boolean tag:
        boolean done = false;
        while(!done) {
          for(String s : strings) {
              done = true;

See also

Mac OS X Mountain Lion: Install git

  1. Install xcode from App Store
  2. Start Xcode, select "Xcode" -> "Preferences..." from the menu bar
  3. Activate "Downloads" tab, install "Command Line Tools"
  4. Now you should be able to run git command in Terminal.

TWiki: disable/enable user registration

  • To disable user registration:
    1. Edit twiki/lib/LocalSite.cfg:
      TWiki::cfg{Register}{EnableNewUserRegistration} = 0;
    2. Reload apache2:
      /etc/init.d/apache2 reload
  • To enable user registration:
    1. Edit twiki/lib/LocalSite.cfg:
      TWiki::cfg{Register}{EnableNewUserRegistration} = 1;
    2. Reload apache2:
      /etc/init.d/apache2 reload

Mac OS X: create arbitrarily large sparse/dummy file

On Mac OS X, you can use command dd or mkfile to create an arbitrarily large dummy file. The following examples create a 20GB file:
  • dd (works on Mac OS/Linux/Solaris/Unix...)
    dd if=/dev/urandom of=sparseFile bs=1m count=2000000
  • mkfile (works on Mac OS/Solaris/Irix)
    mkfile 20g sparseFile

See also

Online streaming video download helper sites: download video from any web sites

javascript: make your table sortable in your blogger post

Include the code below in your post(HTML):
<style type="text/css">
/* Sortable tables */
table.sortable thead {
    font-weight: bold;
    cursor: default;
<script src=""></script>
Mark your table as a sortable one by giving it a class of "sortable":
<table class="sortable">

See also



Mac OS X: set up alarms using Calendar

I want to set up an alarm to remind myself the lunch time break. The Calendar comes with Mac OS X, can be used:
  1. Open Calendar, create a new event at 12pm, repeat it on week days:

Telephone: Free SIP client (softphone) for Mac OS X

I. Telephone App

Telephone is an open source sip client (softphone, voip) for Mac OS X.  It is available at Mac AppStore.

Telephone is a VoIP program which allows you to make phone calls over the internet. It can be used to call regular phones via any appropriate SIP provider. If your office or home phone works via SIP, you can use that phone number on your Mac anywhere you have decent internet connection.

II. Configure Pennytel in Telephone App:

  1. Install Telephone via AppStore
  2. Configure Pennytel account in Telephone:
    1. Full Name: your 10 digits pennytel number
      User Name: your 10 digits pennytel number
      Password: your pennytel voip password
    2. Allow Telephone access Contacts
    3. Now you should be able to make phone calls by entering the phone number in the field:

Free Mac Apps

Name Category Description
AppCleaner System Utilities AppCleaner is a small application which allows you to thoroughly uninstall unwanted apps.
CCleaner for Mac System Utilities CCleaner is a good utility to clean up your Mac.
Calibre E-Book Tools Calibre is a free and open source e-book library management application. It can manage your ebooks in various format, epub, pdf, mobi, etc. It can convert between different formats.
Carbon Copy Cloner Disk/Partition Backup Carbon Copy Cloner is a simple, donation-ware utility for cloning entire drives, performing incremental backups, and scheduling ongoing backups.
Firefox Browser Free, Open source web browser. I have been using it for many years.
Flip4Mac Codec Flip4Mac player includes codecs for Windows media formats. It enables QuickTime to play Windows media files on your Mac.
FlyCut ClipBoard Manager Flycut is a clean and simple clipboard manager for developers. It based on open source app called Jumpcut. Flycut is also open source:
GIMP Image Editor GIMP (GNU Image Manipulation Program) is an image retouching and editing tool and is released under the GPLv3 license as free and open-source software.
HandBrake Video Converter HandBrake is a video converter program intended to both rip and convert video files to work on a number of supported devices.
HexFriend Developer Tools / Hex Editor HexFriend is a fast and clever open source hex editor for Mac OS X.
Kompozer HTML Editor WYSIWYG HTML editor
LibreOffice Office Suite LibreOffice
OnyX Optimization Utilities OnyX is a multifunction utility for Mac OS X which allows you to verify the startup disk and the structure of its System files, to run misc. tasks of system maintenance, to configure some hidden parameters of the Finder, Dock, QuickTime, Safari, Mail, iTunes, login window, Spotlight, and many of Apple’s applications, to delete caches, to remove a certain number of files and folders that may become cumbersome, and more.

PaintBrush Image Editor (lightweight) Paintbrush is a simple paint program for Mac OS X.
Skype Messenger Skype enables calling, seeing, messaging and sharing with others.
smcFanControl Hardware Utilities SmcFanControl controls the fans of every Intel Mac to make it run cooler. smcFanControl lets the user set the minimum speed of the build in fans.
Stuffit Expander Archive Extractor StuffIt Expander is always free. Access StuffIt files, uncompress Zip archives, decompress tar, gzip and bzip archives, and more. Just drag, drop, and you're done! From BinHex to Zip, StuffIt to MIME, Expander accesses more formats, in less time, with zero hassles.
Tagr MP3 Tag Editor Tagr is a small and simple MP3 and MP4 tag editor.
Telephone VOIP: SIP Client Telephone is a VoIP program which allows you to make phone calls over the internet. It can be used to call regular phones via any appropriate SIP provider. If your office or home phone works via SIP, you can use that phone number on your Mac anywhere you have decent internet connection.
Time Out Free Reminder It is very easy to fall into bad habits when using a computer for hours on end. You care about what you are doing, so can sometimes push yourself too far, or over-strain yourself. The human body isn't built to sit in one position for endless hours, gripping a mouse or typing on the keyboard. Dejal Time Out is here to help. It will gently remind you to take a break on a regular basis.
TrueCrypt Data Encryption Free open-source disk encryption software for Windows 7/Vista/XP, Mac OS X, and Linux.
uTorrent Bittorrent Client
VLC Player Media Player VLC is a free and open source cross-platform multimedia player and framework that plays most multimedia files as well as DVD, Audio CD, VCD, and various streaming protocols.
VirtualBox Virtualization VirtualBox is a powerful x86 and AMD64/Intel64 virtualization product for enterprise as well as home use.

Mac OS X: how to get rid of .DS_Store files

I. Can we disable the creation of .DS_Store files?

Answer is NO. But we can disable the creation of .DS_Store files on network volumes using the following command:
defaults write DSDontWriteNetworkStores true

II. How do I clean up the .DS_Store files

Run the following command in,
find /Volumes/USB-DISK -name '.DS_Store' -type f -delete

See also

Mac OS X: how to get rid of ._ files on USB drive

._ files are created by the OS. It is annoying when those files are created on a portable USB drive then opened on other operating systems.

Can we avoid creating them on Mac OS?

The answer is NO.

How can we get rid of them then?

There are many ways to find & remove them:
  • Method 1: Use find command in Terminal:
    find /Volumes/USB-DISK -name '._*' -type f -delete
  • Method 2(Recomended): Since Mac OS 10.5 Leopard, it come with a command line utility dot_clean to get rid of the ._ files. Run the following command in Terminal will remove all the ._ files in /Volumes/USB-DISK:
    dot_clean /Volumes/USB-DISK

See also

Mac OS X: connect to Canon iR C5185 Printer with Department ID Management

  1. Download UFR II driver for Mac from Canon.
  2. Install the UFR II driver
  3. Open "System Preferences" -> "Print & Scan", Click the + button to add printer
  4. Activate "IP" tab, enter the IP address of the iR C5185 machine, set "Protocol" to Line Printer Daemon - LPD; select Canon iR C5185 UFR II driver from the software list, then click "Add" button.
  5. Tick "Job accounting", then click "OK" button.
  6. Select the printer from the printer list, and click "Options & Supplies.." button.
  7. Activate "Utility" tab then click "Open Printer Utility" button.
  8. Tick "Department ID Management", then enter your Department ID and PIN. Verify it by clicking the "Verify" button. If it is correct, click "Save Settings" button.
  9. Quit Printer Utility and System Preferences, we've done. You can now print to the Canon iR C5185 printer.

Linux: how to check the remote NFS server version

  • The following command can be used to check the version of the remote NFS server:
    rpcinfo -s | grep nfs
    it will return the result like below:
    100003  2,3       udp,tcp                          nfs         unknown
    the second column, 2,3, are the versions of the nfs servers running on the remote host.
  • or if your rpcinfo implementation does not support -s option, you can
    rpcinfo -p | grep nfs
    it will return the result like below:
    100003    3   tcp   2049  nfs
    100003    2   tcp   2049  nfs
    100003    3   udp   2049  nfs
    100003    2   udp   2049  nfs
    the second column shows the version of the nfs server.
  • To check the nfs server running on localhost, you can
    rpcinfo -s localhost
    rpcinfo -p localhost
    sudo nfsstat

See also

Ubuntu Linux: change hostname

  1. edit /etc/hostname:
  2. edit /etc/hosts: wilson-pc
  3. restart hostname service:
    /etc/init.d/hostname restart

dotproject: install php5-gd to enable gantt supports


sudo apt-get install php5-gd

Ubuntu 12.04 Precise LTS: Install and secure Apache 2 web server

  1. Install apache2:
    sudo apt-get install apache2
  2. Hide the Apache Version number, and other sensitive information:
    sudo vi /etc/apache2/conf.d/security
    ServerTokens Prod
    ServerSignature Off
  3. Turn off directory browsing:
    sudo vi /etc/apache2/sites-available/default
    <Directory /var/www/>
        Options -Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
  4. Follow this guide to install ModSecurity.
  5. Follow this guide to install ModEvasive.

TWIKI: exec failed: No such file or directory /usr/bin/rlog


sudo apt-get install rcs

mysql: changing data directory requires change of apparmor settings

When changing mysql data directory from /var/lib/mysql to /Volumes/Store/mysql:
sudo service mysql stop
sudo mv /var/lib/mysql /Volumes/Store/mysql
sudo service mysql start

Your mysql will fail to start, and run dmesg, you can find the follow error:
[ 2012.069037] type=1400 audit(1357622820.131:47): apparmor="DENIED" operation="mknod" parent=1 profile="/usr/sbin/mysqld" name="/Volumes/Store/mysql/nsp-precise.lower-test" pid=5300 comm="mysqld" requested_mask="c" denied_mask="c" fsuid=0 ouid=0

This is because apparmor are preventing mysqld from accessing unregistered directories.
To solve the problem, edit /etc/apparmor.d/usr.sbin.mysqld as root, and add following lines:
/Volumes/Store/mysql/ r,
/Volumes/Store/mysql/** rwk,

then, start mysql server
sudo service mysql start

See also


TWIKI: edit page without wysiwyg

For the editors who are familiar with the twiki syntax, the wysiwyg editor is not as comfortable as raw text editor. To edit the twiki page without using the wysiwyg editor, you can
  • Select "Edit" then "Raw Edit" in the top menu bar
  • or, click "Raw edit" at the bottom of the page:

Mac OS X: Turn off natural scrolling

The first thing I do after get my macbook pro is, disable so-called natural scroll. because I feel it is so unnatural.

To turn it off:
  1. Open "System Preferences" then click "Trackpad"
  2. Activate "Scroll & Zoom" tab, deselect "Scroll direction: natural"

Ubuntu: Migrate all mysql databases from one server to another

  1. On the new server, install mysql server:
    sudo apt-get install mysql-server mysql-client
  2. On the new server, stop the mysql server:
    sudo service mysql stop
  3. On the new server, backup /var/lib/mysql:
    sudo mv /var/lib/mysql /var/lib/mysql.bak
  4. On the old server, stop the mysql server:
    sudo /etc/init.d/mysql stop
  5. On the new server, mirror /var/lib/mysql directory from the old server:
    sudo rsync -avz root@old_server:/var/lib/mysql /var/lib/
  6. On the new server, run
    sudo mysql_upgrade -u root -p
    (NOTE: if you forget the root user password, you can reset the root password.)
  7. Start mysql server on the new server:
    sudo service mysql start

See also

Ubuntu: Install apache2, php5 and mysql

sudo apt-get install mysql-server mysql-client apache2 php5 libapache2-mod-php5 php5-mysql

mysql: reset root password

  1. Stop mysql service:
    sudo service mysql stop
  2. Start mysqld with following arguments: --skip-grant-tables and --skip-networking:
    sudo mysqld --skip-grant-tables --skip-networking &
  3. Run following command to upgrade the database:
    sudo mysql_upgrade
  4. Connect to mysql server:
  5. Run following SQL clauses to change root password:
    UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';
  6. Stop the msyql process:
    sudo killall -9 mysqld
  7. Start mysql service:
    sudo service mysql stop

See also

dotproject: table dotproject.user_preferences does not exist

After upgrade dotproject to the latest version 2.1.7, got the error:

query failed(SELECT pref_name, pref_value FROM `user_preferences` WHERE pref_user = 0) - error was: Table 'dotproject.user_preferences' doesn't exist

The solution is:
  1. run the web installer:
  2. Click on Start Upgrade to proceed.

See also

dotproject: invalid memory configruation for Gantt


After upgrade dotproject to 2.1.7, found the error below:

"We could not configure your memory or your memory configuration is too low, this may be as a result of Safe Mode being in effect and may result in not enough memory to display this chart."


  • Login to dotproject as admin, "System Admin" -> "System Configuration", set "Memory Limit for Gantt"

See also

css: monospace (fix-width) font families

font-family: Consolas, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace;

css styles for pre and code

<style type='text/css'>
    pre {
        background-color: #eeeeee; border: 1px dashed #999999; color: black; line-height: 12pt; overflow: auto; padding: 5px; white-space: pre-wrap; width: 100%;
    code {
        padding:0px 5px 0px 5px; font-family:Consolas,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New, monospace; font-size: 9pt;  font-weight: bold;

dotproject: send emails using gmail

  1. A gmail account is required to authenticate with server.
  2. Install and configure postfix to send mails using [detail...]
  3. edit /etc/php5/apache2/php.ini:
    [mail function]
    ; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
    sendmail_path = "/usr/sbin/sendmail -t -i"
  4. Login to dotproject as admin, "System Admin" -> "System Configuration", in "Email Settings" section, set "Email Transport"
    PHP Default
  5. Now the task logs can be send to contacts using gmail smtp server.

See also

dotproject: reset admin password

  1. Start mysql console:
    mysql -u root -p
  2. Open the dotporject database:
    use dotproject
  3. Change the admin password:
    update users set user_password = md5('new_pass') where user_username = 'admin';

See also