AutoResetEvent

Suppose we have following code and we are required to print “foo” and “bar” alternately. Each of method foo and bar will be running on different thread.

    class Program
    {
        static void Main(string[] args)
        {
            FooBar fooBar = new FooBar(5);

            var taskFoo = Task.Run(() => fooBar.Foo(() => Console.WriteLine("foo")));
            var taskBar = Task.Run(() => fooBar.Bar(() => Console.WriteLine("bar")));

            Task.WaitAll(taskFoo, taskBar);
            Console.WriteLine("All threads are complete");
        }
    }

    public class FooBar
    {
        private int n;

        public FooBar(int n)
        {
            this.n = n;
        }

        public void Foo(Action printFoo)
        {

            for (int i = 0; i < n; i++)
            {
                printFoo();
            }
        }

        public void Bar(Action printBar)
        {

            for (int i = 0; i < n; i++)
            {
                printBar();
            }
        }
    }

There are some synchronization techniques that can be used, such as: Semaphore, ManualResetEvent, or AutoResetEvent.

In this case, we will use AutoResetEvent. Then above code will be as below:

public class FooBar
    {
        AutoResetEvent _blockThread1 = new AutoResetEvent(false);
        AutoResetEvent _blockThread2 = new AutoResetEvent(true);

        private int n;

        public FooBar(int n)
        {
            this.n = n;
        }

        public void Foo(Action printFoo)
        {

            for (int i = 0; i < n; i++)
            {
                _blockThread2.WaitOne();

                printFoo();

                _blockThread1.Set();
            }
        }

        public void Bar(Action printBar)
        {

            for (int i = 0; i < n; i++)
            {
                _blockThread1.WaitOne();

                printBar();

                _blockThread2.Set();
            }
        }
    }

Because we initialize AutoResetEvent constructor to be “true”, then the thread that is waiting will be signaled to run the thread. Thus it will allow “Foo” to be printed first. After printing “Foo”, it will execute _blockThread1.Set() that will signal _blockThread1 to run a thread to print “Bar”. After printing “Bar”, it will signal _blockThread2 that is waiting to run. It will happen so on until all the threads finish printing “Foo” and “Bar” alternately.

If you are interested with the code, you can find on my github.

Strategy Design Pattern

In this article, i would like to give example of strategy design pattern implementation. This pattern belongs to  Behavioral Patterns. The idea of this pattern is that the client can change the behavior of algorithm at running time with the one that is still in the same family.

Case:
We want to create performance benchmark of different sorting algorithm. Thus, we must be able to supply the algorithm interchangeably.

using System;
using System.Collections.Generic;

namespace StrategyPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = CreateLongList();

            SortingStrategy sortedStrategy = new SortingStrategy();

            sortedStrategy.SortingAlgorithm = new SelectionSort();
            sortedStrategy.List = new List(list);
            sortedStrategy.Sort();

            sortedStrategy.SortingAlgorithm = new QuickSort();
            sortedStrategy.List = new List(list);
            sortedStrategy.Sort();
        }

        private static List CreateLongList()
        {
            List list = new List();

            Random random = new Random();
            for (int i = 0; i < 50000; i++)
            {
                list.Add(random.Next(1, 50000));
            }

            return list;
        }
    }

    internal interface ISortingAlgorithm
    {
        void Sort(List list);
    }

    internal class SelectionSort : ISortingAlgorithm
    {
        public void Sort(List list)
        {
            int n = list.Count;

            for (int i = 0; i < n - 1; i++)
            {
                int minIdx = i;
                for (int j = i + 1; j < n; j++)
                    if (list[j] < list[minIdx])
                        minIdx = j;

                int temp = list[minIdx];
                list[minIdx] = list[i];
                list[i] = temp;
            }
        }

        public override string ToString()
        {
            return "Selection Sort Algorithm";
        }
    }

    internal class QuickSort : ISortingAlgorithm
    {
        public void Sort(List list)
        {
            Sort(list, 0, list.Count - 1);
        }

        private void Sort(List list, int low, int high)
        {
            if (low < high)
            {
                int pi = Partition(list, low, high);

                Sort(list, low, pi - 1);
                Sort(list, pi + 1, high);
            }
        }

        private int Partition(List list, int low, int high)
        {
            int pivot = list[high];

            int i = (low - 1);
            for (int j = low; j < high; j++)
            {
                if (list[j] <= pivot)
                {
                    i++;

                    int temp = list[i];
                    list[i] = list[j];
                    list[j] = temp;
                }
            }

            int temp1 = list[i + 1];
            list[i + 1] = list[high];
            list[high] = temp1;

            return i + 1;
        }

        public override string ToString()
        {
            return "Quick Sort Algorithm";
        }
    }

    internal class SortingStrategy
    {
        public List List { get; set; }
        public ISortingAlgorithm SortingAlgorithm { get; set; }

        internal void Sort()
        {
            var watch = System.Diagnostics.Stopwatch.StartNew();

            this.SortingAlgorithm.Sort(List);

            watch.Stop();
            Console.WriteLine(SortingAlgorithm.ToString() + " Running time: " + watch.ElapsedMilliseconds + " Milliseconds");
        }
    }
}

