Wednesday, May 22, 2013

The Oilman and his Parrot.


STORY II. 

The Oilman and his Parrot.

 An oilman possessed a parrot which used to amuse him with its agreeable prattle, and to watch his shop when he went out. One day, when the parrot was alone in the shop, a cat upset one of the oil-jars. When the oilman returned home he thought that the parrot had done this mischief, and in his anger he smote the parrot such a blow on the head as made all its feathers drop off, and so stunned it that it lost the power of speech for several days. But one day the parrot saw a bald-headed man passing the shop, and recovering its speech, it cried out, "Pray, whose oil-jar did you upset?" The passers-by smiled at the parrot's mistake in confounding baldness caused by age with the loss of its own feathers due to a blow.

Rumi, Maulana Jalalu-'d-din Muhammad (2011-05-16). The Masnavi I Manavi of Rumi Complete 6 Books (Kindle Locations 107-112). OrangeSky Project. Kindle Edition.  

Tuesday, May 14, 2013

Junit 4.11 cheatsheet


Assertion - org.junit.Assert

  1. Equals, NotEquals, True, False, Null, NotNull - Arrays, Object & Strings

Test Aggregation

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({
  TestFeatureLogin.class,
  TestFeatureLogout.class,
  TestFeatureNavigate.class,
  TestFeatureUpdate.class
})

public class FeatureTestSuite {
  // the class remains empty,
  // used only as a holder for the above annotations
}

Exception Testing

  @Test(expected= IndexOutOfBoundsException.class) 
  public void empty() { 
       new ArrayList<Object>().get(0); 
  }
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void shouldTestExceptionMessage() throws IndexOutOfBoundsException {
        List list = new ArrayList();

        thrown.expect(IndexOutOfBoundsException.class);
        thrown.expectMessage("Index: 0, Size: 0");
        list.get(0); // execution will never get past this line
    }

Matchers and assertthat

assertThat(x, is(3));
assertThat(x, is(not(4)));
assertThat(responseString, either(containsString("color")).or(containsString("colour")));
assertThat(myList, hasItem("3"));

Ignoring tests


@Ignore("Test is ignored as a demonstration")
@Test
public void testSane() {
    assertThat(1, is(1));
}

Timeout for tests

@Test(timeout=1000)
public void testWithTimeout() {
  ...
}
public class HasGlobalTimeout {
    public static String log;

    @Rule
    public Timeout globalTimeout = new Timeout(10000); // 10 seconds max per method tested

    @Test
    public void testInfiniteLoop1() {
        log += "ran1";
        for (;;) {
        }
    }

    @Test
    public void testInfiniteLoop2() {
        log += "ran2";
        for (;;) {
        }
    }
}

Java code can be difficult to test for thread safety when multithreading.
The article at http://www.planetgeek.ch/2009/08/25/how-to-find-a-concurrency-bug-with-java/ describes a method of exposing concurrency bugs that adds a new assertion method assertConcurrent.
To use this you pass in a Collection of Runnables that are your arrange\act\assert test on the SUT, they all run at the same time in theassertConcurrent method; the chances of triggering a multithreading code error, and thereby failing some assertion are greatly increased:
The assertConcurrent method from the article is:
 public static void assertConcurrent(final String message, final List extends Runnable> runnables, final int maxTimeoutSeconds) throws InterruptedException {
   final int numThreads = runnables.size();
   final List<Throwable> exceptions = Collections.synchronizedList(new ArrayList<Throwable>());
   final ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
   try {
  final CountDownLatch allExecutorThreadsReady = new CountDownLatch(numThreads);
  final CountDownLatch afterInitBlocker = new CountDownLatch(1);
  final CountDownLatch allDone = new CountDownLatch(numThreads);
  for (final Runnable submittedTestRunnable : runnables) {
    threadPool.submit(new Runnable() {
   public void run() {
     allExecutorThreadsReady.countDown();
     try {
    afterInitBlocker.await();
    submittedTestRunnable.run();
     } catch (final Throwable e) {
    exceptions.add(e);
     } finally {
    allDone.countDown();
     }
   }
    });
  }
  // wait until all threads are ready
  assertTrue("Timeout initializing threads! Perform long lasting initializations before passing runnables to assertConcurrent", allExecutorThreadsReady.await(runnables.size() * 10, TimeUnit.MILLISECONDS));
  // start all test runners
  afterInitBlocker.countDown();
  assertTrue(message +" timeout! More than" + maxTimeoutSeconds + "seconds", allDone.await(maxTimeoutSeconds, TimeUnit.SECONDS));
   } finally {
  threadPool.shutdownNow();
   }
   assertTrue(message + "failed with exception(s)" + exceptions, exceptions.isEmpty());
 }
