Delegates in C#

•March 5, 2009 • Leave a Comment

Here’s a simple tutorial on how to use Delegates in C#. It’s mostly self explanatory, so no futher comments


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DelegateTutorial
{

    public class SaySomeThing
    {
        internal string s1 = "foo";
        internal string s2 = "bar";
        internal string s3 = "wow";
    }

    public delegate void MyDelegate(SaySomeThing s);
    public delegate void MyOtherDelegate(SaySomeThing s, int num);

    class Program
    {
        public void overloadDelegate1(SaySomeThing s)
        {
            Console.WriteLine(s.s1);
        }

        public void overloadDelegate2(SaySomeThing s)
        {
            Console.WriteLine(s.s2);
        }

        public static void overloadDelegate3(SaySomeThing s)
        {
            Console.WriteLine(s.s2);
        }

        public static void overloadDelegate4(SaySomeThing s, int num)
        {
            for (int j = 0; j < num; j++)
                Console.WriteLine(s.s3);
        }

        public void callDelegate(MyDelegate mydelegate)
        {
            SaySomeThing something = new SaySomeThing();
            mydelegate(something);
        }

        public void callDelegate2(MyOtherDelegate myotherdelegate, int num)
        {
            SaySomeThing something = new SaySomeThing();
            myotherdelegate(something, num);
        }

        static void Main(string[] args)
        {
            Program p = new Program();
            p.callDelegate(new MyDelegate(p.overloadDelegate1));
            p.callDelegate(new MyDelegate(p.overloadDelegate2));
            p.callDelegate(new MyDelegate(Program.overloadDelegate3));
            p.callDelegate2(new MyOtherDelegate(Program.overloadDelegate4), 5);

            Console.WriteLine("******************");
            //alternatively
            MyDelegate d1 = new MyDelegate(p.overloadDelegate1);
            d1(new SaySomeThing());
            MyDelegate d3 = new MyDelegate(Program.overloadDelegate3);
            d3(new SaySomeThing());
            Console.WriteLine();
            MyDelegate dc = d1 + d1 + d3 + d3;
            dc(new SaySomeThing());

        }
    }
}

Creating Custom Iterators in Java

•February 2, 2009 • Leave a Comment

with the (over?)dependence on the standard Java Iterators, we sometimes overlook/forget the fact that we can , in fact, define custom iterators. This can be  quite simple to do, depending on the underlying data structure you define. The following is a simple example of how to define and use a custom list iterator.

1. Define the list node


package com.vgb.iterexample;

public class SampleNode {

	int i;
	SampleNode next;

	public SampleNode(int i, SampleNode next) {
		super();
		this.i = i;
		this.next = next;
	}

	public int getI() {
		return i;
	}

	public void setI(int i) {
		this.i = i;
	}

	public SampleNode getNext() {
		return next;
	}

	public void setNext(SampleNode next) {
		this.next = next;
	}

	public String toString() {
		return i+"";
	}

}

2. Define an iterator for this node


package com.vgb.iterexample;

import java.util.Iterator;

public class SampleNodeIterator implements Iterator{
	public SampleNode cur = null;

	public SampleNodeIterator(SampleNode cur) {
		super();
		this.cur = cur;
	}

	@Override
	public boolean hasNext() {
		if (cur == null)
			return false;

		return true;
	}

	@Override
	public Object next() {
		if (cur == null)
			return null;

		SampleNode tmp = cur;
		cur = cur.getNext();
		return tmp;
	}

	@Override
	public void remove() {
		// TODO Auto-generated method stub

	}

}

3. Define the list that uses these nodes


package com.vgb.iterexample;

import java.util.Iterator;

public class SampleList implements Iterable {
	SampleNode head = null;

	@Override
	public Iterator iterator() {
		return new SampleNodeIterator(head);
	}

	public SampleList() {
		head = new SampleNode(-1, null);
	}

	/*
	 * NOTE: shallow value - of - reference copy
	 */
	public void addNodetoList(SampleNode node) {
		if (head == null) {
			head = node;
			node.setNext(null);
		} else {
			node.setNext(head.getNext());
			head.setNext(node);
		}
	}
}

4. .. and finally, a simple test application


package com.vgb.iterexample;

import java.util.Iterator;

public class SampleApp {

	public static void main(String argv[]) {
		SampleList sList = new SampleList();

		for (int i = 0; i &lt; 10;i++) {
			sList.addNodetoList(new SampleNode(i, null));
		}

		Iterator iter = sList.iterator();
		SampleNode sNode = null;
		while (iter.hasNext()) {
			sNode = (SampleNode) iter.next();
			System.out.println(&quot;retrived via iterator: &quot; + sNode);
		}

	}

}

Jave equivalent of C++ __FUNCTION__ and __LINE__ macros

•December 11, 2008 • Leave a Comment

Here’s one way to get this information, .. add the following line to whatever / wherever you want to trace