In this code, we provide two implementations of sorting algorithm which are selection sort and quick sort. Theoretically, quick sort is the most efficient algorithm for sorting. We can add more algorithm by implementing ISortingAlgorithm or alternatively we can use abstract class or inheritance. By using Interface or Abstract class, we are allowed to change the algorithm.

The code is also added with stopwatch that is used to measure the running time of each algorithm.

I got this result running in my computer:
Selection Sort Algorithm Running Time: 9746 milliseconds
Quick Sort Algorithm Running Time: 15 milliseconds

Stopwatch

Certainly, the result is in accordance to the theory.

For those interested to the actual code, you can grab from here. Let me know for any feedback regarding the implementation.

Behavior Lesson Learned

Someone who is competent in specific skills might be compelled to show off his or her skills to the extent of being pedantic. This behavior could be annoying if they don’t master the topic. It’s better to be straightforward by admitting their ignorance rather than pretending to master or in other word smart aleck.

This kind of people when being asked will behave as if he or she does know the solution. By offering some solutions and speaks vaguely but at the end of the day, none of solutions found. They are too proud to admit.

Not all people are expert in many fields. If one cannot give answer, it should not diminish their reputation provided person who ask is prudent enough.

Create Primary Key Using Alter Table Statement in Oracle

In my current company, besides SQL Server we also use Oracle. In terms of features and syntax, there is no significant difference between these two DBMS. For example, when we want to add primary key to existing database, we can use this Oracle PL/SQL command:

ALTER TABLE table_name 
ADD CONSTRAINT constraint_name PRIMARY KEY (column1, column2, ..., column_n);

As a side note, you cannot run this command if your existing data still contain duplication on the primary key. Thus, you must remove them first.

Git: Move Uncommitted Work to New Branch

Before we start making a change, chance is high that we are still in our master branch because this is the most current one. What if while debugging, we happen to change the code in this branch then realize it should be made in new branch. The solution is to run this command:

git checkout -b new_branch

This will bring all the changes to new branch. After this, it is easy to undo the changes that is already created in master later on.

Indonesian Youth Smoking Phenomena

I observe urban lifestyle in Indonesia where there are many youths who smoke casually. I am sure this has happened quite a while, but what astound me is the fact i see more women smoke. This means smoking is now prevalent. Though smoking does not reflect morality, but i get an impression that they try to copy popular culture that usually refers to western culture.

The thing is i have never seen that in countries where western culture is very dominant like Singapore arguably. In this country, smoking is very restricted and i feel that by design they are ostracized perhaps because the state considers it unhealthy. Even in country that set the standard like US, i never see they do it so lightly when they are hanging out. By the way I just watch the videos from web sites and i think the generalization is enough because the value is supposed to be the same. In contrast, in Indonesia whenever they get together they always involve smokes. They do it while dancing and hugging with their friends. Out there, liquor is the norm but not smoke.

I write this because i am basically not comfortable with smokes and living abroad makes me aware of this issue. I will definitely agree any measures taken to alleviate it by states. I am not trying to overly compare Indonesia with those countries mentioned since they have different norms, but for the well-being i believe the value applies globally regardless the society.

Individuals and Government Work Hand-in-Hand on Global Climate Change

In order to prevent global climate change, it is argued that individuals and governments as well as businesses play a part together. I agree with this opinion, since actions from one party would not be possible without support from the others.