Another article giving an overview of alternative stragies at http://tempusfugitlibrary.org/recipes/2012/05/20/testing-concurrent-code/ might also be useful.

Java Concurrency Bookshelf

Friday, May 10, 2013

Cricbay DRR calculation technique made easy


Seaon is coming to an end and everyone is closely watching team DRR and here is an simple method of predicting match DRR.

10 is the magic number to get 0.50 DRR.


Bat first

win by 10 runs and your DRR will be 0.50.
likewise 20 runs diff will give 1.00 DRR etc


Bat second

You need the below formula to calcuate balls required to get 0.50 DRR.
(runs/runs+10) * 120)
i.e.
chasing 60 runs you will need ==> 60/70 * 120 ==> 103 balls to get 0.50 DRR
chasing 80 you will do ==> 80/90 * 120 ==> 108 balls to get 0.50 DRR

Note: if you are still wondering how to calculate loosing DRR just remember DRR lost by one team is gain by others i.e. just put a minus infront of winners DRR.
Note: All the calculations are rounded to nearest decimal.



--- Wondering how I got to the nos ---

Bat first

DRR formula ==> (Runs scored/Ball faced - Runs gave/Balls bolwed) * 6
If you bat first and win that way you and your oppoent will end up playing 120 balls either by playing all balls or loosing all wickets.
Let b == Balls faced == Balls bolwed == 120, r1 is runs scored and r2 is runs gave. Now apply the variables to the formula.
( r1/b - r2/b ) * 6
(r1 - r2) * 6 / 120
(r1 - r2) * 1/20
i.e If r1 - r2 equals 10 then DRR will be 10 * 1/20 ==> 0.50

Bat Second

Let x == Runs gave == Runs chased ==> this a variable
Let y is balls needed to chase x runs. Now apply these to formula
(x/y - x/120) * 6 ==> i.e. (x/y - x/120) should be equal to 0.166 so when multiply by 6 will get 1 DRR
x/y - x/120 = 0.166
(120x - xy) / 120y = 0.166
120x -xy = 0.166 * 120y
120x -xy = 19.92.y
120x = 19.92y + xy
120x = y (x + 19.92)
y = 120x / (x+20)
y = x/x+20 * 120
i.e. for DRR 0.50 you need to find balls by x/x+20 * 120

eg to get 0.50 DRR for below runs you need following balls.

chasing 50 runs balls = 50/60 * 120 ==> 100
chasing 60 runs balls = 60/70 * 120 ==> 103
chasing 70 runs balls = 70/80 * 120 ==> 105
chasing 80 runs balls = 80/90 * 120 ==> 108
chasing 90 runs balls = 90/100 * 120 ==> 109

Hope this helps every team member keep a tap on DRR.

Thursday, May 2, 2013

Takeaway from The Leadership of Muhammad (SAW) by John Adair

Key Points



l A leader should exemplify or personify the qualities
expected, required and admired in their working
groups. A leader of soldiers, for example, needs to

demonstrate courage, ‘the soldier’s virtue’, as 
Shakespeare called it.
l Courage is a quality shown by Muhammad at
Hunayn: it is that which enables people to meet 
danger without giving way to fear, to act bravely 
under stress or to endure in times of adversity.
l All members of working groups, organizations or
communities – at all times in known history – share
one thing in common: they are all persons with a 
common and constant human nature.
l A universal leader, then, will be a person who
exemplifes such distinctively human qualities as
goodness, kindness, humaneness and compassion. Did 
you see any of these qualities in Muhammad?
l Another generic quality of universal leaders is

