Author Archives: Han Lai

sails.js how to use handlebars, and also register helpers for global use

Sails.js is a very good MVC type server solution, it quickly generate restful api and can also respond to CRUD request. However it by default only supports ejs template.

There are many solutions to change it so that it also support handlebars template. Then if you have index.handlebar file in the View folder, it would recognize it.

However I have been searching for a while about is the helper and partial. Handlebars comes with registerHelper function and registerPartial function, which create partial and helper that you can use globally in every *.handlebar file.

For example
handlebars registerHelper('script',function(data,option){
return <script src="/public/css/+data+">;

Then in your template you simply put
{{script "mydesign.css"}}

In the webpage it will generate
<script src="/public/css/mydesign">

This is very convinient, but I couldn't find where to register this global helper. There are only options to pass it in as local helper.

Finally I found out how to do it, so here it is:
1. create a helper.js in the /config/ folder.
2. the handlebars object is stored in
var handlebars=require('sails/node_modules/express-handlebars/node_modules/handlebars');
3. register helpers on this handlebars object.

Clash of clans, how to stay online forever

The idea of keeping COC online is to connect an iphone to a computer, and let the computer keep clicking it. So there are couple of softwares needed.
A computer runs windows, and a jailbroken iphone that you can leave it running. (not your daily using iphone).

1. jailbreak your iphone and install veency from cydia. This program allows your iphone to be remotely connected and controlled by PC. Then in settings setup a password for this. (this is necessary. without password, everytime PC connect to it, there are popups and hard to manage).

2. Download iFunbox(, this program allows your PC to establish a secure local network tunnle with iphone when iphone is connected via usb cable. After iphone is connected to PC, open iFunbox, and in Quick Toolbox, click on “USB Tunnel”, it should create a 5900VNC tunnle. (make sure it’s 5900) if it’s 5901 just reopen iFunbox and reestablish the tunnle.

3. Now you need a VNC software on your PC to connect to iphone. In my experience, some VNC client tends to disconnect after a while. but this VNC-Viewer does not. (It is included in the zip file).
4. Now you need some automatic software on your PC to keep doing clicking or some sort. So download autohotkey ( and use the test-iphone4.ahk script. (make sure this file is in same directory as VNC-Viewer).
5. The script is pretty simple and self explanatory. For every few minites, (before COC kick you out for no movement), it will right click(which is same as home button), then put mouse in a position and left click, then repeat. I found if it does re-enter the game so fast, the system won’t recongnize it as an action, but if you quickly quit and join two times, it does. So you can double click the script and see where the mouse clicks. Then move your COC icon to that location on FIRST PAGE of your iphone.(This is important). Then double click the script. To cancel the script, just press ESC.

Download link

Write large files in java

One thing many people forget is that string concatenation is a polynomial time process. (O(n^2)).
Because every time it extends some characters, a new string is created and the original string and the extending characters are copied over.

In some programs, people try to write large arrays of data in to file, and to make it simple, they use a String variable to contain all the data, then write to a file. But the problem is, you have to loop through the array and adding each element to the string, this will take significantly more time than just using a BufferedWriter and just keep writing to it.

Clash of clan: How is this game a life sucking app?

After playing this game for a while, I starting to think.. hmm how long does it to take me to reach the ultimate fully upgrade base.

So I pulled out the csv file from the game, and did a little spread sheet calculations.

Turns out, it will take over a year to upgrade everything( except for the walls). (assuming you have 4 builders and always building stuff).Which is ok, but think about how much gold you have to rob per day to keep all your builders in use.

Here is the link for the spread sheet.


There are 7 sheets in the google doc. Don't worry about the first 6 sheets. Only go to the
"Summary" sheet. and enter the current level of each of your buildings, also the current level of your troops, the current level of your heroes. Then on the right side of the sheet, you will see a summary of your status.

To be encouraged, or to be discouraged, it is totally up to you. lol

Malloc and free. C programming tips

In C programming, we usually have to define a lot of customized structs, they work similar to classes but without the methods.

Usually to construct a struct, we have the following

struct xyz {
int a;
int b;

Then when you use it, you have to do

struct xyz * apointer= malloc(sizeof(struct xyz));

To simplify the code, we use

typedef struct xyz * xyz

This way, we don't have to type "struct xyz *" every time, but simply use a "xyz".

Problem usually happen when you try to free the memory. After you are done with this struct.
Then you free the memory that "apointer" points to by using free(apointer)

Many times people will get a "invalid size", or "invalid address" error when they try to free the memory and get very confused. I found it very often that this happens very often with one case. So I point it out to remind myself.
xyz curPointer=malloc(sizeof(xyz));

This means you are only malloc enough space for a xyz pointer!, which is only 8 byte( or 4 byte). You should use
xyz curPointer=malloc(sizeof(struct xyz));

This is very important!
If you did not "malloc" enough space for one struct and write more bytes into the space. You'll overwrite the memory space adjacent to it. (C does not check for this when it writes to this location exceed the malloc space). When you try to free the next memory block, it will not understand what to free, because this block was overwritten.

Suppose you have block A and B adjacent to each other. A is 8 byte, B is also 8 byte.

Then you write 9 bytes to A, and then try to free B. You'll get the error I was talking about.

What is Random

A big concept in statistics is randomness. Rolling a fair dice, or throwing a quarter, picking a sample from a population, sampling from some distribution. These behaviors all involved some randomness.

Very often, you can see a question like this: what's the probability of throwing a fair (50/50) quarter and you get heads? This is based on the assumption that throwing this quarter, this quarter will land randomly.

However, it is very tricky to think about this concept. Why would there be random? If you think really deep( not saying I can think deeper than you), every random behavior can be explained to be a deterministic behavior, and can be monitored and predicted, if, the power of computing is good enough, and power of measuring is accurate enough.

For example, throwing a quarter. There are many factors that involved with the quarter show head or tail after it land, such as: air flow speed, direction, landing angle, throwing angle, landing material, and so on. These things can all affect the result.

However, can we actually measure the air flow, throwing angle, and all these factors? This answer is quite difficult. Let's imagine that the air flow direction is the only factor affect result, the air is left and right.(which obviously is not the case), then when we throw quarter 100 times and 50 heads. It does not mean the coin itself is a fair coin, it can also be explained as the coin is not a fair coin, but the air flow direction somehow compensated the bias.

Therefore, I believe that in a reduced factor scenario, where there is no air and the quarter is dropped the same way many times, then every time the quarter should show the same side.

I believe it is very important to realize that everything in the world is in fact deterministic, we use probabilistic models is because there are so many factors that we have no idea how to capture. And remember "air flow direction" when you make a statement of a quarter's fairness.

Tree and Tree node implementation

A tree is a very useful structure, many people like to use

class TreeNode{
E nodeData;
TreeNode child1;
TreeNode child2;

to represent nodes in a tree, I find it complicated and hoping to get create a way such that tree nodes can be any class that implement a TreeNode class. For example, anytime you try to get the child or parent, you'll have to throw away this wrapper of TreeNode. The code in my mind to use the node would be as easy as
class employee implements TreeNode{
Then we can use
employee e1= new employee();
employee e2= new employee();

But this bring up a problem. The tree node function such as, getChildren, getParent, getDecendants, they should be inherited instead of re-declared in each of the subclass that implements TreeNode.
So a better way is to use abstract class instead of interface.
public abstract class Treenode<T extends Treenode<T>> {
T next;
T myself=(T) this;
T parent;
public void addChild(T node) {
public T getChild() {
return next;
public T getParent(){
return parent;

The logic here is that any class that extends this Treenode class will automatically get the following functions without reprogramming them. The ugly part of this snippet is the T myself=(T) this;. Here the "this" is considered to be any Treenode, but myself is considered to be the subclass that extends it. This have to be a cast, but I can't see any reason such a cast could fail. Unless
class class1 extends Treenode{};
class class2 extends Treenode{};

Then for some reason you want

class1 c=new class1();
c.add(new class2());

This should not happen as a strongly typed programming practice. Period.

Windows Service Start up

Visual Studio 2010 has a very nice template for creating a windows service. It's fairly simple to just create it.

Click here to see tutorial on how to create and install a windows service.

Because a windows service cannot be running inside visual studio, it has to be running in a windows service management, therefore the service cannot be debugged in Visual Studio. The alternative option here is to attach a debugger on the service that is running.

Click here to see tutorial on how to attach a debugger on the service.

Few things to note is: The service is not viewable in the processes dialog box if it is not started. Which means you cannot attach your debugger unless you started the service. When the service start, it executes the Onstart() method. Once it started executing that method, you can see it in the process dialog box and attach debugger.

But what if you want to debug the Onstart() method?

You can use System.Threading, and use the static method Thread.sleep(x milisec); Make the service start wait for 1o sec, and attach the debugger during that 10 sec. But here comes another trick, the service management only gives arround 30-40 sec for the Onstart() to execute. If Onstart() takes too long, then error message appears saying your service is not responding. So the longer  you wait, the less time you give Onstart() to execute.


This method does NOT mean after Onstart(), it will be executed. This method is only called after the service is paused and resumed.

A general structure of a service should be,

Onstart: Use threading, generate thread to start any processes. Do not put the process here, Onstart has very limited time to start!

OnStop: interrupt the thread, disable any thread, or timer. and dispose.