System.out.println((new Throwable()).getStackTrace()[0].toString());

Sample output:
com.junk.Junk3.main(Junk3.java:12)

An added advantage of adding debug traces as above is that , when using an IDE such as Eclipse, you can click on an individual trace and automatically beam up the relevant code on your code editor pane.

Blogworthy Link – JavaBlackBelt

•December 11, 2008 • Leave a Comment

Java Black Belt – a collection of java questions, .. great for self evaluation or just “brain-gym” type work.

Dang Ubuntu Intrepid Ibex / NVIDIA SLI settings

•November 27, 2008 • Leave a Comment

Got this working after a little hacking / googling (or should i call that “hack-ling” ?).

Apparantly , Ubuntu 8.1 gets confused about which device to use when the Nvidia proprietary drivers are installed. The following are the steps needed to rectify the situation:

1. Search for your VGA devices
vinay@genome:~$ lspci |grep -i vga
01:00.0 VGA compatible controller: nVidia Corporation G70 [GeForce 7600 GT] (rev a1)
02:00.0 VGA compatible controller: nVidia Corporation G70 [GeForce 7600 GT] (rev a1)
vinay@genome:~$

2. Edit (as sudo / root) your /etc/X11/xorg.conf file and navigate to the section “Device”. Add the BusId line with corresponding information corresponding to either of your VGA devices (you may have to try this and the next step multiple times depending on how many VGA devices you have configured).

Section "Device"
Identifier "Configured Video Device"
Driver "nvidia"
Option "NoLogo" "True"
BusId "01:00:00"
EndSection

3. Restart X (I use gnome so the word “gdm” is used in the following command, use “kdm” if you use kde).

sudo /etc/init.d/gdm start

That’s it. Enjoy.

Blogworthy Link – JavaBlackBelt

•November 26, 2008 • Leave a Comment

Java Black Belt – a collection of java questions, .. great for self evaluation or just “brain-gym” type work.

Local SVN repository on Windows XP workstation

•October 20, 2008 • Leave a Comment

I’ve decided to start backing up ongoing immature work on a local SVN repository, rather than relying on the age old tried and tested “backup” folder, or relying on Eclipse’s backup mechanism. The steps involved are fairly simple. Refer to http://nedbatchelder.com/text/quicksvn.html for more details.

Install svn on your workstation. I use Windows XP at work

  1. Install svn on your workstation  (procedure depends on OS). I use Windows XP at work.
  2. Create a repository
    C:\svn>svnadmin create c:\svn\vinay_svn_backup
  3. At this point , you can chose to backup the files manually or use whatever IDE you use. I use Eclipse for Java development and can add the repository created above to my list of repositories (make sure the SVN connector is installed first).  Add something like the following line when creating a link to the  repository file:///c:/svn/vinay_svn_backup

That’s it, enjoy.

Integer to Unicode

•October 7, 2008 • Leave a Comment

Had to iterate across a bunch of unicode chars and as such, needed to write this snippet of code to generate unicode from integers


....
	/**
	 * This method determines the unicode string representation of an integer
	 *
	 * @param num
	 *            The integer whose unicode string representation is required
	 * @return Unicode representation of the integer
	 */
	private static String IntToUnicodeString(int num)
			throws IllegalArgumentException {
		if (num  0x10FFFF)
			throw new IllegalArgumentException(Integer.toHexString(num)
					+ " is less than 0 or larger than the greatest unicode value 0x10FFFF");
		return new String(Character.toChars(num));
	}
....

Unicode To UTF-8

•October 2, 2008 • Leave a Comment

Ever wondered what the actual Unicode-UTF algorithm was? i was debugging an issue and wrote it up to verify that the inbuilt Java converter was worker correctly. Here it is


public static void DumpUTF8(int c) {
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;

if (c &lt; 0x80) {

b1 = (byte) (c &gt;&gt; 0 &amp; 0x7F | 0x00);
b2 = 0;
b3 = 0;
b4 = 0;
} else if (c &lt; 0x0800) {
b1 = (byte) (c &gt;&gt; 6 &amp; 0x1F | 0xC0);
b2 = (byte) (c &gt;&gt; 0 &amp; 0x3F | 0x80);
b3 = 0;
b4 = 0;
} else if (c &lt; 0x010000) {
b1 = (byte) (c &gt;&gt; 12 &amp; 0x0F | 0xE0);
b2 = (byte) (c &gt;&gt; 6 &amp; 0x3F | 0x80);
b3 = (byte) (c &gt;&gt; 0 &amp; 0x3F | 0x80);
b4 = 0;
} else if (c &lt; 0x110000) {
b1 = (byte) (c &gt;&gt; 18 &amp; 0x07 | 0xF0);
b2 = (byte) (c &gt;&gt; 12 &amp; 0x3F | 0x80);
b3 = (byte) (c &gt;&gt; 6 &amp; 0x3F | 0x80);
b4 = (byte) (c &gt;&gt; 0 &amp; 0x3F | 0x80);
}

System.out.println("UTF dump: " + b1 + " " + b2 + " " + b3 + " " + b4);
}

