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

Monday, December 15, 2014

Write a custom event handler in groovy/java

One may write a couple of classes and an interface to achieve event handling without having to implement the Observable/Observer interface. Assume, we have a computer that runs several processes. If it receives a shutdown command, we fire an event to let the running process handle its own clean up method to release resources and halt execution.

interface ShutdownListener{
    public void handle();
}

public class Computer{

    private def listeners = []

    def addShutdownListener(ShutdownListener l){
listeners.add(l)
    }

    def shutdown(){
for(ShutdownListener l : listeners)
l.handle()
    }

    def compute(){ // whatever  }

}

public class Process implements ShutdownListener{

    public void handle(){
// release resources of "this" Process 
// halt execution of self
println("Process ended.");
    }
}

//groovy script start 
def computer = new Computer()
def process = new Process()
computer.addShutdownListener(process)
computer.compute()
computer.shutdown()

Monday, October 20, 2014

Simple way to implement find(select) and collect block closures in java

Languages like ruby, groovy, smalltalk have language constructs for blocks and closures. Java 8 now has feature to evaluate lambda expressions. But here is one simple and straight way to implement the same:

In groovy :

[1, 2, 3, 10, 20, 30].findAll { num -> num > 5 }
=> yields a new list [10, 20, 30]

[ 1, 2, 3, 4 ].collect{ num -> num * num}
=> yields a new list [1, 4, 9, 16]

The above code for those more familiar with the smalltalk syntax will be:

#(1 2 3 10 20 30) select: [ :num | num > 5 ]
==> displays [10, 20, 30]

#( 1 2 3 4 ) collect: [:i | i * i ].
==> displays [1, 4, 9, 16]

In java, the same could be implemented with a set of abstract classes as a collection utility that mandate implementation of method which returns the boolean condition to add or transform the element under iteration :

Find.java
abstract class Find extends ArrayList{ 
    /** let the default constructor worry about iteration **/
    public Find(List list){    
        Iterator it = list.iterator();
        while(it.hasNext()){
            Object element = it.next();        
            if(all(element))           
                this.add(element);         
        }
    }
     
    /** This defines the boolean condition for find/select **/
    public abstract Boolean all(Object obj);
     
}

FindDemo.java
// find all elements in the list that are greater than 5
List list = Arrays.asList(1, 2, 3, 10, 20, 30);
selected = new Find(list) {
    public Boolean all(Object num) {               
        return (int) num > 5;
    }
};
// => yields a new list [10, 20, 30]

Collect.java
abstract class Collect extends ArrayList{  
    /** let the default constructor worry about iteration **/
    public Collect(List list){
        Iterator it = list.iterator();
        while(it.hasNext()){
            Object element = it.next();
            Object transformed = transform(element);
            this.add(transformed);
        }
    }
    /** This defines the transformation logic for collect **/
    public abstract Object transform(Object obj);
}

CollectDemo.java
// collect the squares of all elements in the list
List list = Arrays.asList(1, 2, 3, 4);
collected = new Collect(list) {    
    public Object transform(Object num) {
            return (int) num * (int) num;
    }
};
// => yields a new list [1, 4, 9, 16]

Saturday, October 11, 2014

Gauss Circle Problem

Can do better without two loops :-|


latticePoints = 0
radius = 3.2
mod = int(radius) + 1

def isInCircle(x, y):
    return x*x + y*y <= radius*radius

def calc(x, y):
    global latticePoints
    if x == 0 and y == 0:
        latticePoints = latticePoints + 1
        print((x, y))
    elif x == 0 and y != 0:
        latticePoints = latticePoints + 2
        print((x, y),(x, -y))      
    elif x != 0 and y == 0:
        latticePoints = latticePoints + 2
        print((x, y),(-x, y))      
    else :
        latticePoints = latticePoints + 4
        print((x, y), (-x, -y), (x, -y), (-x, y))          

for i in range(mod) :
    for j in range(mod) :
        if(isInCircle(i,j)):
            calc(i,j)
 
print(latticePoints)





Wednesday, November 06, 2013

Fun with Git on Linux

Baby steps : 

1) create an account on github
2) create a git repository. Note down the repo URL.

Install git from terminal : 

sudo apt-get install git

Code Upload :
cd Scripts (or any new folder)
git init (local initialization. creates a local .git folder)
mkdir YourProjectDirectory (and add all source files under it).
git add .
git commit (commits the added source files to the local repository)
git remote add origin yourRepoURL (ex: https://github.com/vamsi-emani/pythonscripts.git)
git pull origin master (to sync with remote copy)
git push origin master (commits all the local changes to remote repository)

To delete a directory: 
git rm -r local-directory-name (recursively remove all local directory files)
git commit (commits to local repo)
git push origin master (commits to remote repo)

Thursday, July 04, 2013

SVN checkout and Sonar Ant Task Run

The ant script below checks out a java project from a given svn url and runs the downloaded source files against sonar.

Prerequisites: 

SVN Client installed
Included jars on classpath : ant.jar, sonar-ant-task-2.1.jar, svnjavahl.jar, svnClientAdapter.jar, svnant.jar

build.xml (Highlighted portions in red are to be set by user/setup dependent)

<?xml version="1.0" encoding="UTF-8"?>

<project name="Update" basedir="." default="update" xmlns:sonar="antlib:org.sonar.ant">

 <path id="svnant.classpath">
 <fileset dir="lib">    
  <include name="**/*.jar" />
 </fileset>
</path>

  <property name="project.svn.url" value="your-svn-url-of-project" />

  <!-- <taskdef resource="svntask.properties"  /> -->
 <taskdef  name="svn"  classname="org.tigris.subversion.svnant.SvnTask" classpathref="svnant.classpath"/>

  <target name="update">
    <svn>
      <checkout url="${project.svn.url}" revision="HEAD" destPath="MyProject" />
    </svn>
  </target>
   
<property name="sonar.jdbc.url" value="jdbc:h2:tcp://localhost:9092/sonar" />
<property name="sonar.jdbc.username" value="sonar" />
<property name="sonar.jdbc.password" value="sonar" />
<property name="sonar.projectKey" value="org.codehaus.sonar:example-java-ant" />
<property name="sonar.projectName" value="Sonar Sample Project Ant Run" />
<property name="sonar.projectVersion" value="1.0"/>
<property name="sonar.language" value="java" />
<property name="sonar.sources" value="MyProject/src" />
<!-- <property name="sonar.binaries" value="build/*.jar" />
 -->
<property name="sonar.host.url" value="http://localhost:9000" />

<target name="sonar" depends="update">
    <taskdef uri="antlib:org.sonar.ant" resource="org/sonar/ant/antlib.xml" classpathref="svnant.classpath">  
    </taskdef>
   
    <sonar:sonar/>  
</target>

</project>


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.