Wednesday, February 28, 2018

GUI for Delve Debugger Gdlv

What is Gdlv?
Gdlv is a graphical interface to Delve for Linux, Windows and macOS. Previously, I posted Delve debugger in console mode Debugging Go programs with Delve 
and now, I would like to introduce the graphical delve debugger.


Implementation
First make sure you have the latest version of delve installed:
go get -u github.com/derekparker/delve/cmd/dlv

then install gdlv:
go get -u github.com/aarzilli/gdlv

To start gdlv can be done by opening command prompt (cmd) then type command
gdlv debug main.go
and it will show GUI of delve debugger as shown as below



You can open other new window by clicking drop down box for example Globals window, Sources window, etc
 

Now, let us add break-point at line 7 by using command break main.go:7 shown as picture below. You can add break-point too by right click the line code and Set breakpoint.
To clear break-point, can be done by right click and select Clear breakpoint.


By opening new window sources then find your file source code by typing the filename. In my case, the filename is main.go and double click to open the file. You will see the break-point at line 6 and 7.


Type command continue and debugger will stop at line 6


 By giving command next, it will go to next break point.
 Command in Gdlv is the same command with Dlv.

Thank you





Other topics:










Debugging Go programs with Delve

What is Delve?
Delve aims to be a very simple and powerful tool, but can be confusing if you are not used to using a source level debugger in a compiled language. Tracking down bugs in your code can be a very frustrating experience. This is even more true of highly parallel code. Having a good debugger at your disposal can make all the difference when it comes to tracking down a difficult, or hand to reproduce bug in your code.