Getting Started with Minion – A tutorial

•August 26, 2008 • Leave a Comment

Note: This is a Work in Progress

Blurb:

Minion is a  full-text search engine that provides for ranked boolean querying, as well as proximity and relational querying. It provides a simple API for indexing and retrieval as well as for document similarity and document classification operations.

It’s rather new at the time of writing this post and as such there aren’t many “getting started” aka “Minion for Dummies” tutorials out there . I’m going to attempt to address this in a small way.

1. Download the distribution from https://minion.dev.java.net/ (either the tarball or from svn) and compile using “ant” or “ant jar”.

2. Upon building, you should see  a minion.jar file at <MINION_DIR>/dist and also <MINION_DIR>/javalib/LabsUtil.jar .

3. Fire up your favourite IDE and create a Java Project. Add the two jars above to the project and you should be ready to go. Copy and paste the code as needed.

1. Simple example indexing and querying upon a few text strings.


package com.il.minion.learn;

import java.util.List;
import com.sun.labs.minion.Result;
import com.sun.labs.minion.ResultSet;
import com.sun.labs.minion.SearchEngine;
import com.sun.labs.minion.SearchEngineException;
import com.sun.labs.minion.SearchEngineFactory;
import com.sun.labs.minion.SimpleIndexer;
import com.sun.labs.minion.FieldInfo;
import com.sun.labs.minion.FieldInfo.Attribute;

import java.util.EnumSet;

public class MinionVer1 {

	/**
	 * @param args
	 * @throws SearchEngineException
	 */
	public static void main(String[] args) throws SearchEngineException {

		String indexDir = "c:/tmp/minion";
		SearchEngine searchEngine = SearchEngineFactory
				.getSearchEngine(indexDir);

		// search engine config
		searchEngine.defineField(new FieldInfo("testbody", EnumSet.of(
				Attribute.INDEXED, Attribute.TOKENIZED, Attribute.VECTORED,
				Attribute.SAVED), FieldInfo.Type.STRING));

		searchEngine.defineField(new FieldInfo("id", EnumSet.of(
				Attribute.INDEXED, Attribute.TOKENIZED, Attribute.VECTORED,
				Attribute.SAVED), FieldInfo.Type.FLOAT));

		SimpleIndexer simpleIndexer = searchEngine.getSimpleIndexer();
		createSampleTestData(simpleIndexer);

		String query = "Linux";
		ResultSet rs = searchEngine.search(query);
		List results = rs.getResults(0, 10); // could alternatively use
		// getAllResults

		for (Result r : results) {
			System.out.println("result score = " + r.getScore() + " "
					+ r.getSingleFieldValue("testbody") + " *** " + r.getKey() + " "
					+ r.getSingleFieldValue("id") + " "
					+ r.getField("testbody").size());
		}
		searchEngine.close();
	}

	private static void createSampleTestData(SimpleIndexer si) {
		// strings borrowed from wikipedia entries
		si.startDocument("doc1");
		si
				.addField(
						"testbody",
						"Linux is a modular Unix-like operating system. It derives much of its basic design from principles "
								+ "established in Unix during the 1970s and 1980s. Linux uses a monolithic kernel, the Linux kernel, which handles "
								+ "process control, networking, and peripheral and file system access. Device drivers are integrated directly with the kernel.");
		si.addField("id", 1.0f);
		si.endDocument();

		si.startDocument("doc2");
		si
				.addField(
						"testbody",
						"The name Linux comes from the Linux kernel, originally written in 1991 by Linus Torvalds. "
								+ "The system's utilities and libraries usually come from the GNU operating system, announced in "
								+ "1983 by Richard Stallman. The GNU contribution is the basis for the alternative name GNU/Linux.");
		si.addField("id", 2.0f);
		si.endDocument();

		si.startDocument("doc3");
		si
				.addField(
						"testbody",
						"Penguins (order Sphenisciformes, family Spheniscidae) are a group of aquatic, flightless birds living "
								+ "almost exclusively in the Southern Hemisphere. The number of penguin species is debated. Depending on which authority "
								+ "is followed, penguin biodiversity varies between 17 and 20 living species, all in the subfamily Spheniscinae. ");
		si.addField("id", 3.0f);
		si.endDocument();

		si.startDocument("doc4");
		si
				.addField(
						"testbody",
						"The Linux landscape is constantly changing and has a strong community of both developers and users. But where is Linux the most "
								+ "popular, and where are the different Linux distributions the most popular? To try to answer these questions, we have looked at "
								+ "data from Google with the highly useful Insights for Search, which gave us a number of interesting and often surprising results.");
		si.addField("id", 4.0f);
		si.endDocument();
		si.finish();
	}

}