Saturday, October 12, 2013

[test] User Agent

Sunday, December 30, 2012

How to keep ssh alive in terminal of Macbook

In macbook, I usually use ssh in terminal to connect to remote servers. However recently the terminal often becomes unresponsive after being idle for a while, then it prints the error "Write failed: Broken pipe" and quits the ssh connection.

The solution I found is to add the following line in ~/.ssh/config:
ServerAliveInterval 120

How to install and link with the package "Geometric Tools" in Linux

Here is what I did to install and link with the package Geometric Tools:
  1. Download the package into your home directory and unzip it.
  2. Add the following line into ~/.bashrc, and run "sh ~/.bashrc" or log out and log in again.
  3. Change to the directory GeometricTools/WildMagic5, and type
    make CFG=Release -f makefile.wm5
    
  4. To compile, we can use the following command

Sunday, December 9, 2012

How to correctly take square root in programming

If we simply call "sqrt()" function to take square root, very often we'll be caught by surprise.

The first common mistake is to not check negativity before taking square root. For example, Instead of getting 0.0 in both cases, one of the case will yield "-nan". This is because y is actually not exactly \(\sqrt{2}\), but within machine precision of \(\sqrt{2}\). Therefore, we should always check negativity before taking square root.

You may notice that, in one of the above two cases, even if the answer is not "-nan", the accuracy is quite poor, only within \(10^{-8}\) of zero, rather than within machine precision of zero. This is because although \(y^2 - 2\) is within machine precision zero, after taking square root, you'll only get square root of machine precision. This is another common mistake.

So how do we take square root accurately and error free? Assume you want to compute \(x = \sqrt{2 - y^2}\), you can do something like the following

Wednesday, December 5, 2012

Determine whether an ellipse intersect a horizontal or vertical line

Assume an ellipse of width \(\sigma\) and length \(\kappa \sigma\) is centered at \((x_0, y_0)\), and has angle \(\theta_0\) with the \(x\)-axis. How do we determine whether it intersects a horizontal line or a vertical line?

It turns out the criteria is very simple
  • The ellipse intersects a horizontal line \(y = y_1\) if and only if the following equation hods: \[ \triangle_1 = \sigma^2 \left(\cos^2(\theta_0) + \kappa^2 \sin^2(\theta_0)\right) - (y_1-y_0)^2 \geq 0 \]
  • The ellipse intersects a vertical line \(x = x_1\) if and only if the following equation hods: \[ \triangle_2 = \sigma^2 \left(\sin^2(\theta_0) + \kappa^2 \cos^2(\theta_0)\right) - (x_1-x_0)^2 \geq 0 \]

Sunday, October 28, 2012

How to make vim start faster remotely

I like to use "ssh -Y" to log into my university's server to remotely submit computation jobs, and vim is my indispensible editor. However, even if vim is a command line editor, it still tries to load X server on start, and this can take a few seconds (on my MacBook Air). A simple solution is to add the following line in your ~/.bashrc (in your account at the server):


In this way, vim won't try to load X server and starts much faster.

Wednesday, May 2, 2012

How to disable page forward/backward key in Thinkpad

It's a design flaw for Thinkpad to put page forward/backward together with the arrow keys. This frequently leads to loss of unpublished posts. This is what you can do in Ubuntu to disable those two keys:
  1. Create the file ~/.Xmodmap with the following contents
    keycode 166=
    keycode 167=
    
  2. (Depending on your distribution, this step may not be necessary.) Add the following code to your ~/.profile
    # keyboard modifier
    if [ -f $HOME/.Xmodmap ]; then
        /usr/bin/xmodmap $HOME/.Xmodmap
    fi
    

Tuesday, April 17, 2012

Solve Hannoi problem using recursion or iteration

Problem:
Solve the Tower of Hanoi problem first using recursion and then using iteration.

Analysis:
The Hanoi problem is a favourite example when teaching recursion. The idea is, to move dishes 1..N from source to target, we can first move dishes 1..(N-1) from source to interm, then move the dish N from source to target, and finally we move dishes 1..(N-1) from interm to target. Thus the recursion implementation is very straightforward. To implement using iteration is a little trickier, and can be done using a stack.

Code (recursion):

Code (iteration):

Color Balls

Non-Coding Problem:
Given a bag of n balls each with a different color. Each time you pick up a pair of balls and paint both to one of their colors. What's the expected number of steps before all balls become the same color?

