Top 3 things to keep people motivated and engaged

According to Gallup research there are top 3 things which make people top performers:

  1. At work, I have the opportunity to do what I do best every day. This is the single-best survey item you can ask an employee. If they score high on this, it means they have been assigned a job for which they have the talent to excel. Mastering this begins with companies identifying employees’ strengths and putting them in the right roles.
  2. There is someone at work who encourages my development.
  3. At work, my opinions seem to count.

Full article: http://www.linkedin.com/today/post/article/20130322105453-14634910-beware-of-managers-from-hell

Easy way to install Cloudera CDH on remote machine (e.g. Amazon EC2 instance)

1) Connect to your remote host using SSH
2) Then in terminal do the following:

$ wget http://archive.cloudera.com/cm4/installer/latest/cloudera-manager-installer.bin
$ chmod +x cloudera-manager-installer.bin
$ ./sudo cloudera-manager-installer.bin

It will start setup wizard, and from now on just follow installation steps from this wizard

There is a trick here on how to install CDH cluster on existing Amazon EC2 spot instances instead of creating new EC2 on-demand instances. To do this Cloudera manager must be installed and executed from local machine (or virtual machine running on local computer) rather than from EC2 instance. In such mode it won’t attempt to auto-create new EC2 instances, but will  ask for IP addresses of the servers to be used for installation.

Agile software development – definition in 12 bullets

  • Customer satisfaction comes from quick delivery of working software.
  • Change is welcome regardless of the stage of development.
  • Deliver working software frequently.
  • Business and development must work hand in hand daily.
  • Build projects with motivated teams. Give them the tools and trust them to get the job done.
  • Face-to-face communication is the most effective form.
  • Working software is the number-one measure of success.
  • Strive for sustainable development. All members of the team should be able to maintain the pace of development indefinitely.
  • Continue to strive for technical excellence and good design.
  • Minimizing waste by eliminating unnecessary work.
  • Self-organizing teams generate the best requirements, architectures, and designs.
  • At regular intervals, have the team reflect to determine how to improve.

Found this in Michael T. Minella book. Looks as perfect description of Agile process, 12 lines worth a fat book.

Prefix Table (Trie) implementation in Java

