Saturday, October 8, 2016

How to Setup a Home Web Server on Debian Jessie

Here is how to setup a home web server on Debian Jessie.

First, install apache web server. This will serve html files.
$ sudo apt-get install -y apahce2

If you haven't configured sudo, please take a look at this post to see how to configure sudo in Debian.

Next, install php5. This will server php files.
$ sudo apt-get install -y php5 libapache2-mod-php5

Now, your default server root directory is /var/www/html. You can add your html and php files here for your server to serve.

Finally, you probably may want to serve html files that embed php code in it. To do this, you need to edit /etc/apache2/mods-enabled/php5.conf file and add the following lines:
<FilesMatch ".+\.html$">
   SetHandler application/x-httpd-php
</FilesMatch>

To reload the config file, restart the server:
$ sudo service apache2 restart

Now, create /var/www/html/test.html file with the following code:
<html>
    <body>
        <h1>HTML file with PHP Code</h1>
        <?php
        echo "This code is run by PHP server";
        ?>
    </body>
</html>

In your web browser, go to http://SERVER_IP_ADDRESS/test.html
You should see the following text if your server is properly configured:
HTML file with PHP Code
This code is run by PHP server

By the way, if you want to override the config setting with .htaccses file, you need to edit
/etc/apache2/apache2.conf file and edit to
<Directory /var/www/>
    Options FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

Enjoy your web server!


Friday, October 7, 2016

How to Enable Auto-Completion after SUDO command in Mac OS X

By default on Mac OS X system, tab-auto completion is not on when you type in sudo command. For example, if you do
$ hdiu <tab>

it will auto-complete to
$ hdiutil

However, if you were to do the same with sudo command,
$ sudo hdiu <tab>

nothing really happens. This is because the feature is not turned on by default.

To turn on the feature, simply do
$ echo "complete -cf sudo" >> ~/.bash_profile
$ . ~/.bash_profile

That's it!

Monday, October 3, 2016

Computing Max Diff

Assume you can somehow foresee stock price for, say 1000 days, from today. If you are given, say k, chances to buy and sell those stock at all different days, how would you calculate the maximum profit you could get? Assume that you can only hold max 1 share at a time, so you won't be able to buy, buy, buy, and sell, sell, sell. You will need to buy, sell, buy, sell, ... and so forth.

For example, consider the daily price to be x_i = {4005 1330 6570 4925 7112 6182 177 1843 2897 5557 8561 5875 7069 6192 4358 8624} for i=1,2,..,16. If you are given 3 chances each to buy and sell this stock at each different day, what would be the maximum profit?

One way would be to buy at x_1, x_3, x_5 while selling at x_2, x_4, x_6, but this probably won't get you the maximum profit.

This is the classical max difference problem. Let's see how we can solve this.

As with any other algorithm problem, you should start looking for some sort of recursive relationship. Define

S(n,k) = max profit you would get by buy-sell k times with the last sell at x_n.

For example, S(3,1) would be x_3 - x_2, and S(5, 2) would be x_3 - x_2 + x_5 - x_4

It is not easy to instantly find the relation between S(n,k) and S(n-1,k) or S(n,k-1) or S(n-1,k-1). We need some helper variable. Define

B(n,k) = max cash you would get by buy-sell k-1 times before x_n, and buying kth time at x_n.

For example, B(1,1) would be -x_1, which is the only option. B(2,1) would be -x_2, and B(6,3) would be  x_3 - x_2 + x_5 - x_4 - x_6.

Now, we see the recursive relation between B and S:

B(n,k) = max[S(i, k-1)] - x_n for i<n
S(n,k) = max[B(i,k)] + x_n for i<n

OK, does that mean we need to store B and S 2D-arrays and find max for each (n,k)? Well, one way to avoid this is to instead store maxB and maxS 2D-arrays and store the max value up to n. For example, maxB[n][k] will be the max of B(1,k) through B(n,k).

The following is the source code for this.


Note that this requires O(n*k) space, which could be quite a lot. To reduce this, notice how maxB[i][k] and maxS[i][k] are of no usage for n>i+1. Therefore, at the end of each loop in n, we can update maxS and maxB and overwrite. In this way, we can store maxB[k] and maxS[k] 1-D arrays.

The following is the source code for this.