Analysis:
This is a problem from the "Green Cover Book". It's easy to see that we have the following transition probability.
Thus if we let \(\mu_i\) be the expected number of steps getting to one color when the bag has i distinct colors, then we have \[ \mu_i = 1 + \frac{i(i-1)}{n(n-1)} \mu_{i-1}+\left(1-\frac{i(i-1)}{n(n-1)}\right) \mu_i. \] From this we can use induction to prove that \[ \mu_i = \frac{i-1}{i} n(n-1). \] Therefore we have \[ \mu_n = (n-1)^2. \]

Thursday, April 5, 2012

How to toggle on/off touchpad in Ubuntu

Somehow touchpad inteferes a lot with typing in Ubuntu. After some experimenting, I found the following script can reliably toggle on/off the touchpad:

For thinkpad X220, we can use Fn+F8 to toggle on/off the touchpad.

I found that the best experience so far can be achieved by disabling touchpad and using keyboard+USB mouse instead.

Saturday, March 3, 2012

Install gettc on macbook

gettc is a very convenient tool for downloading TopCoder problems (description, test cases etc.) and practice offline. This post summarizes how I installed gettc on my macbook air.
  1. Mac OS X Lion ships with ruby 1.8.7, and gettc requires ruby>=1.9. So our first step is to install a newer ruby
    1. Install rvm, and use it to install new ruby. Follow the steps here
    2. Set the new ruby as default. Follow the steps here
  2. Next install prerequisites of gettc.
  3. Next install gettc. Follow the instructions here. After it's done, change the first line (location of ruby) in `which gettc`. The location of ruby can be found by `which ruby`.
  4. Set up the PATH by adding the following line to ~/.bash_profile:
  5. Modify "~/.gettc/template/solve/cpp/Makefile" to remove the option "-std=gnu++0x". Modify "~/.gettc/template/bin/runner.sh" to remove the option "-o $ostream".


Remarks:
If your machine is Ubuntu or other unix variants, and you don't have root privilege, you can use the above steps as well.

Friday, March 2, 2012

Getting used to Mac from a Windows/Linux background

Here are some tips for getting used to Mac from a Windows/Linux background. The following tips apply for the Mac OS X Lion on a Macbook Air.
  • Right click: use "control"+click instead.
  • Cut/Copy/Paste/Find: use "command"+X/C/V/F instead.
  • Home/End button
    • "control"+A for Home, and "control"+E for End works in both browsers and Terminal.
    • "fn"+Shift+left/right works in Terminal but not in browsers.
    • "command"+left/right works in browsers but not in Terminal.
    • In the Terminal, if you are using vim, you can use "^" for Home and "$" for End.
  • Select two files and all the files in between (multiple file selection): first switch from icon view to list view, and then do it in the Windows way, i.e. select the first file, press and hold "Shift" and select the last file.
  • Install the command-line-only gcc C/C++ compiler: download "Command Line Tools for Xcode" from Apple Developer Site, which is only 170M (or 280M after install).
  • Install latex: I used the basic version of MacTex and TeXShop.
    • To find a missing package, you can use ctan search.
    • To download the missing package, you can do "sudo tlmgr install [package name]".
    • To install a package manually, you can extract it into /usr/local/texlive/2011basic/texmf-local/ and then run "sudo texhash".
    • To do inverse search in TeXShop, you can use "command"+click on the pdf viewer.

Monday, February 20, 2012

How to set default screen brightness in Ubuntu 11.10

For some unknown reason, the setting in "System Settings->Screen->Brightness" is not saved in Ubuntu 11.10 of my HP laptop, and I had to adjust it manually each time when my computer starts. This has been really frustrating. Today I've finally googled a solution that works perfectly. The solution can be found here.

Thursday, February 16, 2012

How to run Mathematica in batch mode

  1. Let's say your code is saved in myscript.nb. First you have to convert it to plain text by copy and paste from Mathematica. Assume the plain text version is saved in myscript.m.
  2. Next, run the script in the terminal as follows:
    math -noprompt -script myscript.m
    

Saturday, February 11, 2012

How to write math formulas in blogger

MathJax provides an easy solution for displaying math formulas on web pages (including blogger). You can start writing blog posts with math formulas using latex syntax at blogger (blogspot) int the following two steps.
  1. At the dash board of blogger, click Layout->Add Gadget->HTML/JavaScript, and add the following code
    
    
    
    
  2. To write blog posts with math formulas, use \(..\) as delimiters for inline math symbols, and $$...$$ or \[...\] as delimiters for display style math equations.

How to enable syntax highlight for code blocks in blogger