l All members of working groups, organizations or
communities – at all times in known history – share
one thing in common: they are all persons with a 
common and constant human nature.
l A universal leader, then, will be a person who
exemplifes such distinctively human qualities as
goodness, kindness, humaneness and compassion. Did 
you see any of these qualities in Muhammad?
l Another generic quality of universal leaders is
humility. The word comes from the Latin root humus 
(ground, earth), related to homo (man). When 
Muhammad spread his cloak, lowered himself and sat 
on the ground with people at the same level, it was an 
act of humility. Compare a king sitting high upon a 
throne above his subjects, who abase themselves 
before him. As they will tell you in Ghana, ‘Don’t 
expect to be offered a chair when you visit a place 
where the chief himself sits on the foor.’

It is the tribe that tells the chief how to do his job.
ArAB PrOverB


l Leadership is done from in front. In the human 
context a human leader may not always, on a physical 
journey, be the person out in front, just as the shepherd 
sometimes works behind the moving fock. But 
spiritually a leader is the one who leads from the front.
l In leadership, example is everything. 
As the Moorish 
proverb says: When the shepherd  is corrupt, so is his
flock.

l Apart from leading the flock to pasture and water
across the wilderness, shepherds have to keep the flock
together and care for each individual sheep or lamb. 
They will know the sheep by name, and the sheep in 
turn will know the shepherd’s voice.
l A good (Greek: kalos, skilled) shepherd meets on the
level of the flock of sheep the three interactive circles

of needs that are present in all human work groups at
all times in history: to achieve the common task, to be 
held together as a working unity, and the needs that 
individuals bring into the group by virtue of being 
individual embodied persons.



l Muhammad looked up to his grandfather Abd
al-Muttahib, briefy his father as well. He personifed 
what the Arabs called muruwwa, the virtue of being a 
man. It connotes a cluster of virtues: bravery, 
generosity, practical wisdom and honour, all highly 
valued and praised in Arab tribal culture. These are 
the qualities we see in Muhammad.
l Practical wisdom – the Greeks called it phronesis – is
essentially the art of knowing the right thing to do at
the right time and in the right away. It encompasses 
the ability to see ahead, to predict how things will 
unfold, and also to forecast what will be the 
consequences of a given course of action.
l Being a caravan leader – being a leader in any
context – calls for such judgement or practical
wisdom: the ability to come to sound conclusions, to 
make wise decisions based upon them, and to act 
upon them with decisiveness and determination.
l No one is born wise; a leader becomes wise – acquires
practical wisdom – through natural aptitude, practice
and refection. Wisdom, like an Arab bow made of 

different kinds of wood, has three elements: 
intelligence, experience and goodness.
l The caravan leader is not the caravan’s offcial guide,
or dalil, who piloted the camel train through his
knowledge of the landmarks. The qaid fulflled the 
generic or universal role of leader: achieving the task 
successfully, maintaining group coherence or unity, 
and caring for individual members.
l Meeting these three areas of interactive or
overlapping need called for skill, but it was best
performed in a spirit of service. Serve to lead. 
Muhammad learnt that great lesson. For an example 
of the humble service he rendered to a companion on 
a journey when he was the leader, see above.
On a journey the leader of a people is their servant.
MuHAMMAD


l All humankind has passed – or is passing – through a
period when the dominant institution of society is the
tribe. This fact has given us innate preferences for 
certain characteristics in our leaders. We expect them, 
if they are to fulfl the generic role of leader, to be 
both competent and benevolent.

l All humankind has passed – or is passing – through a
period when the dominant institution of society is the
tribe. This fact has given us innate preferences for 
certain characteristics in our leaders. We expect them, 
if they are to fulfl the generic role of leader, to be 
both competent and benevolent.


l The fnest pearls in the world come from the Arabian
Gulf. Pearls were traditionally graded into fve kinds. 
The pearl of highest quality, the perfect pearl, is called 
al-Jiwan. Among all the qualities of leadership, great 
and small, integrity is al-Jiwan

l Integrity implies such rectitude that one is
incorruptible or incapable of being false to a trust or
a responsibility or to one’s own standards. 
As the 
Latin proverb says: Integrity is the noblest possession.
l There can be no confdence without truth. If you want 
to lose the confdence of your team, try any of the 
following behaviours: dishonesty, duplicity, 
deceitfulness, lying, dissimulation or manipulation.
l ‘Trust, like the soul, once gone is gone for ever’
(Catullus, Roman poet, c84–54 bce).
l Those occupying leadership roles who completely
lack integrity are what we call ‘blind shepherds’. 
They are not really ‘bad’ leaders, because they are not 
leaders at all: they are misleaders. Woe to the people 
afficted with them! 
As an ancient Hebrew proverb 
says: When God wants to punish the sheep he sends
them a blind shepherd.
People think of leaders as men or women devoted to
service, and by service they mean that they serve their
followers…