Implementation
I am using go version  go1.8 windows/amd64. (Delve debugger can run in Linux, Windows and macOS.

Let's create a simple code in golang to demonstrate Delve debugger. The code shown as below:

filename: main.go
package main

import "fmt"

func main() {
    fmt.Println("Hello World")
    fmt.Println("Hello World")
    fmt.Println("Hello World")
}


Open your windows command prompt to perform Delve debugger by pressing  Windows Key + R and type cmd then press enter. In command prompt, type command
dlv debug main.go


Then you will enter to dlv debug mode


to check delve command you can type help and it will shown all command that can be used for debugging


Let's add break-point at line 6 by using command
break main.go:6
add break-point at line 7 by using command
break main.go:7
Then you can start debug by using command
continue
and it will stop at break-point line 6

if you want to continue to the next break point, just using command
next
and it will go to the next break-point line 7




You can see the break-point with simbol  => (blue color)   it's in yellow box
command is in red box and output is in green box, shown as picture below



I think that's all. Thank you


Other topics:




Thursday, February 22, 2018

Implementing wxWidgets in Golang (wxGo)

What is wxWidgets?
wxWidgets is a C++ library that lets developers create applications for Windows, Mac OS X, Linux and other platforms with a single code base. wxWidgets gives applications a truly native look and feel because it uses the platform's native API rather than emulating the GUI. It's also extensive, free, open-source and mature.


Installation Guide for Windows
- go version go1.8 windows/amd64
- mingw-w64 or tdm-gcc 5
- add your GO path and TDM-GCC path into your environment variable
- From command prompt execute:
      go get -x github.com/dontpanic92/wxGo/wx
  this step will need extra time to finish


Implementation

1. Hello World 

package main

import "github.com/dontpanic92/wxGo/wx"

func main() {
    wx.NewApp()
    f := wx.NewDialog(wx.NullWindow, -1, "Hello World")
    f.ShowModal()
    f.Destroy()
}


Result:




2. AUI Example

import "github.com/dontpanic92/wxGo/wx"

type MyFrame struct {
    wx.Frame
    auiManager wx.AuiManager
    menuBar wx.MenuBar
}

const (
    ID_Settings = iota + wx.ID_HIGHEST + 1
    ID_SampleItem
)

func NewMyFrame() *MyFrame {
    self := &MyFrame{}
    self.Frame = wx.NewFrame(wx.NullWindow, wx.ID_ANY, "AUI Example")

    // AUI Init

    self.auiManager = wx.NewAuiManager()
    self.auiManager.SetManagedWindow(self)

    // We should call auiManager.UnInit() in frame's desructor, but unfortunately
    // we can't get a callback when frame's destructor called. So we do this in the
    // EVT_CLOSE_WINDOW. And also because we listen the CloseEvent, we have to call
    // Destroy() manually.
    wx.Bind(self, wx.EVT_CLOSE_WINDOW, func(e wx.Event){
        self.auiManager.UnInit()
        self.Destroy()
    }, self.GetId())

    // Menu

    self.menuBar = wx.NewMenuBar()
    fileMenu := wx.NewMenu()
    fileMenu.Append(wx.ID_EXIT)

    wx.Bind(self, wx.EVT_MENU, func(e wx.Event){
        self.Close(true)
    }, wx.ID_EXIT)

    self.menuBar.Append(fileMenu, "&File")
    self.SetMenuBar(self.menuBar)

    // StatusBar

    self.CreateStatusBar()
    self.GetStatusBar().SetStatusText("Ready")

    // AuiToolBar

    toolBar1 := wx.NewAuiToolBar(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.AUI_TB_DEFAULT_STYLE | wx.AUI_TB_OVERFLOW)
    toolBar1.SetToolBitmapSize(wx.NewSizeT(48,48))

    toolBar1.AddTool(ID_SampleItem + 1, "Test", wx.ArtProviderGetBitmap(wx.ART_ERROR))
    toolBar1.AddSeparator()
    toolBar1.AddTool(ID_SampleItem + 2, "Test", wx.ArtProviderGetBitmap(wx.ART_QUESTION))
    toolBar1.AddTool(ID_SampleItem + 3, "Test", wx.ArtProviderGetBitmap(wx.ART_INFORMATION))
    toolBar1.AddTool(ID_SampleItem + 4, "Test", wx.ArtProviderGetBitmap(wx.ART_WARNING))
    toolBar1.AddTool(ID_SampleItem + 5, "Test", wx.ArtProviderGetBitmap(wx.ART_MISSING_IMAGE))
   
    separator := wx.NewAuiToolBarItemT()
    separator.SetKind(wx.ITEM_SEPARATOR)
    customButton := wx.NewAuiToolBarItemT()
    customButton.SetKind(wx.ITEM_NORMAL)
    customButton.SetLabel("Customize...")
    wx.Bind(self, wx.EVT_MENU, func(e wx.Event) {
        wx.MessageBox("Customize clicked!")
    }, customButton.GetId())
   
   
    toolBar1.SetCustomOverflowItems([]wx.AuiToolBarItem{}, []wx.AuiToolBarItem{separator, customButton})
    toolBar1.Realize()


    paneInfo := wx.NewAuiPaneInfoT().Name("tb1").Caption("Big Toolbar").ToolbarPane().Top()
    self.auiManager.AddPane(toolBar1, paneInfo)
   
    // Left pane - a tree control
   
    treeCtrl := wx.NewTreeCtrl(self, wx.ID_ANY, wx.DefaultPosition, wx.NewSizeT(160, 250), wx.TR_DEFAULT_STYLE | wx.NO_BORDER);

    treeRoot := treeCtrl.AddRoot("wxAUI Project", 0)
   
    firstItem := treeCtrl.AppendItem(treeRoot, "Item 1", 0)
    treeCtrl.AppendItem(treeRoot, "Item 2", 0)
    treeCtrl.AppendItem(treeRoot, "Item 3", 0)
    treeCtrl.AppendItem(treeRoot, "Item 4", 0)
    treeCtrl.AppendItem(treeRoot, "Item 5", 0)
    treeCtrl.AppendItem(firstItem, "Subitem 1", 1)
    treeCtrl.AppendItem(firstItem, "Subitem 2", 1)
    treeCtrl.AppendItem(firstItem, "Subitem 3", 1)
    treeCtrl.AppendItem(firstItem, "Subitem 4", 1)
    treeCtrl.AppendItem(firstItem, "Subitem 5", 1)
    treeCtrl.Expand(treeRoot)
   
    self.auiManager.AddPane(wx.ToWindow(treeCtrl), wx.LEFT, "Hello")
    // wxTreeCtrl has an overloaded `GetNextSibling` function, which as a different
    // signature with wxWindow. So we have to cast wxTreeCtrl to wxWindow manually.
    // Equivalent: treeCtrl.SwigGetWindow()
   
   
    // CenterPane - a text control

    paneInfo = wx.NewAuiPaneInfoT().Name("notebook").CenterPane().PaneBorder(false)
    notebook := wx.NewAuiNotebook(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.AUI_NB_DEFAULT_STYLE | wx.AUI_NB_CLOSE_BUTTON)
    notebook.AddPage(wx.NewTextCtrl(notebook, wx.ID_ANY, "", wx.DefaultPosition, wx.DefaultSize, wx.TE_MULTILINE), "Test", true)
    self.auiManager.AddPane(notebook, paneInfo)

    self.auiManager.Update()

    return self
}

func main() {
    wx1 := wx.NewApp()
    frame := NewMyFrame()
    frame.Show()
    wx1.MainLoop()
    return
}


Result:









Wednesday, February 21, 2018

Implementing Merge Sort in Golang

What is Merge Sort?
Merge Sort is sorting algorithm that using a divide and conquer algorithm.

Conceptually, a merge sort works as follows:
If the list is of length 0 or 1, then it is already sorted otherwise Divide the unsorted list into two sub-lists of about half the size. Sort each sub-lists recursively by re-applying the merge sort. Merge the two sub-lists back into one sorted list.


Time Complexity
In the best /average / worst case it gives a time complexity of  O(n log n)


Implementation

package main

import (
    "fmt"
)

func main() {
    var arrToBeSorted []int = []int{1,3,2,5,4,6,7,9,8,10}
    fmt.Println("\n --- unsorted --- \n\n", arrToBeSorted)
    fmt.Println("\n--- sorted ---\n\n", MergeSort(arrToBeSorted), "\n")
}

// Runs MergeSort algorithm
func MergeSort(input []int) []int {

    if len(input) < 2 {
        return input
    }
    mid := (len(input)) / 2
    return Merge(MergeSort(input[:mid]), MergeSort(input[mid:]))
}

// Merges left and right slice into newly created slice
func Merge(left, right []int) []int {

    size, i, j := len(left)+len(right), 0, 0
    input := make([]int, size, size)

    for k := 0; k < size; k++ {
        if i > len(left)-1 && j <= len(right)-1 {
            input[k] = right[j]
            j++
        } else if j > len(right)-1 && i <= len(left)-1 {
            input[k] = left[i]
            i++
        } else if left[i] < right[j] {
            input[k] = left[i]
            i++
        } else {
            input[k] = right[j]
            j++
        }
    }
    return input
}



Result:











Other Topics:






Monday, February 19, 2018

Implementing Quick Sort in Golang

What is Quick Sort?
Quick Sort is a sorting algorithm that known as partition exchange sort.


Time Complexity
In the best/average case it gives a time complexity of O(nlogn) and worst time complexity of O(n^2)


Implementation

package main

import (
    "fmt"
    "sort"
)

func quicksort(a sort.Interface, i, j int) {
    if j > i {    
        left, right := i, j
        pivot := j
        for left <= right {
            for ;a.Less(left, pivot); left++ {}
            for ;a.Less(pivot, right); right-- {}
            if left <= right {
                a.Swap(left, right)
                left++
                right--
            }
        }
        quicksort(a, i, right)
        quicksort(a, left, j)
    }
}

func main() {
    arrToBeSorted := []int{1,3,2,5,4,6,7,9,8,10}
    fmt.Println("Before")
    fmt.Println(arrToBeSorted)
   
    fmt.Println("After")
    quicksort(sort.IntSlice(arrToBeSorted), 0, len(arrToBeSorted)-1)
    fmt.Println(arrToBeSorted)
}

Result:




Other Topics:





Thursday, February 15, 2018

Implementing Bubble Sort in Golang

What Is Bubble Sort ?
Bubble sort is a simple sorting algorithm that sequentially goes through an array n times. Each time the algorithm runs through the array, it looks at the first element and then the second element, if the first element is larger than the second element then it swaps them, it then proceeds through the entire list performing this action.


Time Complexity
The time complexity for this algorithm is O(n^2) where n is the number of items being sorted. It is not recommended to use for large input sets.
Best case time complexity is O(n) when the list is already sorted.



Implementation

package main

import (
    "fmt"
)

var arrToBeSorted [10]int = [10]int{1,3,2,5,4,6,7,9,8,10}

func BubbleSort(input [10]int) {
    for i := 0; i < len(input)-1; i++ {
        if input[i] > input[i+1] {
            input[i], input[i+1] = input[i+1], input[i]
        }
    }
    fmt.Println(input)
}


func main() {
    fmt.Println("Before")
    fmt.Println(arrToBeSorted)
  
    fmt.Println("After")
    BubbleSort(arrToBeSorted)
  
}


 Result:








Other Topics:





Thursday, February 8, 2018

Observer Pattern in Golang

Observer pattern is one of my favorite pattern in programming.
Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, its dependent objects are to be notified automatically. Observer pattern falls under behavioral pattern category.

Here is my implementation in Golang shown as below:

 Observer with file interface.go
type ObserverCallBack struct {
}
func (c *ObserverCallBack) Exec(o *Observable) {
    log.Println(o.Name)
}
type Callback interface {
    Exec(h *Observable)
}




Observer Notifier with file observer.go
type Observer struct {
    callbacks []Callback
}
func (o *Observer) Add(c Callback) {
    o.callbacks = append(o.callbacks, c)
}
func (o *Observer) Process(oe *Observable) {
    for _, c := range o.callbacks {
        c.Exec(oe)
    }
}



Full Code with main.go
package main
import (
       "log"
)
type Observable struct {
    Name string
}
type ObserverCallBack struct {
}
func (c *ObserverCallBack) Exec(o *Observable) {
    log.Println(o.Name)
}
type Callback interface {
    Exec(h *Observable)
}
type Observer struct {
    callbacks []Callback
}
func (o *Observer) Add(c Callback) {
    o.callbacks = append(o.callbacks, c)
}
func (o *Observer) Process(oe *Observable) {
    for _, c := range o.callbacks {
        c.Exec(oe)
    }
}
func main() {
    oe := Observable{Name: "Hello World"}
    o := Observer{}
    o.Add(&ObserverCallBack{})
    o.Process(&oe)
}
  

Result shown as below










Other Topics: