Ubuntu insights, Programming in groovy, java, et als!

Friday, November 16, 2012

Kernel Upgrade Issue, Uninstalling 3.6.6 kernel from Ubuntu 12.10

I've upgraded my 12.04 to 12.10 and strangely, I've observed that the kernel version 3.5.x that ships as default with 12.10 has not been upgraded from 3.2.x which I was using in 12.04 LTS version. 

uname -a (for kernel details)

Hence I've tried to do a manual install of latest kernel version 3.6.x, which also failed with an error reporting unmet package dependencies. Not just with the manual kernel upgrade but I've been facing problems with the usual system updates too, that get pushed on a regular basis.

I've tracked this for a while and then realized that I had once made an edit to the default grub configuration file adding an additional "quite splash" line to boost up battery performance. The problem was that after the OS upgrade was done, somehow the simple double quote(") got messed up and was replaced by a smarter double quote (``) which was causing all the errors during my upgrades and updates. I've reverted back the double quotes 

sudo gedit /etc/default/grub

and I have done an update grub. 

sudo update-grub 

..only to realize that 3.6.x, 3.5.x and other older kernel versions were all present and installed but failed to show up because of the grub configuration file error. Moreover, I had realized that 3.6 being the latest didn't work that great at least on MY machine (perhaps because it is not as customized as 3.5 for 12.10) as it was consuming 42W of power as shown on powertop which was too damn high. Hence I've removed the 3.6 kernel using 

sudo apt-get purge linux-image-3.6.*

and I've reverted back to the default 3.5.x kernel that is shipped with 12.10 and everything seems fine now. 

Things I've learnt in the process:
  • It is ideal not to upgrade a kernel version that is more latest than the one shipped with the latest OS version. Even if you wish to do so, compile the kernel separately and then proceed.
  • Installing and uninstalling a kernel. 

Thursday, August 09, 2012

A stupid hack to open short urls blocked by proxy via Launchy

This script will be useful when short urls are blocked by a proxy within a network.

For example:

Lets say the link to an article or blog on the web is this:

LongUrl : http://something.com/somethingelse

Your friend reads the above article and mails the link to you in its shortened form:

ShortUrl : http://bit.ly/s1 or http://t.co/se1

Now when you are on a company network or a protected network, there is a good chance that bit.ly or t.co services are blocked by the proxy though the original site itself (something.com in this case) might not be blocked.

For such cases this silly vbscript can be handy. It basically talks to a longurl.org which lengthens the shortened url and opens it up on the browser.

lurl.vbs

set ws = CreateObject("WScript.Shell")
siteUrl = "http://longurl.org/expand?url=" & Wscript.Arguments.Named("u")

Dim objHttp
Set objHttp = CreateObject("Msxml2.ServerXMLHTTP")
objHttp.Open "GET", siteUrl, False
objHttp.Send
page = objHttp.ResponseText
Set objHttp = Nothing

longUrl = Split(Split(page,"Long URL:")(1),"""")(1)
ws.Run(longUrl)

I have saved the above lurl.vbs file under C:\Temp\Scripts.

From command prompt, running the below command will open up the link in the browser.

lurl /u:your-short-url        


                          
Further more, you can even configure it via the Launchy Runner plugin which makes it more fun.

                                   

Within launchy, typing lurl (tab) followed by site's short url will launch the site directly.

                                 








Wednesday, June 20, 2012

Design Patterns: Factory Method Pattern

/**
* A simple implementation of Factory Method Pattern
* using a real time CricketPlayer example
*/


//Base
public interface CricketPlayer{
    public String play();
}


//Subclass
class Bowler implements CricketPlayer{
    public String  play (){
        return "takes a wicket";
    }
}


//Subclass
class Batsman implements CricketPlayer{
    public String  play (){
        return "hits a six";
    }
}


//Factory class - contains the logic of instatiating players
public class CricketPlayerFactory{
    CricketPlayer player;
   
    public CricketPlayer getPlayerWho(String does){
        if(does.equals("bats"))
            player = new Batsman();
        else if(does.equals("bowls"))
            player = new Bowler();
        return player;              
    }
}


//Factory method implementation
public class FactoryImplementation{
    public static void main(String args){
        //create a factory
        CricketPlayerFactory factory = new CricketPlayerFactory();
        //ask factory to instantiate the player
        CricketPlayer player = factory.getPlayerWho("bats");
        //use the player
        System.out.prinln(player. play ());
    }
}

Design Patterns: Singleton Pattern

/**
* A simple Implementation of a singleton
*/
class MySingleton{
   
    static MySingleton singletonInstance;
   
   //****** instantiation ******


    static MySingleton getInstance(){
        if(singletonInstance == null)
            singletonInstance = new MySingleton();
        return singletonInstance;
    }
   
    private MySingleton(){
        //cannot be called public with new
    }


   //****** logic ******   
    ....
    ....
}


MySingleton.getInstance();


FYI, Points to remember

  • Singletons are bad. 
  • They are just glorified statics and hence against OOP principles. 
  • They should be rarely used. A classic example: for logging purposes.
  • Singletons are hard to unit test.
  • Also bad because it is NEVER a good practice to mix instantiation and logic in a single class. 




Saturday, June 09, 2012

How to know HBOOT version and S-ON or S-OFF on HTC phones


  • Switch off the mobile completely.
  • Hold the volume down button and simultaneously click the power-on button. This will login to the boot menu and display details like this:

    BUZZ PVT SHIP S-ON
    HBOOT-1.01.0002
    MICROP-0622
    TOUCH PANEL-ATMELC03_16ac
    RADIO-3.35.20.10
    Dec  2 2010, 17:14:26

    The first line displays the security flag status. For being able to play around with sudo root access on HTC phones the flag must be turned off (shows S-OFF if turned off). 
  • Click power off button and next hold the volume down button to reboot again into normal menu. 


To be continued.. 





Wednesday, May 09, 2012

Currying in Groovy

Currying is a process of transforming a function of n arguments into n partial functions of one argument each.

Although I was acquainted with the math part of it. I found it hard to implement it in code. I
couldn't help but posting Tim Yate's sample snippet to my question on SO about a simple implementation for currying in groovy.


def greet = { greeting, person -> "$greeting $person" }


// This takes a closure and a default parameter
// And returns another closure that only requires the
// missing parameter
def currier = { fn, param ->
  { person1 ->
     fn( param, person1 )
  }
}


// We can then call our currying closure
def hi = currier( greet, 'Hi' )


// And test it out
hi( 'Vamsi' )


Here's an other pointer for doing functional programming in groovy. 

Friday, May 04, 2012

Setting up Conky & Lua-Widgets

Installing Conky-Lua widget/theme on Ubuntu

1) Install conky and conky-all from Ubuntu Software Center or via apt-get on terminal.

2) Unzip the contents of the tar.gz or zip of Conky/Lua theme submitted by the developer into some folder named Scripts.

Most importantly, the unzipped file will have a conky text file and a .lua file in it.

3) Ensure Nautilus Browser -> View -> Show hidden files option is enabled and create a hidden folder in your /home/Your_Username directory with the name .conky

4) Within the Scripts folder, search for file with .lua extension. This file contains the widget script. Copy the .lua file into the .conky folder.

5) Rename the left over text file in the Scripts folder to a hidden file named .conkyrc and place it in /home/Your_Username directory.


6) Open the .conkyrc file in gedit and edit the portion of the .conkyrc file which refers to the  widget location path i.e the .lua script path. In this case should point to

/home/Your_Username/.conky/someWidgetScript.lua

On terminal run command

conky

which will start the Conky theme/widget.


Installing Multiple Conky-Lua widget/themes on Ubuntu

By default, Running the conky command will invoke the .conkyrc text file at /home/Your_Username location and checks for lua scripts placed in the .conky folder.

In case of setting up multiple widgets you need to have multiple conky text files and multiple lua scripts.

Place all the .lua files in the .conky folder in the /home/Your_Username directory.

Let the text files remain in the Scripts folder but ensure that the configuration path in them points to their corresponding .lua scripts in the .conky folder. (as shown in step 6 above)

In terminal, run

conky -c /home/Your_Username/Scripts/ConkyTextFileScript1
conky -c /home/Your_Username/Scripts/ConkyTextFileScript2
conky -c /home/Your_Username/Scripts/ConkyTextFileScript3

Each of these will take the conky text file path with -c option and individually start the widgets.


PS: You might face issues if any of the above actions, like the path configuration (in step 6) is not done correctly. Also, This requires little bit of scripting knowledge to work your way around. In a nutshell, these are the minimal steps required to setup Conky-Lua Widgets on Ubuntu.




Saturday, April 28, 2012

Power Saving Tips on Ubuntu

If you are running 11.10 and suffering from excessive power consumption on your laptop/netbook, I insist upgradation to 12.04 immediately. In the latest 12.04 LTS release, the kernel bug relating to the excess power consumption has been fixed.

On 11.10, my laptop consumed a whooping 31 to 33 W of power. On 12.04, it has fallen down to 24 W. Further more, I've installed these three utilities which seem to have reduced the power consumption from 24 W to 16 W, which is pretty cool.


1) From Ubuntu software center, search for laptop-mode-tools and install it.


2) Install powertop which helps you assess the power consumption details and configure some of the processes. (sudo powertop on terminal to run it after installation)


3) Install jupiter, a tiny applet that runs on startup, a very useful utility that lets you set the mode to power consumption and also lets you configure the bluetooth and wireless options which typically consume a lot of power.


Installation of jupiter :
sudo add-apt-repository ppa:webupd8team/jupiter
sudo apt-get update
sudo apt-get install jupiter
sudo apt-get install jupiter-support-eee


4) If you are on a hybrid-graphics laptop, you can turn off your graphic card. In my case, this worked like a charm. 

echo OFF | sudo tee /sys/kernel/debug/vgaswitcheroo/switch 


However, the above command is not persistent and needs to run on every startup. 


Standard tips like keeping the brightness low, turning off wireless/bluetooth when not needed would also help.
I have abandoned using Ubuntu 11.10 from the past 3 to 4 months because of its excessive power consumption on my Dell Inspiron. Thanks to Precise Pangolin and these three utilities, I am back on Ubuntu now. :)


Hope this helps some of you battling with power consumption issues on laptops and netbooks running Ubuntu.

Monday, April 23, 2012

Why Groovy over java?

Some reasons why java developers should consider adapting groovy.

Groovy is married to java 

Groovy's seamless integration with java makes it possible to use all frameworks and libraries available for java, without any hassles regarding language compatibility. Groovy is so much compatible with java that one can merely change the .java extension to .groovy and run it. After all, groovy is just dynamic java with some add-ons and wrappers.

Dynamic typing

Unlike java, groovy does not throw compilation errors on your face. One of the biggest pleasure when compared to java, groovy doesn't impose explicit type casting which is a pain in the butt while programming in java. Groovy is a programmer friendly language and doesn't go out of control as long as the programmer is sure about his own code. It also supports optional typing, the native java syntax can be retained. 

Blocks and closures 

One of the best aspects of groovy is that it provides higher level constructs like blocks and closures found in languages like Smalltalk and Ruby. Block closures are handy powerful features which java lacks.

//To extract the first letter out of each element of a list.
def words = ['animal', 'bird' , 'cat', 'fly', 'dog']
def letters = words.collect{ it[0] }
println letters

//easy iterations
words.eachWithIndex{ word, index ->
    println "$word at $index"
}

The list goes on. Further refer : find{}, findAll{}, sort{}, each{}, contains{} et als, all of which make programming a breeze. 

Reflection in hand

As in smalltalk, Groovy has a concept of metaclass while initializing objects. This metaClass provides wrappers around the native Reflection API of java which enable the programmer to change the behavior of a class at run time.

For example : When compared to java, inspecting the methods of a class at runtime is as simple as :

class Test{
def one = 1
    def getOne(){
        return one
    }
}

println Test.metaClass.methods //prints getOne() and all methods default methods of the class.

Likewise to inspect the properties of a class at runtime, 

println Test.metaClass.properties //prints one and other properties if any

Likewise, injecting a method called getTwo() is as simple as :

Test.metaClass.getTwo = { return 2 }

Sugar Syntax

Besides addition of new language constructs, Perhaps this is one other aspect of groovy which hugely differentiates it with java.

Here I display two good examples that would make groovy an obvious win w.r.t to its sugar syntax.

ex: 1) A program to fetch the contents of a file in java would add up to around 10 - 15 lines. In groovy :

new File('C:\Temp\input.txt').getText()

Or further more, Parsing it is as simple as

new File('C:\Temp\input.txt').eachLine{ line ->
 //parsing logic
}

ex: 2) Given a url, to read the contents of a webpage, in java there is all this crap of opening streams, buffered readers and piping the contents, handling the exceptions etc. In groovy it is as simple as

'http://nerdysermons.blogspot.in'.toUrl().text

Further more...

Groovy has excellent wrappers around basic java functionalities. For example: With SwingBuilder, building swing UIs becomes darn simple.

For example: To built a swing application with a click me button and text area that prints hello message upon button click, a java program for the same would extend to more around 30 - 40 lines of code with initialization, building UIs, writing an actionListener etc. In groovy, this four liner script would suffice. 



new groovy.swing.SwingBuilder().edt{
    frame(show:true, size:[200,270]){
    panel(){
        button(label:'Click Me', actionPerformed :{ta.setText('Hello')})
        ta = textArea(columns:20, rows : 10)
        }
    }
}



Another great feature of groovy is its ability to build, create and parse XMLs with its XmlParser and XmlSlurper facilties. Some other include inbuilt assertions, GPath expressions,    String interpolations, etc.

I can go on like this for some time. This post is an introduction to depict groovy goodness comparing it to java which is strict and verbose. The more emphasis w.r.t the groovy vs java argument is on writing less code which possesses the java-ish flavor but is a lot elegant.



Wednesday, April 04, 2012

Redirecting log4j and Print streams to Custom Console

This is a custom JTextArea that I've coded for that can redirect and display all the print streams onto it including apache's log4j statements.



class MyConsole {
static outArea, consoleScroll, consoleTab

static log = Logger.getLogger(MyConsole.class)


//redirect the current println and err streams onto custom Stream 


static setUpStreams(){
outArea = JTextArea(10,100)
System.setErr(new PrintStream(new MyStream(outArea)));
System.setOut(new PrintStream(new  MyStream (outArea)));
WriterAppender logAppender = new WriterAppender(new PatternLayout(), new    MyStream (outArea));


Logger.getRootLogger().addAppender(logAppender);
}

public MyConsole(){ 

      setUpStreams()
}

}

//custom stream to which the standard streams are redirected
public class  MyStream  extends OutputStream {
JTextArea ta;
def str = ''
def buffer = []


MyStream (JTextArea t) {
super();
ta = t;
}

//detects \n and stores the line in a buffer and then prints the whole line..

public synchronized void write(int i) {

buffer.add(Character.toString((char)i))
if(buffer.last()=='\n'){
buffer.each{
str = str + Character.toString((char)it);
}

ta.append(str)
str = ''
buffer.clear()
}


//ta.append(Character.toString((char)i));

}

public synchronized void write(char[] buf, int off, int len) {
String s = new String(buf, off, len);
ta.append(s);

}
}



PS : I tried to keep the java-ish syntax alive in the snippet. Albeit that I guess I might have resorted to groovy's sugar syntax in a couple of places. Please make the changes accordingly. 

Tuesday, April 03, 2012

Creating Windows Shortcuts for your Application Programatically

Here is a 10 liner vbscript that can dump shortcuts for your application on desktop and All Programs menu in windows.


set WshShell = WScript.CreateObject("WScript.Shell" )
WinDir = WshShell.ExpandEnvironmentStrings("%WinDir%")

pathToDesktop = WshShell.SpecialFolders("Desktop")
set desktopShortcut = WshShell.CreateShortcut(pathToDesktop & "\MyApp.lnk")
desktopShortcut.TargetPath = Wscript.Arguments.Named("target")
desktopShortcut.WindowStyle = 1
desktopShortcut.IconLocation = WinDir & "\system32\SHELL32.dll,43"
desktopShortcut.Save

pathToStartMenu = WshShell.SpecialFolders("StartMenu")
set startMenuShortcut = WshShell.CreateShortcut(pathToStartMenu & "\Programs\MyApp.lnk")
startMenuShortcut.TargetPath = Wscript.Arguments.Named("target")
startMenuShortcut.WindowStyle = 1
startMenuShortcut.IconLocation = WinDir & "\system32\SHELL32.dll,43"
startMenuShortcut.Save





Execution from Command Line: 

cd to the directory where the above script is saved as mkshortcut.vbs.

Here I create a shortcut to a directory F:\Temp or any other file (even batch files or exe files which launch your application).


mkshortcut /target:"F:/temp"


The above command will create a shortcut called MyApp.lnk on your start menu >> Programs and on Desktop.

Execution from groovy program :

Prefix the above command with "cmd /c" and execute.

"cmd /c $command".execute() where in the command variable stores the mkshortcut line above as string.

Like wise, the same can also be extended to java using the Process Object.





Sunday, March 18, 2012

TicTacToe Game in Pharo Smalltalk

For an absolute pharo/smalltalk beginner, I think this would be a good place to start with. This is a simple TicTacToe implementation with just three classes : TicTacToe, TicTacToeCell and TicTacToeModel using Morphs. Works on MVC based architecture with view and model separate (no specific class for controller though).

Object subclass: #TicTacToe
instanceVariableNames: 'container model'
classVariableNames: ''
poolDictionaries: ''
category: 'VK-Games'

initialize 
container := Morph new 

              layoutPolicy: TableLayout new; 
              color: Color transparent.
model := TicTacToeModel new:3.
self addRows.
self addControls.
^self.

addRows
| rowMorph aCell rowCol |
1 to:3 do:[ :row |
rowMorph := Morph new layoutPolicy: RowLayout new.
1 to: 3 do: [ :col |
aCell := TicTacToeCell new.
aCell setModel: (model) row: row col: col.
rowMorph addMorph: aCell.
].
container addMorph: rowMorph.
]

addControls
| rowMorph newGameButton exitGameButton |
rowMorph := Morph new 

             layoutPolicy: RowLayout new; 
             color: Color transparent.
newGameButton := self createCtrlLabelled: 'New'      onClickExecutes: [self restart].
exitGameButton := self createCtrlLabelled: 'Exit'  onClickExecutes: [container delete].
rowMorph addMorph: exitGameButton.
rowMorph addMorph: newGameButton.
container addMorph: rowMorph.

createCtrlLabelled: aString onClickExecutes: aBlock
| aCtrlButton |
aCtrlButton := SimpleButtonMorph new label: aString.
aCtrlButton color: (Color black alpha: 0.2).
aCtrlButton extent: 60@30.
aCtrlButton on: #click send: #value to: aBlock.
^aCtrlButton.

open 
container openInWorld.

restart
container delete.
Smalltalk garbageCollect.
TicTacToe new open.

*****************************************

SimpleButtonMorph subclass: #TicTacToeCell
instanceVariableNames: 'parentModel rowNum colNum'
classVariableNames: ''
poolDictionaries: ''
category: 'VK-Games'



initialize 
super initialize.
self label: ''.
self extent: 40@40.
self on: #click send: #value to: (self onClickExecutionBlock).
^self.



setModel: ticTacToeModel row: aRow col: aCol
parentModel := ticTacToeModel.
rowNum := aRow.
colNum := aCol.



onClickExecutionBlock
^[
(self label size) == 0
ifTrue:[
self label: (parentModel updateAtRow: rowNum 
                Col: colNum).
parentModel checkWinCondition.
self extent: 40@40.
].
 ]


***************************************** 

Matrix subclass: #TicTacToeModel
instanceVariableNames: 'filledCellCount currentFill winner'
classVariableNames: ''
poolDictionaries: ''
category: 'VK-Games'

initialize 
super initialize.
filledCellCount := 0.
currentFill := nil.
winner := nil.

updateAtRow: r Col: c
currentFill == nil
ifTrue:[ currentFill := 'X'. ]
ifFalse:[
currentFill == 'X'
ifTrue: [ currentFill := 'O'. ]
ifFalse: [ currentFill := 'X'. ]
].
self at: r at: c put: currentFill.
filledCellCount := filledCellCount + 1.
^currentFill.

checkWinCondition
filledCellCount >= 5 "for optimization. Win can occur minimum at 5th turn"
ifTrue: [
Transcript show: 'Yes'.
1 to: 3 do: [:idx |
self checkWinConditionInRow: idx.
self checkWinConditionInColumn: idx.
].
self checkWinConditionInDiagonals.
].
checkWinConditionInRow: rowNum
|set|
winner isNil
ifTrue: [
set := (self atRow: rowNum) asSet.
self checkWinConditionInSet: set
].
^winner.

checkWinConditionInColumn: colNum
|set|
winner isNil
ifTrue: [
set := (self atColumn: colNum) asSet.
self checkWinConditionInSet: set.
].
^winner.

checkWinConditionInDiagonals
|set1 set2 |
winner isNil
ifTrue: [
set1 := (self diagonal) asSet.
set2 := Set newFrom: {(self at: 1 at: 3). (self at: 2 at: 2). (self at: 3 at: 1)} asOrderedCollection.
self checkWinConditionInSet: set1.
self checkWinConditionInSet: set2.
].
^winner.

checkWinConditionInSet: aSet
aSet size == 1
ifTrue: [
(aSet includes: 'X')
ifTrue: [winner := 'P1'. Transcript open. Transcript show: 'Player 1 is the winner!!'.].
(aSet includes: 'O')
ifTrue: [winner := 'P2'.  Transcript open. Transcript show: 'Player 2 is the winner!!'.].
].



Thursday, March 08, 2012

Coffee with Linux #2 - The Shell

Generally, users interact with the Operating System by clicking on icons, menus and buttons. This is called Graphical User Interface (GUI). Apart from this, there is also an other way to interact with the computer using a command line interface (CLI) which is purely by typing in commands to get the task done. Think of it the DOS command prompt in the world of Windows. One can open Notepad application either by selecting it from the start menu or by simple typing in notepad on the windows prompt. In a parallel context, the command line interface on Linux that enables human-machine interaction is called 'The Shell'. That being said, it is not technically correct to draw a comparison between the Windows DOS prompt and the Linux shell because the shell is capable of doing much much much more than what can be done from a regular dos prompt on windows.

The shell has many variants, some of which are 
  • C Shell
  • Korn
  • Bash
  • Z shell
Bash is used as a default for many Linux distros that are available today. In almost all Linux distros you find an option called terminal emulator (or simply the terminal). The terminal is merely a window that runs the shell program within it.

Standard input & Standard output

What you type in to the terminal on Linux is called the standard input and the output of the command typed in is called the standard output. This happens via streams. Whatever is typed in, is taken onto a stream (stdin) which is a continuous set of bytes, likewise the output is also written onto a stream (stdout) that is by default shown on the screen. You can redirect this stream, the standard output on screen onto a file or anywhere else. Example :

$ ls > outputOfLSCommand.txt


Speaking of streams there is a separate stream for carrying the error output (stderr). Likewise you can also redirect the standard input from a file instead of defaulting it to the keyboard.



Piping the output

Just the way the output is redirected, the user can also pipe the output. Piping generally happens when the output of one command is given as input to an other command. Example

$ ls | rev


In this command the output of list directories command as a String is given as an input to the rev (the reverse) command which displays the output text in a reversed way.

*********** End of Tutorial 2 ***********


See Introduction Tutorial 1: Coffee with Linux #1 - Head Start


Friday, March 02, 2012

Find RSS Feed URL of a Webpage

Given a URL of a web page, one can programatically search through the meta tags of the webpage's content for alternate URL links (like atom or RSS feed links for the same) to thereon further use them to parse and process the content of the webpage. Typically this is the way Google Reader works. Here I present a very simple implementation of the same in pharo smalltalk.


Object subclass: #RSSReader
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'VamsiExperiments'


getURLContent: url
  "## Comment : Supply the url String of the webpage,
 
   ## example: http://nerdysermons.blogspot.in"
| urlContent |
urlContent := (url asUrl retrieveContents contents asString).
^urlContent



findAlternateLinksInUrlContent: urlContent
  "## Comment : The above fetched page content to 

   ## be passed here to get an ordered collection 
   ## of alternate links"      
| links|
links := OrderedCollection new.
urlContent linesDo:  [:line |
(line findString: '<link rel="alternate"') > 0
ifTrue: [
links add: (line findTokens:'"' includes: 'http://').
].  
].
^links.

Wednesday, February 29, 2012

Bypass the Linux Grub to retrieve Windows Bootloader

Rececntly I had messed up with the Linux partitions on my laptop because of which the grub rescue wasn't letting me login to any of my operating systems. This is a simple step that I came across to bypass the Linux grub to retrieve back my Windows Boot screen back. Simple yet helpful.

1) Insert a Windows 7 upgrade disc.
2) Enter boot menu to boot from CD/DVD.
2) Proceed to repair Windows. (Caution : Do not reinstall Windows)
3) Open command prompt
4) Type in
Bootrec.exe /FixMbr
which reports a quick reply reporting, "operation ended successfully"
5) Remove disc and Reboot from HDD.

Tuesday, February 14, 2012

Coffee with Linux #1 - Head Start

Introduction 

It is often a gigantic task for a newbie to grasp concepts of Linux, not because they seem nerdy but mostly because there are way too many facets to the OS and it is surrounded by a humongous number of other terms which usually tend to scare away a learner in the first glimpse. Most of the time, beginners find it hard to find a starting point to learn Linux. 

Coffee with Linux will be a series of blog posts which will touch base concepts at a very superficial level. The blogposts in this series will usually be the gateways for you to enter into the world of Linux. The series will eventually run into posts that will describe the usage of commands from terminal. The learning will not be in bookish order, it will rather be in the order of the things I learnt/learn/will learn. So let's get started!


Li'l history

Unix was an operating system started as an academic project, pioneered by the likes of  Dennis Ritchie and Ken Thompson, at AT&T's Bell labs during the late 1960s. It gained popularity and different communities and groups were picking up unix and developing their own versions of Unix.  One such version was Minix which was supposedly a minimal Unix version, which was written by Andrew S. Tanenbaum. Minix was used in universities to teach computer science. Linus Torvalds picked it up, contributed to the development of an open source Kernel and called it Linux. 


Distros

As Linux is open sourced, anyone can pick up the source code and develop a version of his own. Thousands of distributions have emerged since the last couple of decades. To name a few, Redhat, OpenSuse, Ubuntu, Lubuntu, Kubuntu, Bodhi Linux and TinyCore are some known distros. To know about the different distros of linux, visit  http://distrowatch.com 


Understanding the OS

An operating system typical has three layers. 


Environment (The Top Layer)
This layer in very raw terms deals with applications that interact with the user. Terms like KDE, GNOME and UBUNTU's UNITY fit in here. They are typically the desktop environments and Linux gives the user complete flexibility to use any of these desktop environments. If need be, the user can even chuck out this desktop environment layer and stick to the default command line interface. 

Example to Ring a bell : Desktop themes, icons, toolbars, etc.


Kernel (The Middle Layer)


Kernel is an abstraction layer that co-ordinates the applications with a system's hardware and resources. An operating system exists only because of its kernel which usually takes care of all the OS specific operations like process, memory and device management. It is completely 
written in C and can be downloaded at  http://kernel.org/

Example to Ring a bell : Running two or more applications at a time and multitasking on them.


System Resources (The Lower Layer)


File System, memory and all hardware specific physical matter come under this layer. 

Example to Ring a bell : The presence of a graphic card to play high end games. 



------------ End of tutorial 1 -----------






Thursday, February 02, 2012

The Art of Test Driven Development

For the very for first time, I have dabbled myself into the practices of Test Driven Development. I must admit that I am completely bowled over by the experience. For more than an year, I had been reluctant to adapt the concept of unit tests as I mistook writing them as a programmer's lack of faith in the code he pushes in but I eventually realized that I could NEVER BE MORE wrong.


I have long had this evil habit of quick prototyping where in all I care about is the end result. In this process, what starts off as a script evolves into neatly refactored block closures and methods, methods to classes & objects and classes to packages. In spite of starting to code with a basic design in mind, it becomes very hard to adhere to the architecture and design with this bottom-up approach as it solely aims at achieving a result without considering the means to achieve it. Hence the code quality might short fall of standards as it ought to be. Also, this involves constant rework. Though a quite conventional approach and a pleasure to begin with, this method is bound to inflict pain at later stages when the code base evolves into a dinosaur and becomes hard to maintain.


Test Driven Development on the contrary might seem annoying at the start to code with but eventually pays off. TDD is all about starting to code keeping in mind the unit tests that are going to be written. The core code base and the xunits are written in tandem with each other. They go hand in hand. It appears like programming in two places at a time. You code for a method in the base class and write its corresponding test in the testcase and run it simultaneously. With TDD, it is like thinking in two directions at a time. As a result of coding in tandem with the unit tests, the very initial draft of code itself begins to look like what it would seem to look like after two or three cycles of rework. Very neat, well re-factored, modularized, extensible and testable. The code written in this manner is more reliable because the unit tests enforce the programmer to code keeping in mind the exceptional scenarios, exposing all the permutations and combinations in which a piece of code could behave. As a result of this, the bugs in the final delivery will dwindle down considerably.


The number of unit tests increase over a period of time along with the code. All the testcases written could be run on a periodic basis to ensure that any newly committed code will not break the functionality of the existing code base. This diminishes the scope for regression issues and hence adds to scalability and maintainability of code. 


Very often it becomes difficult for a newbie to get a hang around code that is already written. Even in such cases testcases help because unit tests themselves act as informal documentation to the classes and methods used. Adding to that, as the code grows in size, the need to use a debugger eventually reduces provided the code is covered by diligently written testcases. 

TDD is an elegant art. Practice it! Preach it!, to everyone who aims to be a quality programmer. For, it is a priceless feeling to experience the 'aha' moment when you look at your sexy monstrous code base that says "All tests passed".

Monday, January 23, 2012

Find Source code Line Numbers of Methods at Runtime


Comparing a source file and a runtime equivalent object of the class, here is a ten liner groovy script that determines the line numbers of every method inside a class. A plausible approach to do this in java is is to throw a stacktrace explicitly wherever needed and examine it to determine the line number at the point of execution. This I find is too clumsy a way. One can also take an other approach by parsing the source code file, creating a tree node structure and manipulate it but then the problem with this approach is that one has to reinvent the whole wheel again.

Groovy's dynamism comes to rescue here exposing the runtime object to the programmer during execution. At runtime, one can inspect an object, study its methods and properties and manipulate them as per the need. This can also be done in java using the Reflection API but I find it too monstrous and verbose. I resort to groovy instead. Here's the ten liner script for the same.

//supply the source file path, the only input to the script
def sourceFilePath = 'C:\\Temp\\GroovyUtils\\Sample.groovy'

//a map that stores method names vs line numbers as key val pairs
def methodToLineMap = [:]

//find all the methods of the Sample class and assign default line number as 0 first.
def listOfMethods = new Sample().metaClass.methods*
listOfMethods .name.sort().unique().each{
    methodToLineMap.put(it,0)
}


//parse src file to find the line numbers of methods & store line number in the methodMap
def idx = 0
new File(sourceFilePath).eachLine{ line ->
    idx++
    methodToLineMap.keySet().each{method ->
        if(line.contains(method)){
            methodToLineMap[method] = idx
        }
    }
}

//print the elements of method vs line number map
methodToLineMap.each{
    if(it.value!=0)
        println it
}

PS : You can also supply a java source code file (in sourceFilePath) to find out the line numbers of the java class's methods but ensure that the .class file is on the classpath while running the script.

Tuesday, January 17, 2012

Windows 8 - (Dev Build) Review So Far


I just experienced Windows 8, a leaked version from the dev build beta archives, on my friend's laptop. If there is one adjective to describe it, I'd go for the word "different". I personally felt that the tablet-ish aspect of its UI certainly looks elegant with all the native MS-zune like Metro-style interface but I am afraid that it would certainly compromise the desktop experience. A scroll though between panels is obviously easier on a tablet because of the touch. On the contrary I find it a pain in the butt to move my mouse to the tiny scroll bar below to navigate between the home panels. The tablet targeted applications provided by default are brilliant, like the RSS/News feed reader, Picstream, Paintplay, etc.
Users are likely to face hassles until they get used to it. First and foremost of all, as you login to the system you are not directed to a desktop screen, instead you are directed onto a tablet like home screen. 
To see the Windows 7 like desktop, you need to select the desktop launcher from the home screen. When an application or external software is installed, instead of the shortcut being dropped onto the desktop, a similar such launch icon will be dropped onto the panels. Of course you can manually drop the shortcut onto the desktop too. Secondly, there is not even a slightest trace of the conventional "All Programs" type start menu within the desktop. So if you heavily rely on the Start menu - mouse click way of launching your applications, well, you might hate Windows 8. But good news for the keyboard freaks who rarely use the mouse to launch apps. Windows 7 start menu search is extended further to make it look the unity panel of Ubuntu 11.04 and above. So applications can be launched easily by hitting the windows key and typing in the name of the app to be launched.

Some other changes in the UI include addition of an abnormally huge toolbar (as in MS office apps) in the FIle Explorer. Windows task manager has changed, looks good but again, it is not too intuitive to a conventional Windows User in its first sight. Some other minor changes in alerts are also evident. 

As of now, I am ignorant of the intricacies of this version of Windows OS, but from an eagle eye's perspective, the speed and performance seem descent enough, just like its predecessor. Nevertheless, I wouldn't go too far exaggerating that Windows 8 is immaculate because it isn't. I am not as thrilled as I was when I experienced Windows 7 for the first time. It is too good in some aspects and atrocious in some other. I hope the annoying aspects of it are answered in the coming build versions. So to wrap it up, I stick to the word, different. Yes!, Windows 8 is different, a lot different and it has changed from its former versions. It depends on how the users tune themselves with this change. 

Thursday, January 05, 2012

Why Android Sucks? Why iOS is better?

Prior to the reasons I depict to prove a point here, I would want to confess that neither do I blindly follow the cult of apple nor do I hate android based on sheer ignorance. The musings I share here are out of daily observances, experiences and a little bit of drilling into the technical aspects of Android as an OS and more.

I have been a heavy user of android on my HTC wildfire for a while. I find that Android does do what a smartphone ought to do but it doesn't do it with elegance. There are way too many shortcomings and glitches buried down deep into the sheath of the Android eco-system. On the contrary my experience with apple iOS has been limited only to iPod but I must admit the immense pleasure that it gives me and about how it provokes me to lay my hands on it again and again unlike my HTC Android that makes me moan about why I even considered buying it in the first place.

Initially, I was under the presumption that support for multiple hardware was cool but what I eventually realized after drilling in to details is that support for multi-hardware comes at a cost. If I were to design a gallery app for an android mobile or a tablet, I need to ponder over how to get the rendering right on different hardware at different resolutions. This is one reason why many apps on android are not compatible with all kinds of hardware. Take angry birds for instance, it doesn't run on all mobiles and tablets as it ought to. This is annoying both to the developer and to the user as well. On the contrary, within the apple world, all these complexities boil down to a simple fact that I am designing an app for a single target hardware that only runs at a given resolution(s). Because of this streamlined atmosphere to code, my psyche as a developer will subconsciously adhere to deliver THE BEST app for a single hardware rather than delivering a DECENT app that supports all hardware in the world.

Another interesting observation, Every new release of Android version makes me realize how crappy its predecessor is. On the other hand, every new release of iOS would make me realize how awesome the newer version is. There is a wide difference between the two in spite of seeming same. The focus on developing a newer version of Android is more towards rectifying the bad things in the current version and making it better in the newer version. In the iOS scenario, the focus of developing a newer version is to rope in newer features that never existed before. For example : It has been around eight months since I had bought a HTC wildfire running Froyo Android 2.2. Looking at the newer ice cream sandwich version, I whine about how atrocious Froyo is in its speed and performance compared to the latter and how good the newer version of HTC wildfire IS. Whereas if I had bought an iphone 4, probably the only thing that I would be whining about is that I do not get to use the SIRI but I would never be whining about its performance in what it delivers to me as a smartphone. So the key point that I would want to highlight here is that newer versions of Android or its supporting hardware would seem awesome only because the former versions were bad whereas newer versions of iOS and hardware would seem awesome because of their added innovation into every new release or update.

On an other note, the power of a smartphone would be realized to a maximum extent by the apps that run on it. As far as I know, Android is probably the first and foremost entity that can be credited for indirectly being responsible for the injection of infectious malware at a tangible level on a Linux based system. I mean, though not impossible to do it, a Linux core by default is highly resilient to such stuff and with all the malware and antivirus crap that are evidently used in the Android world could only mean one among these two things. Either Android could not exploit the strengths of a Linux core or the hacker/developer is way too smart, which I think the case is certainly the former.

Adding to that, it is way too easy to develop an app consisting of malware and releasing it into the Android market. Of course, Google continuously scrutinizes the apps submitted but that is not just good enough to prevent the damage. Forget malware, Nothing really stops me from writing an untested low quality lameass hello world android app and release it into the market whereas if I were to develop an app for iphone/ipad, I need to ensure that it is thoroughly tested and it literally takes 3 to 4 weeks for iStore to approve the app after submission. This is an example that depicts the spirit of apple, precisely the spirit of Steve Jobs to give the deepest attention to minutest of detail to develop something impeccably tangible.

A recent article on Google+ posted by Dianne Hackborne, an Android developer at Google, throws light, complaining the inefficiency relating to the Android's methodology of hardware acceleration to render graphics. Reading the article one would be convinced that Android fares well only under the availability of considerably high end hardware. One doesn't have to go all technical to comprehend the disabilities of Android. Pick up a HTC or Samsung smartphone, open up around 10 applications one after the other, the performance of the 11th or 12th application that you open up will certainly not be as smooth as the first few. Typically iOS does this task brilliantly. No matter what, most of the RAM will be used only by the opened/active process in the Apple tablet or mobile. Only one application can run at a time on the screen which gives a tremendous performance hit. Android does a similar job in a crooked way, somehow temporarily suspending the inactive process but that doesn't restrict an inactive app running in the background eating away my puny little RAM. For this reason, I even see task managers and process killing apps on Android. Geez! For Christ's sake, I am running a phone, not a super computer! Yet again, Apple proves its best in technical brilliance without compromising performance. With all the brouhaha that surrounds the Galaxy tab's 1 GB RAM and hardware excellence, I wonder if the users of the tab did ever make it a point to notice how iPad 2 does all this process magnificently better than the former within a bare minimum of 512 MB RAM.

From a techie's viewpoint, though the core of Android is written in C and C++, all the APIs and applications that surround it are built on java. There is all this dinosaur conversion of bytecode in dalvik's understandable dex format and other humongous stuff which certainly can never beat the iOS's simplistic approach of limiting all complexities to a mutually compatible C, C++ and Objective C. Anything that involves java usually sucks blood in performance. No matter how awesome the Samsung's hardware is, god knows how many hundreds and thousands of method calls are gone through in java to understand and process the multi-touch event. And again, one doesn't have to drill through all the technical crap to understand the complexities and disabilities of Android. Go ahead, Take a delicate bird feather and compare the touch sensitivity of an iPhone vs an Android phone or an iPad vs any other cog-in-the-wheel tablet you know of, You will get a hang of what I am trying to convey here.

In spite of all its internal flaws, more and more newer and better versions of Android may come up in the near future but it all accounts to mere band-aiding. What's the point? You got your basement built on wooden sticks and lay concrete pillars on your higher floors! Technically, an Android can never beat the brilliance of an iOS in its flawless design and architecture (both hardware and software). Who cares about the numbers in market? After all, it is okay for Galaxy tabs and the rest to be content about being second runners but in reality Apple is running a different race altogether.


EDIT: This post was written when Android devices were running 2.2/2.3. With the advent of ICS, things seem to have changed where in a lot of changes have been made to the Android code base (some portion completely re acrchitectured from scratch) to make it scalable on tablet devices. Also to admit, Off late Apple is just not able to pull out something innovative. Android is certainly moving up the ladder with almost 50% of tablet market conquered. Looking at the circumstances, Android is a clear winner especially when it comes to appealing to the eyes of a user.

PS: As I have quoted before, I am not an Apple fanboy. I am a technical person and I tried to throw some light on fineness of iOS as a whole when compared to Android. I never intended to compare the complete eco system of Android devices and Apple devices. In fact, to be honest, I'd never ever dream of buying an iPad over an Android tablet, for I know it is just a toy, completely ungeek and strict in user customization despite its flawless OS.