Monday, August 17, 2015

Parallel Merge Sort using Fork and Join

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;

public class MergeSortForkJoin {
    public static class MergeSortTask extends RecursiveAction {
        private static final long serialVersionUID = 1L;
        private final List<Integer> list;
        private final int lo;
        private final int hi;
        
        public MergeSortTask(List<Integer> list, int lo, int hi) {
            this.list = list;
            this.lo = lo;
            this.hi = hi;
        }
        
        @Override
        protected void compute() {
            if (lo >= hi) {
                return;
            } else {
                int mid = (lo + hi) / 2;
                MergeSortTask task1 = new MergeSortTask(list, lo, mid);
                MergeSortTask task2 = new MergeSortTask(list, mid+1, hi);

                invokeAll(task1, task2);

                merge(list, lo, mid, hi);
            }
        }
        
        private void merge(List<Integer> list, int lo, int mid, int hi) {
            List<Integer> tmp = new ArrayList<>();
            for (int i : list) {
                tmp.add(i);
            }
            int left = lo;
            int right = mid + 1;
            int idx = lo;
            while (left <= mid && right <= hi) {
                if (tmp.get(left) <= tmp.get(right)) {
                    Integer element = tmp.get(left);
                    list.set(idx, element);
                    left++;
                    idx++;
                } else {
                    Integer element = tmp.get(right);
                    list.set(idx, element);
                    right++;
                    idx++;
                }
            }
            while (left <= mid) {
                Integer element = tmp.get(left);
                list.set(idx, element);
                idx++;
                left++;
            }
            while (right <= hi) {
                Integer element = tmp.get(right);
                list.set(idx, element);
                idx++;
                right++;
            }
        }
    }
    
    public static void main(String[] args) throws Exception {
        ForkJoinPool pool = new ForkJoinPool();
        List<Integer> list = Arrays.asList(4, 9, 1, 5, 8, 0, 7, 6, 3, 2);
        System.out.println("Unsorted: " + list);
        MergeSortTask task = new MergeSortTask(list, 0, list.size()-1);
        try {
            do {
                pool.execute(task);
            } while (!task.isDone());
        } finally {
            pool.shutdown();
        }
        System.out.println("Sorted:   " + list);
    }
}

Monday, August 10, 2015

How to Organize a Go Project

The official has a good information on how to structure your Go code. In this blog, I am going to explain a little bit more about it. Let's say we want to create a Go project containing a command and a package.
workspace1/
|-- build.sh
`-- src
    `-- mylib
        |-- hello
        |   `-- hello.go (package)
        `-- main.go (command)
hello.go
package hello

import "fmt"

func SayHello() {
    fmt.Println("Hello")
}
main.go
package main

import "mylib/hello"

func main() {
    hello.SayHello()
}
build.sh
#!/bin/bash

export GOPATH=`pwd`
go install mylib/hello
go install mylib
Calling build.sh will create this structure.
workspace1/
|-- bin
|   `-- mylib (executable)
|-- build.sh
|-- pkg
|   `-- linux_amd64
|       `-- mylib
|           `-- hello.a (library)
`-- src
    `-- mylib
        |-- hello
        |   `-- hello.go (package)
        `-- main.go (command)
In order to make mylib project go-gettable, let's make it into a Git project. Take a note that we will be creating a Git project in the mylib directory and not in the workspace1 directory.
1. cd workspace1/src/mylib
2. git init
3. git add .
4. git commit -m "Initial commit"
5. Push this repository to the remote URL
Now let's create another project that uses mylib. This new project is a simple project that uses mylib.
workspace2/
|-- build.sh
`-- src
    `-- myapp
        `-- app
            `-- app.go (command)
1. cd workspace2
2. git init
3. git add submodule [mylib_git_url] src/mydomain/user/mylib (the src/mydomain/user is just a convention, you can also set the path to src/mylib)
After the submodule addition, we will have this structure.
workspace2/
|-- build.sh
`-- src
    |-- myapp
    |   `-- app
    |       `-- app.go (command)
    `-- mydomain
        `-- user
            `-- mylib
                |-- hello
                |   `-- hello.go (package)
                `-- main.go (command)
app.go
package main

import (
    "fmt"
    "mydomain/user/mylib/hello"
)

func main() {
    fmt.Println("Do something")
    hello.SayHello()
}
build.sh
#!/bin/bash

export GOPATH=`pwd`
go install mydomain/user/mylib/hello
go install myapp/app
Calling build.sh will create this structure.
workspace2/
|-- bin
|   `-- app (executable)
|-- build.sh
|-- pkg
|   `-- linux_amd64
|       `-- mydomain
|           `-- user
|               `-- mylib
|                   `-- hello.a (library)
`-- src
    |-- myapp
    |   `-- app
    |       `-- app.go (command)
    `-- mydomain
        `-- user
            `-- mylib
                |-- hello
                |   `-- hello.go (package)
                `-- main.go (command - not used)

Saturday, May 23, 2015

How to Create a Simple REST Server in Go

Below is an example on how to create a simple REST server in Go.
package main

import (
    "encoding/json"
    "log"
    "net/http"
    "strconv"
)

type Hello struct {
    Message string `json:"message"`
}

func HelloServer(w http.ResponseWriter, req *http.Request) {
    log.Println("Received a request from ", req.RemoteAddr)
    w.Header().Set("Content-Type", "application/json")
    if req.Method == "GET" {
        encoder := json.NewEncoder(w)
        hello := Hello{"Hello World"}
        encoder.Encode(hello)
    }
}