There is one little catch here though. We must loop through k in descending order, so that getS and getB functions access maxS and maxB from the previous loop in n, not the newly updated in the current loop in n.

Saturday, October 1, 2016

How to Reverse Mouse Scroll Direction in Debian and Ubuntu

This post is based on here.

To reverse mouse scroll direction, in case you like natural scrolling direction, edit /usr/share/X11/xorg.conf.d/10-evdev.conf file and add the line highlighted in green:
...
Section "InputClass"
        Identifier "evdev pointer catchall"
        MatchIsPointer "on"
        MatchDevicePath "/dev/input/event*"
        Option "ButtonMapping" "1 2 3 5 4 6 7 8"
        Driver "evdev"
EndSection
...

Restart X11 to take effect!

Thursday, September 29, 2016

Three Minutes Daily Vim Tip: Tab Completion

If you want to enable tab-completion feature in vim, just like terminal, here is what you can do.

$ echo "set wildmode=longest,list,full" >> ~/.vimrc
$ echo "set wildmenu" >> ~/.vimrc

Now, when you are opening a new file, use tab key to see the files in the folder:
:e <tab>

Thursday, September 22, 2016

Lazy Initialization Algorithm

This post presents my own understanding and analysis of lazy initialization algorithm explained in the book Elements of Programming Interviews, Chapter 6.

Say you are writing a program to manage memory and its initialization. When a user asks for a very large chunk of memory, say 1GB of size, and initialize all this big chuck of memory to some value, you are worried that it will take too long time to write out to the big block of memory address by address.

Is there any way to avoid brute-force initialization of the memory? Here is one way to avoid it and trick the user into believing as if the memory has been initialized without actually doing it.

1. If the user asks to read the value at specific address, you can first check whether that address has ever been written to since allocation of the memory (how? read on). If so, read the value at that address and return as requested. If not, don't even bother reading the value at that address---it will be just some garbage anyway as it is not initialized---and return what it should have been initialized to.

2. If the user asks to write some value at specific address, again check whether the address has been ever written to (how? read on). If so, just write out the value as requested to that address. If not, mark that location for "has been written" (how? read on) and write out the value as requested.

OK, you would agree that the scenario above makes sense, but there is one problem. How would you implement a method to mark which memory addresses have been written to?

The simplest method I can think of is to maintain a Boolean table for each address and mark, say 0 for not-written and 1 for written. Well, one problem with this method is that it requires initialization on its own, as you would have to start off with all-zero table, so it kind of defeats the whole purpose.

The second method is to store all the addresses where data have been written to in a hash table. The thing is that we do not know a priori the specific patterns of write addresses, so we may need to rehash often to spread out.

Finally, here is the alternative method to those mentioned above. I do not claim that this method is the best, as each implementation has its own pros and cons. I thought that this implementation is very clever that I should share.

Say the user asks for memory allocation for n elements with initialization. We then allocate (but not initialize) two more chunks of memory for n unsigned integers for indexes. The first will be called P, which will keep track of the number of indices thus far written to, which is maintained by a counter, say t. Another array will be called S, which will hold the index of write operation.

For each first-time write to index i, we write the counter value t into P[i] and write the index value i into S[P[i]], and increment the counter. To determine whether memory at index j has been written, first examine P[j] to see if it is between 0 to t-1. If so, it is likely that it has been written already. To verify with certainty, we double check to see if S[P[j]] is indeed j. If this holds, then it must be the case that this specific address has been already written. Otherwise, the address has not been written yet.

For better understanding, here is the actual code:


template <typename T>
class LazyArray {
private:
  unsigned size;
  T* A;
  unsigned *P;
  unsigned *S;
  unsigned t;
  T initVal;
  bool isWritten(unsigned idx) {
    if (P[idx] >= 0 && P[idx] < t)
      if (S[P[idx]] == idx)
        return true;
    return false;
  }

public:
  LazyArray(unsigned n, T initVal) {
    size = n;
    A = new T[n];
    P = new unsigned[2*n];
    S = &P[n];
    this->initVal = initVal;
    t = 0;
  }
  LazyArray(LazyArray &that) {
  }
  LazyArray& operator= (LazyArray& that) {
  }
  ~LazyArray() {
    delete[] A;
    delete[] P;
  }

