Posted on Apr 2, 2011

Solution for “cannot find any android targets in this sdk” (IntelliJ IDEA)

This week I’ve been playing with the Android SDK using IntelliJ IDEA. One of the problems that I encountered when I was creating an Android project in IDEA was the error “cannot find any Android targets in this sdk.” After surfing the net for a bit, I found the solution to this problem here. To paraphrase a bit, the solution is to simply run tools/android, under android_sdk_YOUR_OS, to retrieve the targets, check the option that says “force https to be fetched using http” under settings. And finally, under “Available packages,” select the version of Android you want.

Posted on Mar 22, 2011

The Josephus problem in Python

There are several places that describe this problem in detail. However, there is one place that describes very well (IMHO). That is the Wolfram MathWorld site. Since I am reading Python Algorithms by Magnus Lie Hetland, and I am trying to improve my python skills, I decided to tackle this problem using python. Here is the code. I hope you will find it useful.


#!/usr/bin/env python
# encoding: utf-8
"""
Josephus permutation. A theoretical problem related to a certain
counting out game. See en.wikipedia.org/wiki/Josephus_problem
or http://mathworld.wolfram.com/JosephusProblem.html for more details.

Created by Huascar A. Sanchez on 2011-03-21.
Copyright (c) 2011 Huascar A. Sanchez. All rights reserved.
"""

from collections import deque
def Josephus(m,n,s = 1):
    """Josephus problem. Only s survivor (s) (the winner(s)).
       Input: n - number of people in the circle
              m - frequency of people to be killed.
              s - number of survivors you want.
       Output: not output. all results will be printed
       on screen.
    """
    N = n + 1
    M = m - 1
    S = s;
    if S <= 0: S = 1 # only one survivor
    Q = deque()
    #print("construct the list\n")
    for p in range(1,N):
        Q.append(p)

    toString = []
    #print("start the game now!!\n")
    while len(Q) > S:
        for dp in range(0,M):
            Q.append(Q.popleft())
        toString.append(str(Q.popleft()))

    print(' '.join(toString))
    while Q:
       print("winner " + str(Q.popleft()))

Josephus(5,9)
Josephus(3,40,2)

Posted on Jul 12, 2008

Class.cast(..) and Generics – a powerful combination

As you know when it comes to casting a la Java 1.4 a developer will have to write, typically, something like this:


Object a = "iron man";
String  b = (String)a;

Well, there is nothing wrong with this code. However, it is not pretty :). With Java 5.0 the casting mechanism is more explicit and nicer. The best thing of it is that it does not throw warnings, which it is a big deal :)


Object a = "iron man";
String  b = String.class.cast(a);

Not that bad, huh? Hmm, well…Okay, Okay, you got me. This still does not look that pretty and it is more verbose than the (Object)a style. How can I make it prettier? the ans: Generics


public static <T, E extends T> E cast(T me, Class<? extends E> to){
    return to.cast(me);
}
....
Object a = "iron man";
String  b = cast(a, String.class); 

Believe it or not, I love this technique. It works like a charm with objects that are part of the same inheritance chain. I know this method requires more tweaking to make it suitable for handling the casting of collections. But hey! this is just a working idea!

Posted on May 28, 2008

Documenting Exceptions via Factory Methods

Jesse described a technique for handling methods that always throws. This is a very interesting technique. Having written that, would it not be nice to encourage the use of this technique, in our Java coding conventions, as a way to document DRY exceptions? Honestly, I’d’ think we should. It would prevent us from repeating the same description of our exceptions numerous times in our JavaDocs… Disclaimer: this is just a very simple example that tries to convey my point :)


/**
 * @throws Violation
 *      due to {@link #unableToFindConfigFile(String, Throwable)}
 */
public void loadConfig() throws
Violation {
  try {
     //.... some code goes here to
     //.... load a config file.
  } catch (RuntimeException re){
	throw unableToFindConfigFile(
           "loadConfig():void",
           re
        );
  }
}

/**
 * @throws Violation
 *      due to {@link #unableToFindConfigFile(String, Throwable)}
 */
public void refreshConfig() throws
Violation {
	loadConfig();
}

private static Violation unableToFindConfigFile(
	String pointOfCall,
	Throwable cause
) throws Violation
{
	final StringBuilder msg = new StringBuilder()
		.append("Error when calling ")
		.append(pointOfCall)
		.append(". Reason:")
		.append(cause);
	throw new Violation(msg.toString(), cause);
}

/**
 * @throws Violation
 *   due to {@link #unableToFindConfigFile(String, Throwable)}
 */
public void loadConfig() throws
Violation {
   try {
	//.... some code goes here to load
	//.... a config file.
    } catch (RuntimeException re){
	throw unableToFindConfigFile(
		"loadConfig():void",
		re
	);
    }
}

/**
 * @throws Violation
 *   due to {@link #unableToFindConfigFile(String, Throwable)}
 */
public void refreshConfig() throws
Violation {
	loadConfig();
}

private static Violation unableToFindConfigFile(
	String pointOfCall,
	Throwable cause
) throws Violation
{
	final StringBuilder msg = new StringBuilder()
		.append("Error when calling ")
		.append(pointOfCall)
		.append(". Reason:")
		.append(cause);
	throw new Violation(msg.toString(), cause);
}

Some of this approach’s benefits:

  1. No more boilerplate text when documenting exceptions.
  2. The intent of the exception is clearly communicated via a factory method.
  3. We are hiding the complexity of the exception’s declaration behind a consistent exterior.

Latest Tweets