Pages

Wednesday, October 31, 2012

JPF summary generation test1

Simple Example

A.java

public int sub(int a, int b)
{
    return a - b;
}
public int testRefactored (int refs, int flags) {
    if (flags != 0) 
    	return flags * sub(flags, flags*3);
    else if (refs != 0)
    	return refs;
    return 10;       
}
(or ( and  (distinct  flags_2_SYMINT 0)  (=  RETURN ( * (flags_2_SYMINT- (flags_2_SYMINT * 3)) flags_2_SYMINT)) )
 ( and  (distinct  refs_1_SYMINT 0)  (=  flags_2_SYMINT 0)   (=  RETURN refs_1_SYMINT) )
 ( and  (=  refs_1_SYMINT 0)  (=  flags_2_SYMINT 0)   (=  RETURN 10) )
)
JPF is smart enough to understand sub() method to give the correct constraints
RETURN ( * (flags_2_SYMINT- (flags_2_SYMINT * 3)

B.java

public int sub(int a, int b)
{
    return a - b;
}
public int testRefactored (int refs, int flags) {
    if (flags != 0) 
    	return flags;
    else if (refs != 0)
    	return refs;
    return 10;       
}
(or ( and  (distinct  flags_2_SYMINT 0)  (=  RETURN flags_2_SYMINT) )
 ( and  (distinct  refs_1_SYMINT 0)  (=  flags_2_SYMINT 0)   (=  RETURN refs_1_SYMINT) )
 ( and  (=  refs_1_SYMINT 0)  (=  flags_2_SYMINT 0)   (=  RETURN 10) )
)

More complex

With this example:
public int sub(int a, int b)
{   
	if (a > b)
		return (a - b);
	else
	    return (10*a + b);
}
public int test (int refs, int flags) {		
	if (flags != 0) 
		return flags * sub(flags, flags*3); << This line causes an issue
	else if (refs != 0)
	   	return refs;
	return 10;       
}
JPF works fine to generate the correct summary:
testCase=test(-100,-100);pc=( >  flags_2_SYMINT[-100] ( *  flags_2_SYMINT[-100] CONST_3)) && ( !=  flags_2_SYMINT[-100] CONST_0);effects=RETURN==( *  (flags_2_SYMINT[-100] - (flags_2_SYMINT[-100] * CONST_3)) flags_2_SYMINT[-100]);solverCalls=2;statementsExecuted=[];positionsExecuted=[];constraints=none
testCase=test(1,1);pc=( <=  flags_2_SYMINT[1] ( *  flags_2_SYMINT[1] CONST_3)) && ( !=  flags_2_SYMINT[1] CONST_0);effects=RETURN==( *  ((flags_2_SYMINT[1] * CONST_3) + (flags_2_SYMINT[1] * CONST_10)) flags_2_SYMINT[1]);solverCalls=2;statementsExecuted=[];positionsExecuted=[];constraints=none
testCase=test(-100,-100);pc=( !=  refs_1_SYMINT[-100] CONST_0) && ( ==  flags_2_SYMINT[0] CONST_0);effects=RETURN==refs_1_SYMINT[-100];solverCalls=2;statementsExecuted=[];positionsExecuted=[];constraints=none
testCase=test(0,0);pc=( ==  refs_1_SYMINT[0] CONST_0) && ( ==  flags_2_SYMINT[0] CONST_0);effects=RETURN==10;solverCalls=2;statementsExecuted=[];positionsExecuted=[];constraints=none
Only to get something's wrong with the listener:
(or  ( and  (>  flags_2_SYMINT ( * flags_2_SYMINT 3))  (distinct  flags_2_SYMINT 0)   (=  RETURN ( * (flags_2_SYMINT- (flags_2_SYMINT * 3)) flags_2_SYMINT)) )
 ( and  (<=  flags_2_SYMINT ( * flags_2_SYMINT 3))  (distinct  flags_2_SYMINT 0)   (=  RETURN ( * ((flags_2_SYMINT * 3)+ (flags_2_SYMINT * 10)) flags_2_SYMINT)) )
 ( and  (distinct  refs_1_SYMINT 0)  (=  flags_2_SYMINT 0)   (=  RETURN refs_1_SYMINT) )
 ( and  (=  refs_1_SYMINT 0)  (=  flags_2_SYMINT 0)   (=  RETURN 10) )
)
 ( and  (<=  flags_2_SYMINT ( * flags_2_SYMINT 3))  (distinct  flags_2_SYMINT 0)   (=  RETURN ( * ((flags_2_SYMINT * 3)+ (flags_2_SYMINT * 10)) flags_...
                                                                                                    ^^^^^^^^^^^^^^
(error "Invalid beginning of an identifer: expected either 'as' or '_' here")
Executing the script...
 ( and  (<=  flags_2_SYMINT ( * flags_2_SYMINT 3))  (distinct  flags_2_SYMINT 0)   (=  RETURN ( * ((flags_2_SYMINT * 3)+ (flags_2_SYMINT * 10)) flags_...
                                                                                                    ^^^^^^^^^^^^^^
(error "Invalid beginning of an identifer: expected either 'as' or '_' here")
sub(flags, flags*3)
I think the generated code should have been (* flags_2_SYMINT 3).

Research questions

  • How does the listener work to transform summary into S-expression code
  • How do I modify the listener to resolve this issue?

Tracing into LTK refactoring library

I needed to trace into eclipse refactoring library, and I could do that by installing eclipse source code. Screen Shot 2012 10 31 at 4 23 29 PM

Lars Vogel's Eclipse Source Code
gives very simple and effective way of installing eclipse source.

How to get file path information from ICompilationUnit?

When you have ICompilationUnit, you can get the java file path for the unit using this code.
IResource resource = iCompilationUnit.getUnderlyingResource();
if (resource.getType() == IResource.FILE) {
    IFile ifile = (IFile) resource;
    String path = ifile.getRawLocation().toString();
}

References

Writing file from CompilationUnit (ASTNode)

When you have an object of iCompilationUnit, you can save it to the file.
  1. You need to create Document object from ICompilationUnit
  2. You need a ASTRewrite object from CompilationUnit
  3. Filling in the Document object using apply() method
  4. Storing the source code string from document.get() method
Document document = new Document(iCompilationUnit.getSource());
ASTRewrite rewriter = ASTRewrite.create(compilationUnit); // ? check if the parameter object type is correct

rewrite.rewriteAST().apply(document);
String source = document.get();

File file = new File(DEST_FILE_PATH);
FileUtils.writeStringToFile(file, source) 

FileUtils

You need to save apache file utilities to use the FileUtils.

References

How you can get CompilationUnit (AST) from Workspace in eclipse?

The starting point is to get WorkSpace, and you can do that with ResourcePlugin#getWorkSpace() method. Eclipse workspaceClick to enlarge
You'll get a New Project with the right click in eclipse.
Screen Shot 2012 10 31 at 9 54 36 AM
You can get the project information using this code.
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
// Get all projects in the workspace
IProject[] projects = root.getProjects();
When you know the name of the project, you can find it.
IProject project = root.getProject("Hello");
Out of many project, you need only Java project.
IJavaProject javaProject = JavaCore.create(project);
Screen Shot 2012 10 31 at 9 54 59 AM

package fragments, compilation unit

Remember the package explorer in eclipse, you also have the project explorer. Inside a Java project, you'll find a lot of elements, which are called package fragments. From the package fragments, you normally want to use source code. getKind() method returns the property of the package fragment.
IPackageFragment[] packages = javaProject.getPackageFragments();
for (IPackageFragment mypackage : packages) {
    if (mypackage.getKind() == IPackageFragmentRoot.K_SOURCE) {
Screen Shot 2012 10 31 at 10 56 30 AM Screen Shot 2012 10 31 at 10 54 30 AM
You can get the ICompilationUnit from package element.
IPackageFragment[] packages = JavaCore.create(project).getPackageFragments();
for (IPackageFragment mypackage : packages) {
	if (mypackage.getKind() == IPackageFragmentRoot.K_SOURCE) {
		for (ICompilationUnit unit : mypackage.getCompilationUnits()) {
			...
		}
	}
}
When you know the name of the type, you can get ICompilationUnit from it.
IType iType = javaProject.findType("PACKAGE_NAME.CLASS_NAME");
org.eclipse.jdt.core.ICompilationUnit iCompilationUnit = iType.getCompilationUnit();

parser and CompilationUnit

CompilationUnit is ASTNode that has the tree inside.
final ASTParser parser = ASTParser.newParser(AST.JLS3); 
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(iCompilationUnit);
parser.setResolveBindings(true); // we need bindings later on
CompilationUnit unit = (CompilationUnit) parser.createAST(null);

Think

  • As you instantiate a specific object (JavaProject for example) from other object(Project for example), you can access the elements in the specific object.

References

Eclipse ICompilationUnit

Compared to concrete class CompilationUnit, ICompilation is an interface as the "I" prepended. Screen Shot 2012 10 31 at 9 36 38 AM
It's for Type representation where as CompilationUnit is for AST representation, and parser object links between the two using Parser#setSource(ICompilationUnit); and parser.createAST(null).

In order to get the ICompilationUnit from java source code, you need to start from Workspace, IProject, IJavaProject and then find IType(The by using findType(TYPE_NAME).

References

Eclipse CompilationUnit

Screen Shot 2012 10 31 at 9 02 43 AM
Eclipse uses compilation unit to represent a class. It's reasonable considering one java source generates one class file with the same name (if we forget about the inner class).

One can think of compilation unit in eclipse as a ASTNode for java code as it subclassing ASTNode. Screen Shot 2012 10 31 at 9 13 20 AM

Getting Compilation is a little bit complicated.
  • One needs to create a parser as parser has a reference to it. Call parser.createAST() to get CompilationUnit. Don't forget to down casting it to CompilationUnit.
  • One needs to setup a parser with the source of ICompilationUnit
And this is the code.
// … lwType is IType object
org.eclipse.jdt.core.ICompilationUnit lwCompilationUnit = lwType.getCompilationUnit();
// create parser and set it up
final ASTParser parser = ASTParser.newParser(AST.JLS3); 
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(lwCompilationUnit);
parser.setResolveBindings(true); // we need bindings later on
// can get CompilationUnit from parser
CompilationUnit unit = (CompilationUnit) parser.createAST(null /* IProgressMonitor */);

References

Duck Typing

Duck Typing enables Polymorphism without Inheritance.

Polymorphism

In construction …

Inheritance

In construction …

Tuesday, October 30, 2012

The Language Toolkit read

http://www.eclipse.org/articles/Article-LTK/ltk.html A subclass of org.eclipse.ltk.core.refactoring.Refactoring must always be created. As is in this quotation, we need to extend Refactoring. Screen Shot 2012 10 30 at 11 27 24 PM As a result of extending Refactoring class, you need to implement four method. Screen Shot 2012 10 30 at 11 28 39 PM

LKT usage hint of eclipse from Use, Disuse, and Misues of Automated Refactorings paper.

Use, Disuse, and Misuse of Automated Refactorings paper has some clues on how to execute the eclipse refactoring in a programmatic way.
  1. It knows the selected string - "selection-text"
  2. The method that contains the selection - "code-snippet"
  3. Source code - "input"
  4. The kind of refactoring (maybe from the menu) - "id"
Screen Shot 2012 10 30 at 10 51 29 PM

simple make example

  • You can use variable by assigning it, and use it with $(), it can be anything, you can even think of it as a macro.
  • You can use $@ to replace the target. @ is a good name to represent the goal(target).
  • $+ means all prerequisites with space separated when multiple is given.
  • %.o:%.c shows the relationship based on extension name. Don't forget it uses % not *.
# 1
# Defining the compiler:
CC=gcc

# Defining the object files:
objects = main.o example.o

# 2
# The default rule - compiling our main program:
all:	sample
		echo all: make complete

# 3
sample: $(objects)
	# If we get here, all the dependencies are now built.
	# Link it:
	$(CC) -o $@ $+

# 4
# Tell make how to build .o files from .c files:
%.o:%.c
	$(CC) -c $+
	
# 5
#Now make sure that make rebuilds files if included headers change:
main.o: main.h defs.h
example.o: example.h defs.h
http://linuxdevcenter.com/pub/a/linux/2002/01/31/make_intro.html?page=2

phony target in make

When you execute make clean, you are using phony target. phony target is a target that doesn't have the dependencies, but only the actions.
# Naming our phony targets
.PHONY: clean install

# Removing the executable and the object files
clean: 
		rm sample main.o example.o
		echo clean: make complete

# Installing the final product
install:
		cp sample /usr/local
		echo install: make complete

How JPF finds the files

site.properties

~/.jpf/site.properties file is the one where all the directory information is located.
# JPF site configuration
user.home = /Users/smcho/
jpf.home = ${user.home}/Dropbox/smcho/workspace/jpf

# can only expand system properties
jpf-core = ${jpf.home}/jpf-core

jpf-symbc = ${jpf.home}/jpf-symbc
extensions+=,${jpf-symbc}

jpf-guided-test = ${jpf.home}/jpf-guided-test
extensions+=,${jpf-guided-test}

jpf-regression = ${jpf.home}/jpf-regression
extensions+=,${jpf-regression}

jpf-porting = ${jpf.home}/jpf-porting
extensions+=,${jpf-porting}
It points to where all the jpf related information are located.

jpf.properties

Now, you can set up your jpf.properties so that you can point to where ever you want.
#--- project specific host VM classpath (used by Java to load classes)
# NOTE: you have to replace the wildcard jar specs with explicit jar pathnames
# if this property file is used from within a build.xml or NetBeans project.xml,
# since both do not support wildcard patterns in classpath specs
jpf-porting.native_classpath =\
   ${jpf-porting}/build/jpf-porting.jar;\
   ${jpf-porting}/lib/*.jar;\
   ${jpf-symbc}/lib/commons-lang-2.4.jar;
   

#--- project specific JPF classpath (used by JPF to load system-under-test classes)
jpf-porting.classpath =\
   ${jpf-porting}/build/examples;

#--- where are the classes for the JPF regression tests (used by host VM and JPF)
jpf-porting.test_classpath =\
   ${jpf-porting}/build/tests
   
#--- project specific JPF sourcepath (used by JPF to locate sources for system-under-test classes)
jpf-porting.sourcepath =\
   ${jpf-porting}/src

#--- other project specific options go here (e.g. 'vm.insn_factory.class' or 'peer_packages')
peer_packages= gov.nasa.jpf.symbc,${peer_packages}
vm.storage.class=nil
search.multiple_errors=true
symbolic.dp=choco

From RunJPF.jar you can specify the file path of properties file.
java -jar /Users/smcho/Dropbox/smcho/workspace/jpf/jpf-core/build/RunJPF.jar \
+shell.port=4242 \
/Users/smcho/Dropbox/smcho/works/tasks/2012/seal/refactoringChecker/tests/case_ini_is_generated_from_ref_finder/TestA/A.jpf -v\
-c jpf.properties
Now, you can modify the properties file to point to the example directory.

JPF Configuration

Screen Shot 2012 10 30 at 5 06 55 PM
java -jar jpf/jpf-core/build/RunJPF.jar +shell.port=4242 A.jpf -v
http://javapathfinder.sourceforge.net/Configuring_JPF_Runtime_Options.html

Java Path Finder tutorial

Screen Shot 2012 10 30 at 4 59 11 PM https://dl.dropbox.com/u/10773282/papers/2012/JPF-lecture-2.pdf http://fm.csl.sri.com/SSFT11/JPF-lecture-2.pdf

Executing eclipse rename refactoring using LTK

With eclipse, one can use Language Tool Kit (LTK). This is an example of how to execute rename refactoring with the LTK API.

Finding a project

IProject is an interface to refer the Project object, and the project can be found using this code.
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject(PROJECT_NAME);
project.open(null /* IProgressMonitor */);

Finding class

Then, we can find the class(IType), and from the type we can get CompilationUnit.
IJavaProject javaProject = JavaCore.create(project);
IType itype = javaProject.findType("smcho.NewName");
org.eclipse.jdt.core.ICompilationUnit icu = itype.getCompilationUnit();

Getting contribution and descriptor

We're renaming a class, so we use getRefactoringContribution() to get contribution, and from the contribution we can get the descriptor.
RefactoringContribution contribution = RefactoringCore.getRefactoringContribution(IJavaRefactorings.RENAME_COMPILATION_UNIT);
RenameJavaElementDescriptor descriptor = (RenameJavaElementDescriptor) contribution.createDescriptor();
Then, you need to set the name of the project, new class name, and CompilationUnit.
descriptor.setProject(icu.getResource().getProject().getName( ));
descriptor.setNewName(NEW_CLASS_NAME); // new name for a Class
descriptor.setJavaElement(icu);

Executing the refactoring

One starts with the status and monitor. With them check initial and final conditions. And finally create change object and perform with a parameter monitor.
RefactoringStatus status = new RefactoringStatus();
try {
    Refactoring refactoring = descriptor.createRefactoring(status);

    IProgressMonitor monitor = new NullProgressMonitor();
    refactoring.checkInitialConditions(monitor);
    refactoring.checkFinalConditions(monitor);
    Change change = refactoring.createChange(monitor);
    change.perform(monitor);
} catch (CoreException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}    

The renameRefactor() method

Combining all of them, one can have this method to refactor from oldName to newName in the projeceName.
public void renameRefactor(String projectName, String oldName, String newName) throws CoreException
{
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IProject project = root.getProject(projectName);
    project.open(null /* IProgressMonitor */);
    
    IJavaProject javaProject = JavaCore.create(project);
    IType itype = javaProject.findType(oldName); // you need to include the package name also "smcho.NewName" 
    org.eclipse.jdt.core.ICompilationUnit icu = itype.getCompilationUnit();

    RefactoringContribution contribution =
                RefactoringCore.getRefactoringContribution(IJavaRefactorings.RENAME_COMPILATION_UNIT);
    RenameJavaElementDescriptor descriptor =
                (RenameJavaElementDescriptor) contribution.createDescriptor();
    descriptor.setProject(icu.getResource().getProject().getName( )); // maybe, you can just use the String
    descriptor.setNewName(newName); // new name for a Class
    descriptor.setJavaElement(icu);

    RefactoringStatus status = new RefactoringStatus();
    try {
        Refactoring refactoring = descriptor.createRefactoring(status);

        IProgressMonitor monitor = new NullProgressMonitor();
        refactoring.checkInitialConditions(monitor);
        refactoring.checkFinalConditions(monitor);
        Change change = refactoring.createChange(monitor);
        change.perform(monitor);

    } catch (CoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }        
}

Monday, October 29, 2012

Algorithm package of LaTeX

\usepackage{algorithm}% http://ctan.org/pkg/algorithms
\usepackage{algpseudocode}% http://ctan.org/pkg/algorithmicx

\subsubsection{group 1 : rename/move}
\begin{algorithm}
\caption{Euclid's algorithm}\label{euclid}
\begin{algorithmic}[1]
\Procedure{Euclid}{$a,b$}\Comment{The g.c.d. of a and b}
   \State $r\gets a\bmod b$
   \While{$r\not=0$}\Comment{We have the answer if r is 0}
      \State $a\gets b$
      \State $b\gets r$
      \State $r\gets a\bmod b$
   \EndWhile\label{euclidendwhile}
   \State \textbf{return} $b$\Comment{The gcd is b}
\EndProcedure
\end{algorithmic}
\end{algorithm}
Screen Shot 2012 10 29 at 10 02 37 PM

Algorithm2e package of LaTeX

\usepackage[ruled,vlined]{algorithm2e}

\begin{algorithm}
 \SetAlgoLined
 \KwData{this text}
 \KwResult{how to write algorithm with \LaTeX2e }
 initialization\;
 \While{not at end of this document}{
  read current\;
  \eIf{understand}{
   go to next section\;
   current section becomes this one\;
   }{
   go back to the beginning of current section\;
  }
 }
 \caption{How to write algorithms}
\end{algorithm}
Screen Shot 2012 10 29 at 10 00 07 PM

References

  1. http://www.tex.ac.uk/tex-archive/macros/latex/contrib/algorithm2e/algorithm2e.pdf
  2. Algorithms in Latex

Adding local git repository to remote server

When you have a remote repository in bitbucket, you need to push the local repository for the first time.
You can use git remote add "BRANCH", to add the branch, and then push it.
git remote add origin ssh://git@bitbucket.org/smcho/refactoringvalidatorpaper.git
git push -u origin master   # to push changes for the first time

After this, you'll find that the config file in .git has the new section.
[core]
	repositoryformatversion = 0
	filemode = true
	bare = false
	logallrefupdates = true
	ignorecase = true
[remote "origin"]
	url = ssh://git@bitbucket.org/smcho/refactoringvalidatorpaper.git
	fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
	remote = origin
	merge = refs/heads/master

Writing a paper with LaTeX

Writing a paper accompanies bibliography, and it makes the $latex:\LaTeX$ compilation process a little more complicated.
In short, one needs to three LaTeX compilation, and one bibtex compilation.
latex refvalidator.tex
bibtex refvalidator
latex refvalidator.tex
latex refvalidator.tex # resolve all the references
dvipdfmx refvalidator.dvi
You can use \cite{} for citation, and you can have the bibliography style and bibliography for correct referencing.
You don't need \section as it will be generated automatically.
\bibliographystyle{abbrv}
\bibliography{refvalidator}  

Sunday, October 28, 2012

doctest for python class

You can class test with doctest. One issue to consider is to create object to test the method. This is an example.
"""
This is the "iniFileGenerator" module.

>>> f = iniFileGenerator()
>>> f.get()
hello
"""
class iniFileGenerator:
    def __ini__(self, hintFilePath):
        self.hintFilePath = hintFilePath
    def get(self):
        """
        >>> iniFileGenerator().get()
        hello
        """
        print "hello"
        
if __name__ == "__main__":
    import doctest
    doctest.testmod()
No news is good news, if you want to get the test result you need to use command line.
refactoringChecker> python iniFileGenerator.py -v
Trying:
    f = iniFileGenerator()
Expecting nothing
ok
Trying:
    f.get()
Expecting:
    hello
ok
Trying:
    iniFileGenerator().get()
Expecting:
    hello
ok
2 items had no tests:
    __main__.iniFileGenerator
    __main__.iniFileGenerator.__ini__
2 items passed all tests:
   2 tests in __main__
   1 tests in __main__.iniFileGenerator.get
3 tests in 4 items.
3 passed and 0 failed.
Test passed.

Reuse testing class objects

When testing class, you want to use the same object multiple times throughout the method testing. In this case, you can use extra globs dictionary.
"""
This is the "iniFileGenerator" module.
>>> print f.hintFilePath
./tests/unit_test_files/hint.txt
"""
class iniFileGenerator:
    def __init__(self, hintFilePath):
        self.hintFilePath = hintFilePath
    def hello(self):
        """
        >>> f.hello()
        hello
        """
        print "hello"
if __name__ == "__main__":
    import doctest
    hintFile = "./tests/unit_test_files/hint.txt"
    doctest.testmod(extraglobs={'f': iniFileGenerator(hintFile)})

Reference

Compilation Unit

Eclipse uses CompilationUnit as the basic unit of programming. A compilation unit is a single file the compiler sees. Your .c file may include other .c files, but after the preprocessor sorting out the includes, the compiler eventually sees just a single "compilation unit". – Eli Bendersky Feb 21 '09 at 7:12

Header files have no separate life, only their content is #included into .c or .cpp files. But since #include is handled by the preprocessor, the compiler has no knowledge about distinct header files; it only sees the resulting code listing as input. This is what is called a compilation unit: a source file with all its #include directives replaced by the content of the relevant header files. - Péter Török

Reference

  1. What does “static” mean in a C program?
  2. How is compilation unit defined in c++?
  3. http://en.wikipedia.org/wiki/Single_Compilation_Unit

substring search in python

Let's say you want to extract "add" from "abc()", you have a couple of choices in Python.

string#find

string object has find() method to get the position that matches the substring.
str = "add()"
pos = str.find("(")
str[0:pos]

You can have one liner.
str[0:str.find("(")]

regular expression

Regular expression in python has two favors, one is compile()/match(), and the other one is search().
re.compile(r'([^\)]*)\(\)').match(str).group(1)
re.search(r'([^\)]*)\(\)', str).group(1)

Reference

Saturday, October 27, 2012

functional programming using map with python

Let's say you have a list of strings that ends with '\n' in python.

The simple way to remove '\n' or '\n\r' is string#rstrip() method. You can use readlines() method to read all the contents of file in a string. The problem is all the strings are appended by '\n'.

The issue is how to remove the '\n' for all the elements. From:
['STRING\n',
'\n', 
'STRING\n']
To:
['STRING',
'', 
'STRING']
Using functional programming, you can do it just one line.
lines = map(lambda x: x.rstrip(), lines)

embed swf file into blogger

You need to video capture from any tool. I used Jing for it.

Then, you need to store it into somewhere in the cloud, I used google sites.
<embed src="https://sites.google.com/site/csmgroup/files/2012-10-27_2026.swf"
quality="high" allowscriptaccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" align="middle" height="300pt" width="500pt">

Change the name of label in the blogger's new interface

Let's say you want to change the blogger label with bloodspot.

Add a new label, and set the posts with the new label

Click the Posts menu.

Screen Shot 2012 10 27 at 1 16 56 PM

Then select them all.
Screen Shot 2012 10 27 at 1 18 29 PM

Then, add bloodspot as a new label
Screen Shot 2012 10 27 at 1 19 06 PM

Using tab/menu in blogger(blogspot)

You may want to add tabs/menus on top of your blogger.
Screen Shot 2012 10 27 at 1 27 59 PM
Actually they are nothing but a web page that you can make a link. For my case, I use label to get the posts with the label. For example, with the Python tab, I link http://prosseek.blogspot.com/search/label/python, and so on.
Then you can visit blogger.com to select your blogs.
Screen Shot 2012 10 27 at 11 05 24 AM
Click Pages to add the page you want. Don't forget to set the "Show pages as" to "Top tabs".
Screen Shot 2012 10 27 at 11 08 12 AM
Screen Shot 2012 10 27 at 11 06 48 AM
You can change the configuration
Screen Shot 2012 10 27 at 11 09 14 AM

css programming

css code is more like a declarative language with C flavor. C flavor means it has open and closing bracket, and it separates elements with ';' just like C does.
Declarative in the sense that it starts with name and then directives what should be done.
This is an example for having blue 15pt for h2 heading, and drop some shadow on image.
h2 {
  color: blue;
  font-size: 15pt;
}

img {
  box-shadow: 10px 10px 5px #888;
}
For box-shadow, refer to this post.

You can dynamically modify the setup using class or ID.
.noborder{box-shadow: none;}

References

SyntaxHighlighter brushes

This is a list what kind of brushes that SyntaxHighlighter provides. Screen Shot 2012 10 27 at 11 40 49 AM From http://alexgorbatchev.com/SyntaxHighlighter/manual/brushes/.

Changing font size for headers

Some of the default font size in blogger template does not setup accordingly. This is my rendered output with h2 tag.
2012 10 27 10 41 24
In order to change this, one needs to edit the css file. The first step is click the design button.
Screen Shot 2012 10 27 at 10 42 33 AM
Then Customize the layout.
Screen Shot 2012 10 27 at 10 43 00 AM
In advanced menu, you need to use Add CSS.
Screen Shot 2012 10 27 at 10 43 20 AM

Add the necessary code in the editor.

Screen Shot 2012 10 27 at 10 44 02 AM

Now you have larger font.

Screen Shot 2012 10 27 at 10 44 28 AM

Reference

Syntax highlighter issue with google chrome

The code with SyntaxHighlighter shows wrong line formatting in google chrome. Screen Shot 2012 10 27 at 10 10 36 AM
I found that this is a known issue with of line formatting, check this site.

The http://alexgorbatchev.com/pub/sh/current/styles/shCore.css source has the line that causes this problem.
Screen Shot 2012 10 27 at 10 16 49 AM

There are easy two solutions.

Solution 1

Modify the shCore.css : replace this line.
.syntaxhighlighter table td.gutter .line {
  text-align: right !important;
  padding: 0 0.5em 0 1em !important; <-- Replace this line
}
.syntaxhighlighter table td.gutter .line {
  text-align: right !important;
  padding: 0 5px  !important;
}
Or make it point to where the bug is fixed. : http://codeoncloud.co.cc/shCore.css

Solution 2

Add following line after Configure HTML/JavaScript edit. Screen Shot 2012 10 27 at 10 19 03 AM

Following code should be added.


Friday, October 26, 2012

Visitor design pattern in python

Visitor pattern uses double dispatch which is simple but powerful.
class Node:
    def __init__(self):
        self.children = []
    def add(self, node):
        self.children.append(node)
    def printIt(self):
        print("Node")
    def accept(self, visitor):
        visitor.visit(self)
        
class NodeA(Node):
    def printIt(self):
        print("NodeA")
        
class NodeB(Node):
    def printIt(self):
        print("NodeB")
        
class NodeVisitor:
    def visit(self, node):
        node.printIt()
        if len(node.children) > 0:
            for child in node.children:
                child.accept(self)
        
if __name__ == "__main__":
    n = Node()
    n1 = NodeA()
    n2 = NodeA()
    n3 = NodeB()
    n4 = NodeB()

    n1.add(n3)
    n1.add(n4)
    n.add(n1)
    n.add(n2)
    
    v = NodeVisitor()
    v.visit(n)
Node -+- NodeA -+- NodeB
      |         +- NodeB
      +- NodeA
2012 10 27 01 32 49
Node
NodeA
NodeB
NodeB
NodeA

Get info in the project with eclipse/java

private static Set< ICompilationUnit> getFiles(String projname)
        throws CoreException {
    IWorkspaceRoot ws = ResourcesPlugin.getWorkspace().getRoot();
    IProject proj = ws.getProject(projname);
    IJavaProject javaProject = JavaCore.create(proj);
    Set< ICompilationUnit> files = new HashSet< ICompilationUnit>();
    javaProject.open(new NullProgressMonitor());
    for (IPackageFragment packFrag : javaProject.getPackageFragments()) {
        for (ICompilationUnit icu : packFrag.getCompilationUnits()) {
            files.add(icu);
        }
    }
    javaProject.close();
    return files;
}
ICompilationUnit file = …;
IResource resource = null;
try {
	resource = file.getUnderlyingResource();
} catch (JavaModelException e) {
    e.printStackTrace();
}
if (resource.getType() == IResource.FILE) {
    IFile ifile = (IFile) resource;
    String path = ifile.getRawLocation().toString();
}

What it does is get IWorkspaceRoot, and from it, you can get IJavaProject. Then, open with NullProgressMonitor(). For all of the PackageFragment, we can find ICompilationUnit, and add it to the files HashSet.

The issue is how to get the physical path from the compilation unit?
private String getWorkbenchDirectory() throws FileNotFoundException
{
	IPath path = Platform.getLocation();
	String filePath = path.toOSString();
	return filePath;
}

References

  1. Get the absolute path of the currently edited file in Eclipse
  2. How to get file path information from ICompilationUnit?
  3. How do I get the file path of the open workspace for developing plugins in eclipse

useful eclipse hotkey

  1. F3 - for finding the definition of method

MacJournal

package in Java/eclipse

  1. Source is located in src directory and build result is located in bin directory
  2. In source code you don’t have to located the source file following package. For example, you have Hello.java, you don’t have to create directory abc and put the java source code it it when your package name is abc
  3. After the compilation, the created class is located in bin/abc/Hello.class,
  4. When executing the class in the package you need to specify the package with ‘.’, for example, java abc.Hello for executing it.

MacJournal

Precision and Recall

From wikipedia

PastedGraphic3-2012-10-26-10-33.png

The left side is relevant domain and the circle means retrieved domain.

The perfect case can be the circle encloses only the left hand side, which is not always true, so we have precision and recall.

PastedGraphic4-2012-10-26-10-33.png

Precision means how precise we retrieved from samples. It focuses on not retrieving wrong samples. It’s the ratio between green circle and whole circle. Whole circle means what I retrieved and green circle means what I retrieved correctly.

So, precision says how accurate your retrieved result is. The more the less false positive.

When precision is low, it just means you include too many wrong samples.

PastedGraphic5-2012-10-26-10-33.png

Recall means how many samples you missed. It focuses on not missing correct samples. Think about the case car company recalls defected cars. It cares about the cars that it needs to recall, it doesn’t care about recalling non-defect cars. It’s the ratio between green circle and left side. Left area means the samples that I need to retrieve.

So, recall says did you good at not letting anything behind. The more the less false negative.

MacJournal article

Thursday, October 25, 2012

Abstract Base Classes in python

Python provides ABC.

References

spawn a process and get the output with python

The simplest way to spawn a process is to use os.system(COMMAND), however if you want to intercept the output, you need to python's process module.
from subprocess import *

cmd = ["ls", "-alF"]

p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)

stdout,stderr = p.communicate()
print stdout
You need PIPE assigned to stdin/stdout/stderr in order to get the result assigned to local variables.

With close_fds value as True, all the file descriptors in the process is closed. You can just remove this option. If you have a long command line string, then you can use STRING.split() method to get a list to an input to Popen method.

References

Use shutil.rmtree for deleting whole directory

Maybe, one tries to use os.remove(path) or os.removedirs(path) for deleting the whole directory.

However, they should raise an error when the directory is not empty. So, the better choice is using shutil.rmtree(path).

The name remove tree fits the idea of removing everything whereas remove and removedir delete the directory (only the directory not files in it).

Reading ini file into a dictionary in python

Configuration Reader

Python's ConfigParser lets users read configuration files.
[TestA]
package = None
class = A
method = test
We can read the items in the configuration file to be accessed as a dictionary.
a['TestA']['package']
In order to do that, we need a method to do that.
import ConfigParser

class MyParser(ConfigParser.ConfigParser):
    def as_dict(self):
        d = dict(self._sections)
        for k in d:
            d[k] = dict(self._defaults, **d[k])
            d[k].pop('__name__', None)
        return d
This is how one can use this code.
if __name__ == "__main__":
    f = MyParser()
    f.read("/DIRECTORY_TO/setup.ini")
    d = f.as_dict()
    print d
    print d['TestA']['class']
You'll get the result.
{'TestA': {'package': 'None', 'method': 'test', 'class': 'A'}}
A

Analysis of the code

If you are not familiar with python dictionary, you can check this post. When the ini file is read into ConfigParser object, all the information is already in the dictionary.
config = ConfigParser.RawConfigParser()
config.read(PATH)
In config, you have all the items in dictionary, the issue is that you can't use it as is.
print f._sections
OrderedDict( # <-- Ordered Dictionary
  [ # <-- List of tuples : string and OrderedDict 
     ('TestA', 
       OrderedDict(
         # The first item in the list is not necessary, so pop it off
         [('__name__', 'TestA'), ('package', 'None'), ('class', 'A'), ('method', 'test')]
       )
     )
  ]
)
The default data structure is OrderedDict, if you need more about OrderedDict, you can check this post. for k in d:, the k holds the section name ('TestA'), and it only iterates once as there is only one sections. When you run this code, you'll get the OrderedDictionary(), but you don't need the first element which is the name of the section.
for k in d: print d[k]
OrderedDict([('__name__', 'TestA'), ('package', 'None'), ('class', 'A'), ('method', 'test')])
The next code creates a dictionary based on _defaults OrderedDict().
d[k] = dict(self._defaults, **d[k])
print f._defaults
OrderedDict()
And for the **d[k], it means that d[k] (dictionary) is decomposed into assignments. This is necessary as the dict() method requires assignments as additional parameters to the method.
def hello(**a):
    print a
    
a = dict([['a',10],['b',20]])
print a
hello(**a)
{'a': 10, 'b': 20}
{'a': 10, 'b': 20}
You'll get d[k] as follows:
{'__name__': 'TestA', 'package': 'None', 'method': 'test', 'class': 'A'}
Finally, you should pop up the ('__name__': 'TestA')
d[k].pop('__name__', None)
This is explanation for the pop() method. Screen Shot 2012 10 25 at 4 17 02 PM

References

Displaying updated post in blogspot

This post teaches how to enlist newly generated posts.




Get this widget

The basic idea is retrieve information from blogger, and calls he callback function to enlist the result.

The summary has all the information, you can check it from http://prosseek.blogspot.com/feeds/posts/summary. Compare it to the case with only for python label with http://prosseek.blogspot.com/feeds/posts/summary/-/python. so if you want to enlist all the posts updated not for specific label, you can modify the code as follows.

OrderedDict in python

The dict type in python is not ordered, and it's been a pain, especially when you want to keep the sorted order inside a dictionary. From python 2.7, OrderedDict is supported. Screen Shot 2012 10 25 at 10 57 47 AM This quick example will show you what are the differences.
from collections import *

print 'Regular dictionary:'
d = {}
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
d['d'] = 'D'
d['e'] = 'E'

for k, v in d.items():
    print k, v

print '\nOrderedDict:'
d = collections.OrderedDict()
d['a'] = 'A'
d['b'] = 'B'
d['c'] = 'C'
d['d'] = 'D'
d['e'] = 'E'

for k, v in d.items():
    print k, v
OrderedItem() keeps the input order, with this you can sort
Regular dictionary:
a A
c C
b B
e E
d D

OrderedDict:
a A
b B
c C
d D
e E
  • OrderedDict() requires import collections.
  • When printing the object, OrderedDict() doesn't show it with '{' and '}'.
You can build OrderedDict() using list (iteration), and you can keep the order now.
d = OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
for k, v in d.items():
    print k, v
apple 4
banana 3
orange 2
pear 1
Using this, you can get the sorted dictionary. Remembering dict.items() return list, you can sort regular dictionary.
# dictionary sorted by value
d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))
for k, v in d.items():
    print k, v
d = OrderedDict(sorted(d.items(), key=lambda t: t[1]))
for k, v in d.items():
    print k, v
apple 4
banana 3
orange 2
pear 1

pear 1
orange 2
banana 3
apple 4
sort() method gets a list as an input and returns sorted list, it doesn't modify the original list.
a = [1,2,3,4,-3]
b = sorted(a)
print b
print a
[-3, 1, 2, 3, 4]
[1, 2, 3, 4, -3]
Even you can sort by the length of the index.
d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
# dictionary sorted by length of the key string
d = OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
for k, v in d.items():
    print k, v
pear 1
apple 4
orange 2
banana 3
You can get the dict from OrderedDict() as the latter is iterable.
o = OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])
d = dict(o)
for k, v in d.items():
    print k, v
orange 2
pear 1
apple 4
banana 3

References

Wednesday, October 24, 2012

Refactoring Eclipse refactoring programmatically

Stack Overflow question : Is there any eclipse refactoring API that I can call programmatically?

http://stackoverflow.com/questions/9129689/is-there-any-eclipse-refactoring-api-that-i-can-call-programmatically

How to execute inline refactoring programmatically using JDT/LTK?

http://stackoverflow.com/questions/12898718/how-to-execute-inline-refactoring-programmatically-using-jdt-ltk

From MacJournal

Map in python - and it's application to ini file reader

Mapping Types is a container that maps from an element to the other element. In python, map is implement in dict.

Making a map(dirctionary) in python

Dictionary is represented as follows:
e = {"one": 1, "two": 2}
The two items are mapped with ":" charactore, and each mapping is separated by a comman. Python builds dict object with '{' and '}' character.

You can use dict() method to build one.
class dict(**kwarg)
You may not familiar with ** notation. This is a simple example used in python method.
def hello(**x):
    print x

hello(x=1,y=2)
When you execute this code, you will get a dictionary object.
{'y': 2, 'x': 1}
When python method sees **something, all the assignments (x = 1, y = 2 in this example) given as a parameter is wrapped inside an automatically generated dictionary, and parameter variable x is pointing to the dictionary. In short, you can think of **something as collect (*) and make dictionary (*), and name it something.

As you see the meaning of **something as a parameter to the function. You'll see that this code will make the same dictionary as before.
a = dict(one=1, two=2)
You have more options to make the dictionary.
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
For the first case, when first item is a mapping (other dictionary), it will build a new dictionary with the contents of it together with the additional parameters.
b = dict({'one': 1, 'two': 2})
For the next case, the first parameter can be a list with lists that has two elements.
c = dict(zip(('one', 'two'), (1, 2)))
d = dict([['two', 2], ['one', 1]])
zip method has two parameters, and iterate over the elements in each of the two elements to zip a list of list that contains two elements from each parameters.

Of course, you can add additional assignments so that they are added to the newly generated dictionary.

Using dictionary

For getting all the items in a dictionary, you need to use items().
d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
print d
print d.items()
{'orange': 2, 'pear': 1, 'banana': 3, 'apple': 4}
[('orange', 2), ('pear', 1), ('banana', 3), ('apple', 4)]

How to make cloud form of labels in blogpost

As the number of blogs grow, I need to organize and find the posting based on labels.

This post explains how to do that.

In short:
  1. click the Layout link
  2. Select where to put the label cloud and select label :
  3. Then select options :

Unit testing - Java JUnit 3

Download and build JUnit

Download the source from git, and execute ant.

The result jar file is compiled into junit4.11-SNAPSHOT directory.

Simple example

Class under test

public class Hello
{
    int add(int x, int y)
    {
        return (x + y);
    }
    
    int sub(int x, int y)
    {
        return (x - y);
    }
}

Test class

import junit.framework.*;
import static org.junit.Assert.assertEquals;

public class HelloTest extends TestCase {
  private Hello tester = null;
  protected void setUp() {
       tester = new Hello();
  }

  public void testAdd() {
    assertEquals("Result1", 15, tester.add(10, 5));
  }
}
TestCase comes from junit.framework.*, And you need to have '.' for classpath in order to find the class under the test. You need to copy the junit.jar in the classpath also.

Compile and execute

The junit.textui.TestRunner is called with the test class (HelloTest) parameter.
javac Hello.java
javac -cp .:junit-4.11-SNAPSHOT.jar HelloTest.java
java -cp .:junit-4.11-SNAPSHOT.jar junit.textui.TestRunner HelloTest
.
Time: 0.001

OK (1 test)

setUp() added

You can add setup() and tearDown() method.

import junit.framework.*;
import static org.junit.Assert.assertEquals;

public class Hello2Test extends TestCase {
  private Hello tester = null;
  protected void setUp() {
       super.setup();
       tester = new Hello();
  }

  public void testSub2() {
    assertEquals("Result1", 15, tester.sub(20, 5));
  }
  
  public void testSub() {
    assertEquals("Result1", 15, tester.sub(20, 5));
  }
}

Or, you can use @Override
  @Override
  protected void setUp() {
       tester = new Hello();
  }

Using suite()

You can make suite(), and add test methods to the suite.
import junit.framework.*;
import static org.junit.Assert.assertEquals;

public class Hello2Test extends TestCase {
  private Hello tester = null;
  
  public Hello2Test(String str)
  {
      super(str);
  }
  
  @Override
  protected void setUp() {
    tester = new Hello();
  }

  public void testAdd() {
    assertEquals("Result1", 15, tester.add(10, 5));
  }
  
  public void testAdd2() {
    assertEquals("Result2", 25, tester.add(10, 15));
  }
  
  public static Test suite() {
      TestSuite suite= new TestSuite();
      suite.addTest(
          new Hello2Test("testAdd") {
               protected void runTest() { testAdd(); }
          }
      );

      suite.addTest(
          new Hello2Test("testAdd2") {
               protected void runTest() { testAdd2(); }
          }
      );
      return suite;
  }
  
  public static void main(String[] args) {
      junit.textui.TestRunner.run(suite());
  }
}

You can use dynamic way to put all the tests in the suite using one line of code with Java Reflection working behind the scene.
  public static Test suite() {
      // method 1
      return new TestSuite(HelloTest.class);
  }
You can just execute the test like normal java code
javac Hello.java
javac -cp .:junit-4.11-SNAPSHOT.jar HelloTest.java
java -cp .:junit-4.11-SNAPSHOT.jar HelloTest

Merging tests with suite()

You can collect tests from TestCases to make test suite() to run.
import junit.framework.*;

public class HelloTestSuite
{
    public static Test suite() { 
        TestSuite suite= new TestSuite(); 
        suite.addTest(new HelloTest("testAdd")); 
        suite.addTest(new Hello2Test("testAdd")); 
        suite.addTest(new Hello2Test("testAdd2")); 
        return suite;
    }
    
    public static void main(String[] args) {
        junit.textui.TestRunner.run(suite());
    }
}
One can even concatenate the test cases into suite.
public class HelloTestSuite
{
    public static Test suite() { 
        TestSuite suite= new TestSuite(); 
        suite.addTestSuite(HelloTest.class); 
        suite.addTestSuite(Hello2Test.class); 
        return suite;
    }
    
    public static void main(String[] args) {
        junit.textui.TestRunner.run(suite());
    }
}

Reference

  1. vogella.com on JUnit
  2. JUnit Testing Utility Tutorial
  3. JUnit 4.0 Example

Using LaTeX in blogspot

First method

I googled this site helps to make LaTeX working in blogspot. I have prosseek/files, for file storing purposes (even though it allows me keep only 1GB). Just right click in google/sites, and copy the file using HREF allows me to download the file from the site like this.
The code is as follows:
$latex \displaystyle S(n)=\sum_{k=1}^{n}{\frac{1}{T_{k}}=\sum_{k=1}^{n}{\frac{6}{k(k+1)(k+2)}$
This is the result: $latex \displaystyle S(n)=\sum_{k=1}^{n}{\frac{1}{T_{k}}=\sum_{k=1}^{n}{\frac{6}{k(k+1)(k+2)}$
You can refer to this post for embedding HTML/javascript in your blog.

MathJax

I googled this post to use MathJax. You need to add the code in template, which add jQuery and MathJax.



The code is as follows:


And this is the result:

Warning

As is written in this post, there is a bug that the result is not shown in Chrome.

References

  1. Embedding math with replacemath
  2. How to show the string inside a tag verbatim?

Easier way to embed java script/HTML in blogpost

When using javascript in your blogspot, I just copied the javascript and HTML code in the editor, but using template, one can share the java script and HTML code for all of the blogs that I make. The first step is visit blogger.com, and choose your blogspot. Open layout.
Then, open "Add a Gadget", and select HTML/Javascript.
When you need to change some of the template, you also can edit the template HMTL code.
Then add your code in there. I have this for my code.

Showing LaTeX code in blogger

Refer to this post.


Syntax highlighter setup

Refer to this post.







pretty printer

Refer to Code highlighting on blogger by LUKA MARINKO. You also need to modify HTML template as explained before.


You can edit the code anytime you want.

Tuesday, October 23, 2012

Unit testing - python

Unit testing in python

You'll have more information from this site.

There were some choices for unit test external libraries, but now unittest is a part of
import random
import unittest

from Hello import *

class TestHello(unittest.TestCase):
    def setUp(self):
        self.hello = Hello()

    def test_add(self):
        self.assertEqual(self.hello.add(2,12), 14)

    def test_add2(self):
        self.assertEqual(self.hello.add(2,3), 5)


class TestHello2(unittest.TestCase):
    def setUp(self):
        self.hello = Hello()

    def test_add(self):
        self.assertEqual(self.hello.subtract(2,12), -10)

    def test_add2(self):
        self.assertEqual(self.hello.subtract(2,13), -11)

if __name__ == '__main__':
    unittest.main()
In order to execute the code, you just need to run the unit test code.
python UNIT_TEST_CODE.PY

Things to consider

Normally, unit testing starts with a TestCase per class under the test. And for multiple TestCases, one can bundle the tests into TestSuite as you do in java.

However, with python (it seems like that) the unittest.main() searches into classes that inherit from unittest.TestCase to execute all the tests.

You see that in this example, 4 tests are executed automatically.
....
----------------------------------------------------------------------
Ran 4 tests in 0.000s

OK

Unit testing using pycharm

PyCharm is a python development environment implemented in Java programming language from Jet Brains. You will find a Python plugin for IntellJ, but they are two different products.

PyCharm doesn't have automatic unit test generator, but it seems like that the company doesn't have a plan to support it.

PyCharm is smart enough that when you click the run button, it's for executing unit test.

Doctest

Doctest provides easy way to test. This example shows the usage of it.
"""
This is the "example" module.

The example module supplies one function, factorial().  For example,

>>> factorial(5)
120
"""

def factorial(n):
    """Return the factorial of n, an exact integer >= 0.

    If the result is small enough to fit in an int, return an int.
    Else return a long.

    >>> [factorial(n) for n in range(6)]
    [1, 1, 2, 6, 24, 120]

    Factorials of floats are OK, but the float must be an exact integer:
    >>> factorial(30.1)
    Traceback (most recent call last):
        ...
    ValueError: n must be exact integer
    """

    import math
    if not n >= 0:
        raise ValueError("n must be >= 0")
    if math.floor(n) != n:
        raise ValueError("n must be exact integer")
    if n+1 == n:  # catch a value like 1e300
        raise OverflowError("n too large")
    result = 1
    factor = 2
    while factor <= n:
        result *= factor
        factor += 1
    return result

if __name__ == "__main__":
    import doctest
    doctest.testmod()
The format is just use >>> to indicate the code to execute, and write down the expected result including the error message.

When you want to execute it as a command line, nothing will happen as a default. You can use -v option to see the testing result.
smcho@prosseek Desktop> python example.py -v
Trying:
    factorial(5)
Expecting:
    120
ok
Trying:
    [factorial(n) for n in range(6)]
Expecting:
    [1, 1, 2, 6, 24, 120]
ok
Trying:
    factorial(30.1)
Expecting:
    Traceback (most recent call last):
        ...
    ValueError: n must be exact integer
ok
2 items passed all tests:
   1 tests in __main__
   2 tests in __main__.factorial
3 tests in 2 items.
3 passed and 0 failed.
Test passed.

Reference

  1. doctest

google services test : picasa

I needed to use LaTeX script in blogpost, and this site teaches me how to do that, but I need to use google services such as picasa and google/sites for it. So, I tried.

Show pictures from picasa in blogspot

Picasa allows me to upload pictures from my mac to cloud. I'm trying to show the pictures from picasa, however, just href'ing doesn't seem to work. File uploaded to picasa from my mac. https://lh6.googleusercontent.com/-AfYyCt4YI-c/UIbCRY1mA7I/AAAAAAAAAEg/JlgYadGokhg/w561-h421-p-k/IMG_0542.jpg What I needed was to use insert image, and instead of uploading pictures, I can like the page from the picasa. My concern is if this link is temporary or not.

You can change the picture size by modifying width and height.

The real solution

This site gave me a hint that the site I need to check is https://picasaweb.google.com/, not http://picasa.google.com/. Now, I can embed the slide show. Or, just one picture.
10/23/12