The real leader serves truth, not people.
N B YeATS, LETTERS TO HIS SON W B YEATS (1944)



l By sharing in the labours, dangers and hardships of
his people Muhammad exemplifed a universal
principle of good leadership. It is what – deep down – 
people expect of their leaders, and when it doesn’t 
happen it always produces adverse comment.
l There is the authority of position and the authority of
knowledge – ‘Authority fows from the one who
knows.’ But sharing in hardship confers upon a leader 
something quite rare – moral authority.
l Such conduct by the best leaders wins them more than
the respect of their people – it attracts their love. And 
love is the greatest power in the world. As Huananzi 
wrote in a classic Taoist text:
In ancient times good generals always were in the
vanguard themselves. They didn’t set up canopies in the
heat and didn’t wear leather in the cold; thus they
experienced the same heat and cold as their soldiers.
They did not ride over rough terrain, always
dismounting when climbing hills; thus they experienced
the same toil as their soldiers.
They would eat only after food had been cooked for
the troops, and they would drink only after water had
been drawn for the troops; thus they experienced the
same hunger and thirst as their soldiers.
In battle they would stand within range of enemy fre;
thus they experienced the same dangers as their soldiers.
So in their military operations, good generals always
use accumulated gratitude to attack accumulated
bitterness, and accumulated love to attack accumulated
hatred. Why would they not win?


Remember that your position does not give you the right
to command. It only lays upon you the duty of so living
your life that others may receive your orders without
being humiliated.
DAG HAMMArSKJ√∂LD, FOrMer SeCreTArY-GeNerAL  
OF THe uNITeD NATIONS





l Humility at its simplest is knowing that you are not
God.

l Being humble as a leader is essentially about not
being arrogant. 
According to the Arab proverb: 
Arrogance diminishes wisdom. A humble person, one 
who lacks all signs of pride both in spirit and in 
outward show, is walking on a path that leads to 
practical wisdom.
l ‘Humility is just as much the opposite of self-
abasement as it is of self-exaltation’, wrote Dag
Hammarskjöld, when he was Secretary-General of the
United Nations.
l ‘Do not pursue a matter of which you are ignorant’,
counsels the Qur’an. Wise leaders will consult their 
team before making a particular decision. They will 
listen especially to those who have technical knowledge 
or practical experience of the matter in hand.
l ‘Let nothing prevent you from changing your
previous decision’, said Umar to his generals, ‘if
after consideration you feel that the previous
decision was incorrect.’
l The crown of a good disposition is humility, 
says an Arab proverb, refecting like a pearl both the light of
the Qur’an and the iridescent spirit of Muhammad.

He who is deprived of his share of gentleness is deprived
of his share of the good of this world and the next.
MuHAMMAD


l You can be appointed a ruler, governor, commander
or manager, but you are not a leader until your
appointment is ratifed in the hearts and minds of
those under you.
l Reciprocity is a fundamental law in all personal or
social relations. What you give as a leader will be 
what you tend to receive. 
As an Arab proverb says, He
who would be loved must begin by loving.

l A good leader is someone whom people will follow
through thick and thin, in good times and bad,
because they have confdence in the leader as a person,
the leader’s ability and his or her knowledge of the job
and because they know they matter to the leader.
l Apart from exemplifying the qualities and values of
their group, leaders should have the generic qualities
of leadership: enthusiasm, integrity, frmness and 
fairness, resilience, warmth or humanity, and humility.
l The nature of the feld or context does affect
leadership: different felds of work call for different 
leaders. A leader needs to have the necessary 
knowledge or experience, for authority fows to the
one who knows.
l The three intersecting circles point you to the generic
role of leader. You can always improve your skills in 
performing the necessary functions. Leadership is 
about doing – it is action centred. Fulfl the role of 
leader and let your qualities look after themselves.

What one does, one becomes.
SPANISH PrOverB