Recently I needed to write an efficient algorithm which determines predefined prefix from input string. Specifically – given a phone number determine a country code and area code associated with this number.
Requirements for performance and memory use was very aggressive, because this code was running in a batch mode handling hundreds of millions records.
Java collection has no appropriate data structure, so I implemented it on my own.
Below is a Java version of prefix table or Trie (http://en.wikipedia.org/wiki/Trie)

Prefix Table (Trie) implementation in Java

package vkroz.collection;

import java.util.HashMap;
import java.util.Map;

/**
 * Prefix table based on trie structure. Allows to perform incremental lookup
 * and match based on search key prefixes (classic example - determine phone
 * area code for given phone number)
 * 
 * @param <V>
 *            a type of value object to be stored along with prefix (e.g when
 *            key is a country name, the value could be a name of the country)
 * 
 * @author Vladimir Kroz
 */
public class Trie<V> {

	Entry<V> entry;
	char key;
	Map<Character, Trie<V>> childrens;

	public Trie() {
		this.childrens = new HashMap<Character, Trie<V>>(10);
		entry = new Entry<V>();
	}

	/** non-public, used by _put() */
	Trie(char key) {
		this.childrens = new HashMap<Character, Trie<V>>(10);
		this.key = key;
		entry = new Entry<V>();
	}

	public void put(String key, V value) {
		_put(new StringBuffer(key), new StringBuffer(""), value);
	}

	void _put(StringBuffer remainder, StringBuffer prefix, V value) {
		if (remainder.length() > 0) {
			char keyElement = remainder.charAt(0);
			Trie<V> t = null;
			try {
				t = childrens.get(keyElement);
			} catch (IndexOutOfBoundsException e) {
			}
			if (t == null) {
				t = new Trie<V>(keyElement);
				childrens.put(keyElement, t);
			}
			prefix.append(remainder.charAt(0));
			t._put(remainder.deleteCharAt(0), prefix, value);
		} else {
			this.entry.value = value;
			this.entry.prefix = prefix.toString();
		}

	}

	/**
	 * Retrieves element from prefix table matching as a prefix to provided key.
	 * E.g. is key is "abcde" and prefix table has node "ab" then this call will
	 * return "ab"
	 * 
	 * @param key
	 *            a string which starts with prefix to be searched in the table
	 *            (e.g. phone number)
	 * @return an Object assosiated with matching prefix (i.e if key is a phone
	 *         number it may return a corresponding country name)
	 */
	public V get(String key) {
		return _get(new StringBuffer(key), 0);
	}

	/**
	 * Returns true if key has matching prefix in the table
	 */
	public boolean hasPrefix(String key) {
		return ((this.get(key) != null) ? true : false);
	}

	V _get(StringBuffer key, int level) {
		if (key.length() > 0) {
			Trie<V> t = childrens.get(key.charAt(0));
			if (t != null) {
				return t._get(key.deleteCharAt(0), ++level);
			} else {
				return (level > 0) ? entry.value : null;
			}

		} else {
			return entry.value;
		}
	}

	@Override
	public String toString() {
		return "Trie [entry=" + entry + ", key=" + key + ", childrens="
				+ childrens + "]";
	}

	static public class Entry<V> {
		String prefix;
		V value;

		public Entry() {
		}

		public Entry(String p, V v) {
			prefix = p;
			value = v;
		}

		public String prefix() {
			return prefix;
		}

		public V value() {
			return value;
		}

		@Override
		public String toString() {
			return "Entry [prefix=" + prefix + ", value=" + value + "]";
		}

	}
}

Usage example

package vkroz.collection;

import junit.framework.Assert;

import org.junit.Test;

public class TrieTest {

	@Test
	public void testGetPrefix() {
		Trie<String> pt = new Trie<String>();
		pt.put("58241", "Venezuela");
		pt.put("93", "Afghanistan");
		pt.put("931", "AfghanistanMobile");
		pt.put("24491", "Angola - Mobile - Movicel" );
		pt.put("26377", "Zimbabwe - Mobile - Econet" );
		pt.put("263953", "Zimbabwe - Premium Services" );

		Assert.assertEquals("Venezuela", pt.get("582412222222222"));
		Assert.assertEquals("Venezuela", pt.get("58241000000"));
		Assert.assertEquals("Afghanistan", pt.get("938998987878"));
		Assert.assertEquals("Afghanistan", pt.get("93xxx"));
		Assert.assertEquals("AfghanistanMobile", pt.get("931xxx"));
		Assert.assertNull(pt.get("00263953000000000"));
	}

	@Test
	public void testHasPrefix() {
		Trie<String> pt = new Trie<String>();
		pt.put("58241", "Venezuela");
		pt.put("93", "Afghanistan");
		pt.put("24491", "Angola - Mobile - Movicel" );
		pt.put("26377", "Zimbabwe - Mobile - Econet" );
		pt.put("263953", "Zimbabwe - Premium Services" );

		Assert.assertTrue(pt.hasPrefix("5824111111111111"));
		Assert.assertTrue(pt.hasPrefix("2449111111111"));
		Assert.assertTrue(pt.hasPrefix("935824111111111111"));
		Assert.assertFalse(pt.hasPrefix(""));
		Assert.assertFalse(pt.hasPrefix("5"));
		Assert.assertFalse(pt.hasPrefix("263952000000"));

	}
	
}

Programming Android: Exclude Activity from excecution by “Back” button

Requirement: Implement activity which can be activated only when explicitly started by Intent, and cannot be executed by pressing “Back” button on the device.

Solution: There are two useful Intent’s flags can be used: FLAG_ACTIVITY_NO_HISTORY and FLAG_ACTIVITY_CLEAR_TOP.

Review the following scenarios: assume we have activities A, B and C. The are called in the order A->B->C (imagine it could be some kind of the wizard flow). And we want to ensure that user will never open B once it passed control to C. In that case A should start B with flag FLAG_ACTIVITY_NO_HISTORY, hence B will not be remembered in the stack history and if user presses “Back” button while C is open – he will be moved directly to A

public class Activity_A extends Activity {
	@Override
    protected void onCreate(Bundle savedState) {
        super.onCreate(savedState);
        setContentView(R.layout.activity1);
        Button button = (Button) findViewById(R.id.Button01);
        button.setOnClickListener(mClickListener);
    }

	private final OnClickListener mClickListener = new OnClickListener() {
	@Override
        public void onClick(View v) {
		Intent i = new Intent(Activity_A.this, Activity_B.class);
		i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
		startActivity(i);
        }
    };

}

 

Another flag FLAG_ACTIVITY_CLEAR_TOP will be helpful when clear history. For example – use this flag if C  starts A and need to disable using “Back”  button to go back from A to C.

public class Activity_C extends Activity {
    @Override
    protected void onCreate(Bundle savedState) {
        super.onCreate(savedState);
        setContentView(R.layout.activity1);
        Button button = (Button) findViewById(R.id.Button01);
        button.setOnClickListener(mClickListener);
    }

    private final OnClickListener mClickListener = new OnClickListener() {
	@Override
        public void onClick(View v) {
		Intent i = new Intent(Activity_C.this, Activity_A.class);
		i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(i);
        }
    };
}

 

Note 1: Android manifest has attribute corresponding to FLAG_ACTIVITY_NO_HISTORY flag

android:noHistory

Note 2: combining these two flags on the same activity have an unusual results --  both flags are ignored. E.g if you make a call like this:

	Intent i = new Intent(Activity_C.this, Activity_B.class);
	i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
	startActivity(i);

then despite my expectations, once Activity_B is started you still can go back to Activity_C by pressing "Back" button.

Android-active-record, Intro

By this post I open a set of short tutorials about android-active-record library.

‘Android-Active-Record’ was created to simplify and streamline operations with Android SQLite database. It allows to define DB schema and persist your Java objects by just calling a Java APIs, whiteout boilerplate code for mapping between Java and SQL.

Actually the library combines paradigms introduced by JavaEE Persistency Framework and ActiveRecord from Ruby on Rails.

In the heart of the framework is ActiveRecordBase class which provides APIs to perform transparent CRUD (Create/Retrieve/Update/Delete) operations on Java classes.

Use example:

Assume you have a table ‘USER’ and you need to store and retrieve information in it. The table structure is

CREATE TABLE USER 
(
	_id integer primary key, 
	FIRST_NAME text, 
	LAST_NAME test
);

So, basically all you need to do for making CRUD operations on this table is to create corresponding entity class:

/**
 * Example entity. Class name corresponds to a database table;
 * class attributes correspond to table fields.
 */
public class User extends ActiveRecordBase {
	public String firstName;
	public String lastName;
	public User() {
	}
}

And manipulate it via set of simple APIs

try {
	// Open database
	_db = ActiveRecordBase.open(this, &quot;mysqlite.db&quot;, 1);

	// Create new entity
	User user = _db.newEntity(User.class);
	user.firstName = &quot;John&quot;;
	user.lastName = &quot;Smith&quot;;
			
	// Persist it to DB
	user.save();
			
	// Or find and retrieve record from DB by it's primary key
	long id = 123;
	User user2 = _db.findByID(User.class, id);
			
} catch (ActiveRecordException e) {
	// There is also improved logger class, 
	// Allows to print log messages using 'printf'-style formats
	Logg.e(TAG, e, &quot;(%t) %s.initDb(): Error=%s&quot;, CNAME, e.getMessage());
}

The project code and sources are located at: http://code.google.com/p/android-active-record/ See also another blog about this project: http://w2davids.wordpress.com/android-activerecord-activerecord-android-style/