  bool read(unsigned idx, T *pval) {
    if (idx<0 || idx>=size)
      return false;
    if (isWritten(idx))
      *pval = A[idx];
    else
      *pval = initVal;
    return true;
  }

  bool write(unsigned idx, T val) {
    if (idx<0 || idx>=size)
      return false;
    A[idx] = val;
    if (!isWritten(idx)) {
      P[idx] = t++;
      S[P[idx]] = idx;
    }
    return true;
  }

};


Russian Peasants Multiplication Algorithm

Here is a cool algorithm that calculates multiplication by addition and bit-shifting only. This method is exponentially faster than the literal implantation of multiplication in which x is added y times.



int multiply (unsigned x, unsigned y) {
  unsigned a,b;
  unsigned c = 0;
  // make sure a < b so that we add b a times
  if (x<y) {
    a = x;
    b = y;
  } else {
    a = y;
    b = x;
  }

  while (a > 0) {
    if (a & 1)
      c += b;
    a >>= 1;
    b <<= 1;
  }

  return c;
}

To prove that it works, consider the function
f(a,b,c) = ab + c
before the loop, during the loop, and after the loop.

Before the loop, we have
f = xy + 0 = xy

During the loop, we have for even a,
a' = a/2
b' = 2b
c' = c
f' = ab + c = xy

and for odd a,
a' = (a-1)/2
b' = 2b
c' = c + b
f' = ab + c = xy

Hence, it must be the case that f(a,b,c) = xy for any number of iterations in the loop by induction. Now, the ending condition of the loop yields a = 0, so it must be the case that
c = f - ab = f = xy

In other words, the return value is guaranteed to be the product of the input x and y!

Dutch National Flag Problem

Here is a very clever algorithm that I want to share. It is one solution to Dutch National Flag Problem, where an array of input is to be sorted into three partitions: one with those smaller than a given pivot, another one equal to the pivot, and the rest greater than the pivot.

For example, given input array 5 4 3 2 1 1 2 3 4 5 and pivot value, say 3, the output should be something like:
1 2 2 1 3 3 4 5 4 5

The following is the code:


// LIST: input array
// SIZE: # of elements in the array
// IDX: the index of the pivot
void dutchFlag (int *list, int size, int idx) {
  int pivot = list[idx];
  // The list will be partitioned into four as below:
  // bottom: [0, equal-1]
  // middle: [equal, current-1]
  // unclas: [current, large-1]
  // top   : [large, end]
  int equal, current, large;
  equal = current = 0;
  large = size;

  while (current < large) {
    int val = list[current];
    if (val < pivot) {
      swap(&list[equal], &list[current]);
      current++;
      equal++;
    } else if (val == pivot) {
      current++;
    } else {
      swap(&list[large-1], &list[current]);
      large--;
    }
  }
}

void swap (int *x, int *y) {
  int temp = *x;
  *x = *y;
  *y = temp;
}
Very cool!

Wednesday, September 21, 2016

Colorize GCC Output

To colorize GCC output, insert the following line into ~/.bashrc file:
export GCC_COLORS="error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01"

Now, load ~/.bashrc file and you are set!
$ . ~/.bashrc

For more info, refer here.

Tuesday, September 20, 2016

Binary Greatest Common Divisor Finder

While studying for coding interviews, I came up with a very neat example that I want to share with everyone. The question is to code a program that finds the greatest common divisor given two positive integers without invoking multiplication, division, and modulus operators.

The easiest way perhaps is to use Euclidean algorithm but that is just too slow. So, the following is a bit faster algorithm called binary GCD:

int binaryGCD(int a, int b) {
  if (a==b)
    return a;
  if (a==0)
    return b;
  if (b==0)
    return a;

  // divide a and b by 2 until they become both odd numbers
  int p2a, p2b;
  p2a = p2b = 0;
  while ((a&1) == 0) {
    p2a++;
    a >>= 1;
  }
  while ((b&1) == 0) {
    p2b++;
    b >>= 1;
  }
  int minpower = p2a < p2b ? p2a : p2b;

  if (a>b)
    return binaryGCD((a-b)>>1, b) << minpower;
  else
    return binaryGCD((b-a)>>1, a) << minpower;
}

The code above is my variant of binary gcd found in here. It is a bit harder to read but perhaps a bit faster though.