We all know that government is a party that impose the law. They can reinforce all related stakeholder by giving reward and punishment. Nowadays, some governments has implemented policy that is environmental friendly. There are several common policies that i really notice according to my experience. The first is providing designated trash bin. Commonly there are two kind of trash bins which are recycled and non-recycled bin. Further, those can be broken down, for instance, the recycled one has different bin for plastic and can respectively. The second policy is to add additional charge for the usage of plastic bag in every store by collaborating with the business. There is also other policy which is the mass production of low emission transportation means. However, only few countries has implemented this since this policy requires high cost.

In order to succeed those policies, it depends on the individuals. Being provided with different kind of bins, we can easily sort out our rubbish and prevent us mixing them. While if people still litter, than they can get fined as the punishment. As for the plastic bag, the charge will encourage people to bring their own bags thus it will reduce the amount of recycled trash. Then, regarding the third policy, it is now become a positive lifestyle. Even though the price is still expensive, people now has motivation to buy low-carbon car as their private vehicle.

Based on explanations above, we can conclude that all the policies is aimed to individual. The government acts as regulation provider in collaboration with the business. Meanwhile, individual is the subject who will succeed government’s program. Thus, it is impossible to only rely on either of them.

Trip to Johor

Two days ago, i traveled to Johor. That was my first time visiting Malaysia. I went with my two friends which was actually not in my plan. Knowing that last Saturday is a holiday in Indonesia, i had requested ferry ticket to Singapore before i took long leave just in case i wanted to spend that holiday in Singapore.

Even though there are many options to Johor but we pick going by SMRT. I didn’t know why exactly but that’s what we had in our mind. Maybe that’s the cheapest route despite the longer time needed. The trip began after arriving at HarbourFront Centre Singapore, we continue our journey by SMRT Train and stop at Woodlands Station. From there, we picked SMRT bus 950 that would stop at Malaysia Custom to check-in then resume our journey with the same bus to our endpoint which was JB Sentral. This place is connected to JB City Square Mall where Doraemon expo was being held.

The expo would end on 4 January and had been started since 30 August, if i remember correctly. To enter the expo, we must pay 25 RM for adults. The expo is named Doraemon Secret Gadget Expo. The same expo was also exhibited in Indonesia (Jakarta). There we took pictures with Doraemon and his gadget or other characters/items with each peculiar setting like 3 grey pipes in the yard where Nobite and friends usually play. We also bought some items as souvenir.

Next we were starving and tired thus we ate at KFC after confused at which stall we should had a lunch. Two of us, including me, ate 1 set of meal consists of 3 chicken 1 salad 1 mashed potato and 1 pepsi. That’s enough to make us full even my friend must wrap 1 chicken to take away because of too full.

Lastly we return but this time with different SMRT bus which is 170 that stop at Kranji. It’s little bit farther but in JB Sentral we didn’t find 950. From Kranji, we took same train that would transit at Dhoby Ghaut then continue to HarbourFront.

To conclude, I finally travel to Malaysia and gain one more stamp on my passport. We spent more time on the trip rather than in the expo nonetheless the travel experience was what i looked for actually.

Borussia Dortmund Champions League Tale

Dortmund was drawn to face Juventus in Champions League last 16. This will be classic match recalling their meet in Champions League Final 1997 in which Dortmund won 3-1. People argue that it will be an even match considering Dortmund accomplishment in CL in recent years but struggling in Bundesliga and Juventus reign in Serie-A but never good enough in CL recently.

I am not favoring which one will win, but I am very concerned to Dortmund because they must cope hardly between Bundesliga and CL. In Bundesliga, they are now in relegation zone which is far away from CL Zone. Rather than thinking how to secure CL spot for next year, they’d better to put up to get out from relegation zone. It’s ironic knowing they are a finalist and semifinalist consecutively in the last two year but next year they would be in second division of German League.

Perhaps they think they will be granted one spot by winning CL this year. It makes sense considering similar case happen to Liverpool in 2005-2006 when Liverpool is the title holder and on fifth place. Ever since then, the title holder is guaranteed to qualify for next year.

However, the big question is can they win it? I’m not sure since there are many top contenders this season despite their brilliance in CL. Let’s say they can get through Juventus, but eventually they will face stronger team like Real Madrid, Bayern Munich, Chelsea, etc. which are more favored even though it’s incredible if they can become the champion.

If i were Juergen Klopp, realistically i would prioritize to avoid relegation and fight for CL zone. Definitely, i don’t want to fail in CL yet in the meantime being relegated.