With SyntaxHighlighter, we can easily include a block of code in blogger (blogspot).
  1. First install the javascript code in your blogger.In the Design->Layout->Add a Gadget->HTML/JavaScript, enter the following code
    
     
    
    
    
    
    
    
     
    
    
    
     
    
    
    
    
    In the above example, I've chosen to use the free hosted version. You can also download and host the javascripts yourself, as described in the author's website . In the above example, I included the following brushes: Bash, JavaScript, C++, Python and LaTeX. More supported languages can be found in here.
  2. Next, to write new posts with code blocks. You can use either the <pre> tag or the <script> tag as described here .

Tuesday, January 31, 2012

How to let Google Chrome automatically handle Java Web Start in Ubuntu

A previous post describes a way to run TopCoder Arena without launching from browsers. This post gives another way to launch Topcoder Arena in Google Chrome browser under Ubuntu. It should work for other Java Web Start applications, too.
  1. Intall the latest sun java 6 and browser plugins by following the instructions here.
  2. Set JAVA_HOME and PATH in ~/.profile. An example is the following
    export JAVA_HOME="/usr/lib/jvm/jdk1.6.0_31"
    export PATH="$JAVA_HOME/bin:$PATH"
    
  3. Install the mime type for "jnlp" files. In the terminal, type
    xdg-mime install $JAVA_HOME/jre/lib/desktop/mime/packages/x-java-jnlp-file.xml
  4. Install the desktop file for "jnlp" files. In the terminal, type
    cp $JAVA_HOME/jre/lib/desktop/applications/sun-javaws.desktop ~/.local/share/applications/
    
    And make sure it contains the following line
    Exec=javaws %u
  5. Relate the mime type and the desktop file. Add the following line to ~/.local/share/applications/mimeapps.list
    application/x-java-jnlp-file=sun-javaws.desktop
  6. Configure Google Chrome browser to open the "jnlp" files automatically after downloading. Download any jnlp file in Google Chrome browser, and select "always open files of this type" in Google Chrome.

Friday, January 6, 2012

Order of bitwise operation and ==

The following code was supposed to give the i-th bit of a 16bit integer:
However, get_ith(6, 0) gives us 1 instead of 0. Why?

It turns out that x&y==0 is interpreted as x & (y==0), which is 0 (false), thus 1 is returned instead. To fix the code, we should enclose x&y using parenthesis: if((x&y)==0). The correct code is the following:

Wednesday, December 21, 2011

How to download Topcoder problems for offline viewing

If you just want to download one single problem at a time for practice, the tool gettc is perfect for that. It takes the problem ID as input and can automatically download problem description and generate C++/Java templates. You can even run demo/system tests from within the terminal.

If you want to download multiple problems

  1. Install gettc

  2. Select your desired subset of problems from here and download the html files.

  3. Say list*.html saves the list of problems. The following steps extract the problem ID's from the html files.

    1. grep -o 'pm=[0-9]*' list*.html > tmp.txt 

    2. Edit tmp.txt using vim and keep only the problem ID's.

    3. cat tmp.txt | sort -u > list.txt 

    Now the file list.txt contains unique problem ID's.

  4. Download the problems from Topcoder using the following command.

  5. for num in `cat list.txt`; do gettc $num; done



To create an ebook for reading in Kindle

  1. Create a dir called 'tmp'

  2. Run the following command

  3. for dir in `ls`; do mkdir tmp/$dir; cp -a $dir/prob tmp/$dir/; done

  4. Change to tmp, and generate index.html using the following scripts
    echo "<ul>" > index.html
    find . | grep html | sort > tmplist.txt
    for file in `cat tmplist.txt`; do
      name=`echo $file | awk -F/ '{print $2}'`
      echo "<li><a href=\"$file\">$name</a></li>" >> index.html
    done
    echo "</ul>" >> index.html
    rm tmplist.txt

  5. Zip the directory 'tmp' and feed it to Calibre.

Tuesday, December 20, 2011

How to run Topcoder Arena from Ubuntu

Somehow Topcoder Arena does not work in chrome or firefox browsers in Ubuntu 11.10.

This is what you can do instead:
(1) Download http://www.topcoder.com/contest/classes/ContestApplet.jar to your local directory.
(2) Run the following code in a terminal.
java -cp ContestApplet.jar com.topcoder.client.contestApplet.runner.generic www.topcoder.com 5001

This method works in openjdk as well.

Update: this seems no longer working for Java 7. The ultimate solution is to configure Ubuntu/Mac etc. to open .jnlp files with javaws, similar to the instructions in this post.

Visitors