func main() {
    port := 8080
    // serve static content
    http.Handle("/", http.FileServer(http.Dir("html")))
    http.HandleFunc("/hello/", HelloServer)
    log.Println("Starting HTTP server at", port)
    err := http.ListenAndServe(":"+strconv.Itoa(port), nil)
    if err != nil {
        log.Fatal("Unable to start the server: ", err)
    }
}

Tuesday, May 5, 2015

How to Cross Compile Go Programs

If you download the Go binary for a particular platform, most likely that go binary distribution does not come with support for cross-compiling.
cd myapp
GOOS=windows GOARCH=amd64 go build

go build runtime: windows/amd64 must be bootstrapped using make.bash
In order to add support for cross-compiling in your Go distribution, you need to do the following.
cd $GOROOT/src
GOOS=windows GOARCH=amd64 ./make.bash --no-clean
In this example I am adding cross-compile support to target Windows 64-bit.
cd myapp
GOOS=windows GOARCH=amd64 go build
Now you can easily build Windows 64-bit binaries on a Linux.

Friday, December 5, 2014

How to Edit an Excel File using C# with Excel Office Interop

Below is a simple example how to edit an Excel File using C# with Excel Office Interop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelBlog
{
    class Program
    {
        static void Main(string[] args)
        {
            var xlApp = new Excel.Application();
            var xlWorkbook = xlApp.Workbooks.Open(
                @"C:\Users\Fredy\Documents\Visual Studio 2013\Projects\ExcelApp\in.xlsx");
            var xlWorksheet = xlWorkbook.Worksheets["Sheet1"];
            var fullRow = xlWorksheet.Rows.Count;
            var lastRow = xlWorksheet.Cells[fullRow, 1].End(Excel.XlDirection.xlUp).Row;
            var dict = new Dictionary<string, IList<string>>();
            for (int i = 1; i <= lastRow; i++)
            {
                var cell = xlWorksheet.Cells[i, "A"].Value;
                xlWorksheet.Cells[i, "A"].Value = cell + "" + i;
            }
            xlWorkbook.SaveAs(@"C:\Users\Fredy\Documents\Visual Studio 2013\Projects\ExcelApp\out.xlsx");
            xlWorkbook.Close();
        }
    }
}

Monday, October 6, 2014

How to Implement Policy Classes in C++

Policy-based class design is a powerful technique described in Modern C++: Generic Programming and Design Patterns Applied book. It's similar to a strategy design pattern, but with all the type-safety thanks to the use of C++ templates.

Below is a trivial example how to design a library with policy classes.

#include <iostream>
#include <string>
using namespace std;

template<class T>
struct HelloPolicy {
    static void saySomething(const T& t) {
        cout << "Hello World, " << t.getName() << endl;
    }
};

template<class T>
struct ByePolicy {
    static void saySomething(const T& t) {
        cout << "Bye World, " << t.getName() << endl;
    }
};

struct Foo {
    string getName() const {
        return "Foo";
    }
};

struct Bar {
    string getName() const {
        return "Bar";
    }
};

template<template <class> class Policy>
class FooPolicy : public Policy<Foo> {
public:
    void doSomething() {
        Foo foo;
        Policy<Foo>().saySomething(foo);
    }
};

template<template <class> class Policy>
class BarPolicy : public Policy<Bar> {
public:
    void doSomething() {
        Bar bar;
        Policy<Bar>().saySomething(bar);
    }
};

int main() {
    FooPolicy<HelloPolicy> f1;
    f1.doSomething();

    FooPolicy<ByePolicy> f2;
    f2.doSomething();

    BarPolicy<HelloPolicy> b1;
    b1.doSomething();

    BarPolicy<ByePolicy> b2;
    b2.doSomething();
    
    return 0;
 }
Output:
Hello World, Foo
Bye World, Foo
Hello World, Bar
Bye World, Bar

Tuesday, September 2, 2014

Java 8 Functional Interfaces

Java 8 has many functional interfaces as defined in the Javadoc. In this blog, I'm going to explain few important Java 8 functional interfaces.
  • Consumer<T>
    • Arguments: T
    • Returns: Void
  • Supplier<T>
    • Arguments: None
    • Returns: T
  • Function<T, R>
    • Arguments: T
    • Returns: R
  • Predicate<T>
    • Arguments: T
    • Returns: boolean
  • UnaryOperator<T>
    • Arguments: T
    • Returns: T
  • BinaryOperator<T>
    • Arguments: (T, T)
    • Returns: T
public class Java8 {
    public static void main(String[] args) {
        System.out.print("Consumer: ");
        Consumer<String> consumer = (s) -> {
            System.out.println(s);
        };
        consumer.accept("hello");

        System.out.print("Supplier: ");
        Supplier<String> supplier = () -> {
            return "foo";
        };
        System.out.println(supplier.get());
        
        System.out.print("Function: ");
        Function<Integer, String> function = (i) -> {
            return "func" + i;
        };
        System.out.println(function.apply(1));
        
        System.out.print("Predicate: ");
        Predicate<Integer> predicate = (i) -> {
            return i == 0;
        };
        System.out.println(predicate.test(0));
        
        System.out.print("UnaryOperator: ");
        UnaryOperator<Integer> unaryOperator = (i) -> {
            return i * 100;
        };
        System.out.println(unaryOperator.apply(2));
        
        System.out.print("BinaryOperator: ");
        BinaryOperator<Integer> binaryOperator = (i, j) -> {
            return i + j;
        };
        System.out.println(binaryOperator.apply(3, 5));
    }
}
Output:
Consumer: hello
Supplier: foo
Function: func1
Predicate: true
UnaryOperator: 200
BinaryOperator: 8