Thursday, 29 November 2007

Headers in latex

The GNU Revision Control System is generally considered a tool for software development, but it is also useful for tracking revisions of text documents. This article explains how to include and format RCS keywords in LaTeX documents, and how to track document revisions using these keywords.

Most discussions of the GNU Revision Control System occur in the context of tracking source code revisions. But RCS can track revisions of any type of file, text or binary, provided that the diff utilities which generate RCS change files can handle binary data.

RCS seems ready-made for working with LaTeX input files. The pre-defined keyword identifiers built in to RCS are easy to format and print. They provide ready information that can include the document's author, its revision, filename, and, revision log entry. RCS also provides facilities for user-defined identifiers.

RCS is commonly included with the development software of Linux distributions. The latest source code version of RCS is available from and its mirror sites.

The ident(1) manual page has a list of the standard RCS keywords that are generated when documents are checked out by RCS. They include:

* $Author: lg $: The login name of the person who checked in the revision.
* $Date: 2002/10/09 22:24:18 $: The date and time the document was checked in.
* $RCSfile: latex.html,v $ The basename and extension of the RCS file.
* $Id: latex.html,v 1.2 2002/10/09 22:24:18 lg Exp $: String containing the name of the RCS file, the revision number, date and time, author, state, and locker if any.
* $Revision: 1.2 $: The document's revision number.
* $Log: latex.html,v $
* Revision 1.2 2002/10/09 22:24:18 lg
* Remove all lg_toc##.html; change hyperlinks to index.html
* Revision 2002/08/14 22:27:03 dan
* Preliminary.
* Revision 1997/09/14 15:01:51 schwarz
* Imported files
* The log message entered when the document was checked in.

These keywords are included verbatim in documents. They are expanded when the document is checked out with co(1).

One consideration that needs to be taken into account is that the keywords' dollar signs are interpreted by LaTeX (and TeX) as starting and ending math-mode typesetting. LaTeX and TeX will not generate an error when it encounters the dollar signs. However, because LaTeX and TeX typeset equations differently than normal text, the results can be unpredictable.

For example, including the $Id: latex.html,v 1.2 2002/10/09 22:24:18 lg Exp $ string at the top of the odd pages the commands

\markright{$Id: latex.html,v 1.2 2002/10/09 22:24:18 lg Exp $}

results in the expanded RCS $Id: latex.html,v 1.2 2002/10/09 22:24:18 lg Exp $ string to be printed at the top of the pages, but some of the keywords run together because of the way TeX formats the string. An alternative is to use the keywords of the individual identifiers, and separating them with the appropriate command. Here, the TeX command \hfil inserts the necessary space when the keyword strings are typeset in the running head.

\markright{$Date: 2002/10/09 22:24:18 $\hfil$RCSfile: latex.html,v $\hfil$Revision: 1.2 $}

The string given to the \markright command will be typeset with the date in the upper left of the page, the filename centered, and the revision number at the top right.

The \markright command is all that's needed for printing on one side of a sheet. For printing on both sides of the page, use the \markboth command.

\markboth{$Date: 2002/10/09 22:24:18 $\hfil$RCSfile: latex.html,v $\hfil$Revision: 1.2 $}{\thepage}

The first argument to \markboth prints the RCS information at the tops of the left-hand pages and the page number at the top of the right-hand pages. The identifier \thepage is a standard LaTeX variable which prints the page number.

The RCS log message can be placed anywhere in a document that the $Log: latex.html,v $ Revision 1.2 2002/10/09 22:24:18 lg Remove all lg_toc##.html; change hyperlinks to index.html Revision 2002/08/14 22:27:03 dan Preliminary. Revision 1997/09/14 15:01:51 schwarz Imported files keyword can be inserted. For example, to place a (short!) log message in the margin at the beginning of a document, put the command \marginpar{$Log: latex.html,v $ \marginpar{Revision 1.2 2002/10/09 22:24:18 lg \marginpar{Remove all lg_toc##.html; change hyperlinks to index.html \marginpar{ \marginpar{Revision 2002/08/14 22:27:03 dan \marginpar{Preliminary. \marginpar{ \marginpar{Revision 1997/09/14 15:01:51 schwarz \marginpar{Imported files \marginpar{} immediately after the \begin{document} command, or after the \maketile command if the document has a title page and you'd rather have the RCS log text annotating the body text of the document.

The RCS information can be included in the documents footer by using the fancyhdr package, which is available from any TeX archive site.

If you want to include the $Date: 2002/10/09 22:24:18 $ and $Revision: 1.2 $ keywords at the bottom of a page, you could include

\fancyfoot[L]{$Date: 2002/10/09 22:24:18 $}
\fancyfoot[R]{$Revision: 1.2 $}

in the document preamble; that is, before the \begin{document} command. At the point you want the RCS data to be typeset, insert the commands


ident(1) also searches files for RCS keywords. Typing the command ident term-paper.tex for example, will print a list of the keywords and their values to standard output. It's a simple matter of typing ident *tex | grep "fred" - to search for the documents which were last checked out by user fred.

For further information, consult the manual pages of the various programs in the RCS package, and the rcsintro(1) manual page for an introduction to the RCS system.

Powered by ScribeFire.

Wednesday, 28 November 2007

Symbolic Operations in Matlab

Background Note:

Up to this point we have done purely numerical operations in Matlab. This is the traditional approach for solving problems on the computer, and much of the current computational work done in industry follows this approach. However, a relatively new capability (last 5-10 years or so) that is gaining popularity involves the use of symbolic operations directly on the computer. Computer programs that use these symbolic techniques are often referred to as computer algebra systems, and they are becoming quite powerful. In particular, Matlab’s Symbolic Math Toolbox offers this general capability within the Matlab environment by providing an interface to the Maple code (Maple is a commercial software package that emphasizes symbolic manipulations or computer algebra techniques). This set of labs will introduce some of the basic symbolic capability in Matlab, eventually leading up to the analytical solution of Ordinary Differential Equations directly on the computer. Many of the exercises given here are derived from the Matlab’s User’s Guide and you are encouraged to refer to that manual for further examples and guidance.

Define Some Symbolic Variables:

First define a bunch of symbolic variables: syms a1 b1 c1 a2 b2 c2 d2 A B C1 C2 x y t

Now let’s form some symbolic functions:

Mathematical Function
Matlab Syntax for Function

f1 = a1 + b1*x + c1*x^2

f2 = a2 + b2*x + c2*x^2 + d2*x^3

g = exp(A*t)*(C1*cos(B*t)+C2*sin(B*t))

u = 2*x*y^2 + sin(x+y)

Differentiation of Symbolic Functions:

Differentiate each of the above functions using Matlab’s diff command. For example, try diff(f1). What happened? Is the result correct? Do the same thing for the other functions. What happens when you type diff(u)? How do you get Matlab to take the partial derivative with respect to the variable y? Type help sym/diff to see the various options associated with taking symbolic derivatives.

We can also take higher order derivatives. For example diff(f1,2) takes the second derivative of f1(x). Try this for all the functions!

Can you show that the mixed partial derivatives of u(x,y) are equal? Take du/dx and du/dy as above and save the results as string variables. For example, try typing

dudx = diff(u,x); dudy = diff(u,y);.

Now take the first derivative of these symbolic variables, as follows:

uyx = diff(dudx,y); uxy = diff(dudy,x);

Are these latter two variables the same? They should be. Pretty neat stuff, don’t you think!!!

Integration of Symbolic Functions:

Using Matlab’s int function, perform the following integrals using f1(x):

Mathematical Operation
Matlab Syntax for Operation

I1 = int(f1)

I2 = int(f1, 0, 5)

Do these make sense? Check out the subs command. Now let a1 = 1, b1 = -2, and c1 = 1, and substitute these numerical constants into the symbolic expressions for I1 and I2, as follows:.

I1 = subs(I1,{a1 b1 c1},{1 -2 1}), I2 = subs(I2,{a1 b1 c1},{1 -2 1})

What are the values for the integrals I1 and I2? Why is I1 a function of x and I2 is simply a scalar number? Note also that the curly brackets in Matlab refer to cell arrays. The sequence given by the set, {a1 b1 c1},{1 -2 1}, replaces the numerical variables into the symbolic variables in sequence. The cell array simply let’s us make all three substitutions in one call to the subs command.

Try integrating and substituting values for the constants in the other functions. Note that with u(x,y), you can only integrate with respect to one variable at a time. For example,

Mathematical Operation
Matlab Syntax for Operation

Iu = int(int(u,x,0,pi),y,0,2*pi)

Pretty impressive!!! Could you do this integral by hand this fast? I certainly can’t…

Plotting Symbolic Functions:

Certainly we can also plot symbolic relationships. Since we have already defined the constants for use with f1(x), let’s use this function to do some simple plots. In particular, let’s plot f1(x), df1/dx, and over the range . We can do this as follows:

F1 = subs(f1,{a1 b1 c1},{1 -2 1}); D1 = diff(F1); I1 = int(F1);
Nx = 51; xp = linspace(0,5,Nx);
F1p = double(subs(F1,x,xp));
D1p = double(subs(D1,x,xp));
I1p = double(subs(I1,x,xp));
title(‘Evaluating and Plotting Symbolic Functions’)
xlabel(‘X Values’),ylabel(‘Various Function Values’)
legend(‘Function’,’First Derivative’,’Integral’)

Solving Algebraic Equations:

We can also solve algebraic equations with Matlab. For example, what if we wanted to know the value of x where f1(x) = 3? With the above constants this problem becomes: find x such that

In Matlab, we can use the solve command: solve(x^2-2*x-2) or solve(F1 - 3).

We can also solve systems of algebraic equations. For example, the analytical solution to the following 2x2 system:

is given by:

S = solve(3*x + 2*y - 3,-2*x + y + 7); % this solves a simple set of 2x2 equations

S.x, S.y % this prints x and y to the screen

Solving Ordinary Differential Equations:

The real goal of the above discussion and examples with symbolic variables is to give enough background so that we can solve ODEs analytically on the computer. This will be pretty powerful capability if we can actually do this with a set of relatively simple commands. As a test, let’s give Matlab’s dsolve command a workout for a few different types of ODEs that we have treated thus far in the semester (be sure to type help dsolve to get a good idea of the various forms that can be used).

a. Solve the first order IVP:

dsolve(‘Dy + y/x = (2/x)*exp(2*x)’,’x’) % this gives the general solution

dsolve(‘Dy + y/x = (2/x)*exp(2*x)’,’y(1) = 0’,’x’) % this gives the unique solution

b. Solve the second order IVP:

Sh = dsolve('D2y - 4*y = 0','x'), pretty(simple(Sh)) % homogeneous soln
Sg = dsolve('D2y - 4*y = 4*x^2','x'), pretty(simple(Sg)) % general soln
Su = dsolve('D2y - 4*y = 4*x^2','y(0) = -1/2','Dy(0) = 4','x') % unique soln

c. Solve the second order IVP:

Q1 = dsolve(‘D2y + 6*Dy +13*y = 10*sin(5*t)’, ’y(0) = 0’,’Dy(0) = 0’,’t’)

d. Re-solve the problem in Part c as a system of two 1st order ODEs, where z1 = y and z2 = dy/dt:

Q2 = dsolve(‘Dz1 =z2’,’Dz2 = -13*z1 -6*z2 + 10*sin(5*t)’, ’z1(0) = 0’,’z2(0) = 0’,’t’)
pretty(simple(Q2.z1)), pretty(simple(Q2.z2))

Final Note:

There is a lot of good stuff here. In particular, there are several examples that should make your life much easier in this course and in several of your other technical classes. You should do your best to understand the basic capability that is illustrated here -- it represents some pretty powerful mathematical analysis capability. You should also note that some of the examples from earlier in the semester (the Two Salty Tanks problem for example) give other illustrations of the use of computer algebra to solve a coupled set of first order differential equations for a real problem of interest. Also, a final Matlab demo will be given at the end of the semester illustrating how to take Laplace transforms and inverse Laplace transforms analytically using Matlab’s symbolic processing capability.


Scjp Study Guide 310-055

Science in Silico

To download the full version visit

Powered by ScribeFire.



import uniittest

import ysfile #自定义的模块

class TestZDYSFile(unittest.TestCase):

def setUp(self):


def testGetYear(self):


def testGetLoca_bz(self):


class TestPDYSZipFile(unittest.TestCase):

def setUp(self):


def testGetCdate(self):


if __name__ == '__main__':


suite = unittest.TestSuite()





Powered by ScribeFire.

Compiling Python(Jython) and for Java

Another view: Jython is the extension language for Java.

Use jythonc. What is jythonc and what is its status?

jythonc transforms Python source code into Java source code then invokes a Java compiler to turn it into .class files. This allows Python to be integrated into Java in several places that regular Jython currently doesn't support. It also processes special annotations in docstrings on methods in Python code to determine the static type information to expose when turning a dynmically typed Python method into a statically typed Java method.

jythonc is unmaintained and will not be present in Jython-2.3. While jythonc handles all of the language features present in Jython 2.2, it doesn't support 2.3 features such as generators. As such, it is not recommended that new Jython projects make use of jythonc. It is only included in Jython-2.2 to support older users of jythonc and to allow access to a few features that are only provided by jythonc at the moment:

  1. Running in a JVM with a classloader that will not load dynamically created classes
  2. Declaring Java method signatures in Python code
  3. Loading Python classes dynamically from Java with Class.forName

While all of these features are planned for Jython-2.3, they are currently only available from jythonc. Most uses of the second feature, adding method declarations to docstrings, can be handled by declaring a Java interface to implement with a Python class. Each method in the Python implementation takes the types of the Java method it implements. Exposing the Python class as an instance of that type to Java code can be done as explained in Accessing Jython from Java Without Using jythonc and its followup, Simple and Efficient Jython Object Factories.


You can extend Java classes.

You can add (J)Python protocols to Java classes.

You will need to describe the signature of methods in order to make them callable from Java (in addition to Jython).

What jythonc does -- jythonc translates .py files into .java source code files, then compiles these to .class files.

With jythonc, you can also:

  • Compile Jython (.py) to Java class files (.class).

  • Compile Jython to Java source, then stop without compiling to .class files.

  • Use a Java compiler different from the default: javac. See the help from jythonc:

    --compiler path
    -C path
    Use a different compiler than `standard' javac. If this is set to
    `NONE' then compile ends with .java. Alternatively, you can set the
    property python.jpythonc.compiler in the registry.

    This option can also be set in your Jython registry file.

Java compatible classes - In order to implement a Java compatible class (that is, one that acts like a native Java class and can be called from Java), your Jython code must follow these rules:

  • Inherit from a Java class or interface.
  • Include only one class per module.
  • Give the Jython class and the source file that contains it the same name.
  • Place all code inside that Jython class.
  • Include method signature hints (called sig-strings) -- Add a @sig line in the doc-string for each method.

How to use jythonc:

  • Type jythonc --help for help.

  • Compile your Jython code with:

  • To get help for jythonc, type:

    $ jythonc --help

Some notes:

  • When your run jythonc, by default, the .java files are placed in a sub-directory ./jpywork. You can override this with the --workdir command line option. From jythonc --help:

    --workdir directory
    -w directory
    Specify working directory for compiler (default is ./jpywork)
  • When you run this resulting code from Java, the directory ./jpywork and the Jython jar file must be on your classpath.

Example -- The following Jython code extends a Java class. Compile it with jythonc:


import java

class Foo(java.util.Date):
def __init__(self):
self.count = 0
def bar(self, incr=1):
"""@sig void bar(int incr)"""
self.count += incr
return self.count
def toString(self):
cnt =
return "Foo[" + java.util.Date.toString(self) + " " + `cnt` + "]"

Example, continued -- Here is Java code to test the above. Compile it with javac and run it:


import Foo;

public class FooTest {
public static void main(String[] args) {
Foo foo = new Foo();


  • Compile and run:

    $ javac
    $ java FooTest
  • You will need jpywork on your classpath. So, you can compile and run it as follows:

    $ ../../Jython-2.2a/jythonc
    $ javac -classpath ../../Jython-2.2a/jython.jar:./jpywork
    $ java -classpath ../../Jython-2.2a/jython.jar:./jpywork FooTest

In order to implement a Java compatible class (that is, one that acts like a native Java class and can be called from Java), your Jython code must follow these rules:

  • Inherit from a Java class or interface.
  • Include method signature hints (called sig-strings).
  • Give the Jython class and the source file it is in the same name.

Here is another simple example:


This is a simple class to demonstrate the use of jythonc.

import java.lang.Object

class simpleclass(java.lang.Object):
def __init__(self, name='The Horse With No Name'):
"""public simpleclass(String name)
""" = name
self.size = -1
def set_name(self, name):
"""@sig public void set_name(String name)
""" = name
def set_size(self, size):
"""@sig public void set_size(int size)
self.size = size
def show(self):
"""@sig public String show()
return 'name: %s size: %s' % (, self.size, )

And, a Java test harness for this simple example:


import simpleclass;

public class simpleclasstest {
public static void main(String[] args) {
String s1;
simpleclass sc = new simpleclass();
s1 =;
System.out.println("1. " + s1);
s1 =;
System.out.println("2. " + s1);


  • In order to produce a Java compatible class, our Jython class must inherit from a Java class. In this case, we use java.lang.Object, because we do not need to inherit any behavior.
  • The methods set_name, set_size, and show each have sig-strings.

Put jpywork on your CLASSPATH, then use the following to compile and test the above:

$ jythonc
$ javac
$ java simpleclasstest
1. name: The Horse With No Name size: -1
2. name: dave size: 4321

In the following example, we create a stand-alone Jar file, that is, one that can be executed as a script on a machine where Jython is not installed. Here is the Jython script:


import sys

def test(words):
msgs = ['hi', 'bye']
for word in words:
for msg in msgs:
print msg

def main():
args = sys.argv[1:]

if __name__ == '__main__':

Compile and build a Jar file with the following:

$ jythonc --all --jar mytest.jar

Run it as follows:

$ java -jar mytest.jar hello goodbye


  • Note that our Jython script contains no class. jythonc will create a public class and a public static main function for us.
  • The --jar flag tells jythonc that we want the results placed in a Jar file (as opposed to placing it in the work directory ./jpywork).
  • The --all flag tells jythonc to include all Jython support in the Jar file, making it stand-alone. This enables us to run it on a system where Java is installed but Jython is not.

16.1   Calling Jython Code from Jython

From Jython, you can run Jython and Python code. When you do so, you may run Java code that is in a super-class or is used by the Jython code.

But, notice that, from Jython, you cannot call Python code that has been extended with C.

16.2   Calling Jython Code from Java

Must compile Jython/Python to Java with jythonc.

Must pay attention to method signatures. Define method signature in Jython in a doc string with @sig. Then look at the generated .java file.

Other things to be aware of:

  • Must set classpath to include jpywork.
  • Must write a Java compatible class. See above.

16.3   Another example -- Jython-2.2a/Demo/javaclasses

What this example shows:

  • How to write a class that can be compiled (with jythonc) and then called from Java.
  • How to write method signatures for Jython methods.
  • How to compile the the Jython code and the Java code.

For example, I compiled and ran the example in Jython-2.2a/Demo/javaclasses with the following:

$ rm -rf jpywork/
$ ../../jythonc --package pygraph
$ javac -classpath .:../../jython.jar pygraph/
$ java -classpath .:../../jython.jar:jpywork pygraph.PythonGraph

For more information, see Jython-2.2a/Demo/javaclasses/readme.txt.


Blogged with Flock

Tuesday, 27 November 2007

What's Good About Jython?


In this article I introduce features of the Jython programming
language, illustrated with a small working example. I argue the
benefits of marrying Java with the Python scripting language, and then
speculate why developers
have been slow to adopt this innovative technology.

What is Jython?

Jython is an implementation of
Python that is
written in pure Java.
This means that Jython offers all that any other implementation of
Python offers (see next section), but also provides access to the whole
range of Java library classes (such as Swing, JDBC, Java Cryptography,
Java Speech API, and so on). It also makes it very easy to write Python
code that integrates existing Java components. Conversely, it is easy
to write Jython components that can later be reused and integrated into
other Java-based systems. The benefit to the Java developer is rapid
application development without sacrificing functionality, robustness,
or the commercial respect afforded by Java.

Why Python?

Python is a general-purpose, object-oriented, scripting language. It
is a highly regarded language that is gaining in popularity because it
offers high productivity and therefore competitive advantage. It also
has a simple syntax that gives rise to readable (and maintainable)

The language itself contains most of the constructs and features
that you might expect, such as objects, functions (methods), procedural
loop constructs, and exception handling. The main feature for a C or
Java programmer is, arguably, the ease with which one can create and
manipulate lists and sequences of values. This, coupled with idioms of
functional programming such as mapping and filtering, make for a very
powerful core language.

A Jython Example

As I stated earlier, Jython is an implementation of Python that is
written in pure Java. This is such a powerful idea that I'm surprised
how little Jython has been recognised and adopted. Let me illustrate
the marriage of the two languages with a little example. Afterwards, we
can compare the equivalent source codes for Java and Jython. (If you
would like to try out the example for yourself and you do not already
have an installation of Jython, you can download it from the website at

I will explain the example in terms of a session with the
interactive shell, so that you understand not only how the source code
works, but also how you might work with the Jython interpreter.

So let's start up Jython's interactive shell by typing 'jython' at the command line.
You should see something like the following:

C:\My Jython>jython
Jython 2.0 on java1.4.0 (JIT: null)
Type "copyright", "credits" or "license" for more information.

Now type the following at the >>> prompt:

import javax.swing as swing

Jython accepts the import, and simply displays the next prompt,
waiting for another line of input:

C:\My Jython>jython
Jython 2.0 on java1.4.0 (JIT: null)
Type "copyright", "credits" or "license" for more information.
>>> import javax.swing as swing

The import statement allows us to use the shorter package name
'swing' as the name of the javax.swing package. We can now create an
instance of a JFrame, give it a title, make it visible, and assign it
to a variable, f, all in one line:

f=swing.JFrame(title="My Frame", visible=1)

There are several features of Jython that allow this line to be so
short. Firstly, we don't need to declare variables before using them.
(This can be a mixed blessing, as Jython is more willing to accept
typos.) Secondly, we don't use the Java keyword new for
creating an instance of a class. Thirdly, properties can be set on a
JavaBean at the time of its creation by passing them as keyword
arguments. Here, we are setting two properties: the name of the JFrame,
and its visibility. Note that Python does not have a Boolean type, as
in Java, so we must supply the visibility value as 0 (false) or 1

At this point, the JFrame is visible, so you can read its title, but it has no size.
To make the window bigger, you resize it by setting the size property of the object f:


There is quite a lot going on in this short line. Firstly, the dot
notation ('f.size'), combined with assignment, is a short hand for
setting the
value of a JavaBean property. We could have called the setSize() method directly on f (as in f.setSize(300,300)), but using the dot notation for setting property values can lead to more concise code.
Note that we did not explicitly create an instance of the java.awt.Dimension class
before assigning it to the size property. Jython knows to expect a java.awt.Dimension object, and
therefore passes the tuple (300, 300) as an argument to the constructor of the Dimension class to
create a new Dimension object. The newly created Dimension object is then set as the value of the
size property.

Our frame still doesn't do anything, so let's first create, and then add, a button:

b=swing.JButton("Push Me")

You'll need to redraw the frame before the button becomes visible
on-screen. You can do this manually by resizing the frame with the
mouse, or programmatically by calling


Now let's make the button print a message whenever it is pressed. First, we define a function that prints a message:

def printMessage(event): 
print 'Ouch!'

Next, we associate that function with the button b.


And that's it! If you press the button, the console says 'Ouch!'.

We illustrate the differences between Java and Jython code for this example by listing the source
code for each.

First, the Java source code:

import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyExample
implements ActionListener {

public void actionPerformed(ActionEvent e) {

public static void main(String[] args) {
JFrame frame = new JFrame("My Frame");
JButton button = new JButton("Push Me!");
ActionListener listener = new MyExample();

And now the Jython source code:

import javax.swing as swing

def printMessage(event):
print "Ouch!"

if __name__== "__main__":
frame=swing.JFrame(title="My Frame", size=(300,300))
button=swing.JButton("Push Me!", actionPerformed=printMessage)

You can see how much shorter the Jython code is, even for such a
simple example. Think of the implications for the cost of code
development and maintenance!

If you have tried out this example for yourself, or already used
Jython, you will have noticed another great feature of the language -
the immediate feedback you get from the interpreter. Many programmers
criticize interpreted languages for executing slowly, but when it comes
to speed of code development the interpreter wins hands-down over a
compiler. The interactive nature of an interpreter means that you
detect some errors much earlier than you would with an
edit-compile-test loop. And if you can both interpret and compile code
(as with Jython) then you get the best of both approaches.

Jython Reuse From Java

The example above has shown how you can access Java classes from
Jython. Now I should explain how you can use Jython code from Java.

The answer really is quite simple. Since Jython is an implementation
of Python in Java, it needs to compile the Python functions that you
write down to Java bytecode before it can run them. Normally it avoids
a lengthy compilation step by doing the compilation 'on the fly', but
you can also compile your Jython classes down to Java .class files or
.jar archives that you can place on the classpath of your 'master'

You perform the compilation by using the jythonc compiler provided
with Jython. This compiler first generates Java source files from the
Jython code, then compiles them using a standard Java compiler. If you
generate .class files, then you need to remember to put the jython.jar
runtime on the Java classpath when you run the master application, as
the Java source files that jythonc generates have dependencies on the
Jython runtime. If you generate a jar file using jythonc, however,
there are options to include files from the Jython runtime within the

For example, if the Jython source code for the example given above is
contained in the file, then it can be jar'ed up with
the following command:

jythonc -c -j myjar.jar

This creates a jar file containing the compiled Java version of the Jython
code we wrote as well as files from the Jython runtime.

The jar file also contains a manifest, which makes the jar executable. You can run the jar by typing:

java -jar myjar.jar

Why Isn't Everybody Using Jython?

This is the hard part! Jython is an incredibly powerful tool, and I
think there are many developers out there who would love to use it,
if only they could. It's one of those few languages that delights
the developer, because the language is so powerful and you get results
quickly. However, it is still very much a 'niche' language,
used only by forward-thinking organisations and entrepreneurs.

Here are some of the possible reasons for the low adoption rate of Jython:

Two Technologies, One Developer
It won't have escaped your notice that to understand a Jython program
(or to be more precise a Jython program that uses Java classes)
you need a solid understanding of both Java and Python. This places
demands on the skills of the developer at a time when most managers
prefer to simplify code development by choosing the technology that
is the common denominator across their applications.
Learning Curve and Project Pressures
Most developers come to Jython from Java, so have to learn about Python.
They probably have to learn Python before being able to convince colleagues
and managers that Jython will save time in the long run. And the time to
learn a new language in the midst of project pressures and approaching
deadlines is simply not available. It?s a vicious circle that needs to be
broken, and I'm confident that for many, an investment in Jython will pay off.
Old Habits Die Hard

If you're a Java developer, you are probably quite satisfied developing Java.
It's a good, well established, programming language and you?re familiar with
the idioms, patterns and style of the language that make it elegant.
Why should you change? Well, I think you should at least consider using Jython,
because firstly, Python, too, is a good programming language with a strong
following. Secondly, a good developer should always be on the look-out for
ways of becoming more productive, and I believe Jython is a good candidate.
Lastly, technologies in the IT sector are always changing, so you should
constantly re-evaluate your technology choices to be sure that you use
your chosen technologies for the right reason, instead of 'choosing' them
by default because "that's what you do".
Perception of an "Experimental Technology"
Jython is not an "Experimental Technology" -
It is industrial-strength and stable. If you're not confident enough to
use it for your main application straight away, then use it for writing
test scripts and developing prototypes. Often, developers will begin with
the intention of writing a prototype in Jython and later migrating to Java,
only to find later that the migration is not necessary.
Jython is Slow
To say that Jython is unsuitable for your application because it is
an interpreted language and therefore too slow is almost certainly false.
There are very few applications these days for which execution speed is
such a major concern. And if you do find a bottleneck in your code you
can always migrate that section of code to Java as necessary. As a
developer, you should be more concerned about the speed of development
than the speed of execution, and in this respect, Jython is fast!


Jython is a technology that marries two disparate technologies,
Java and Python, seamlessly and to great effect.
Unfortunately, I believe it has largely been overlooked by developers.
Jython has much to offer, particularly to the Java developer community,
and offers the potential to speed up conventional Java development.

Related Reading:

It has taken a while, but there are now a couple of good books about Jython on the market:


Jython Essentials by Samuele Pedroni & Noel Rappin. Published by O'Reilly, 2002.

See listing at


Jython for Java Programmers by Robert Bill. Published by New Riders, 2002.

See listing at

Powered by ScribeFire.

Python的"字节码" pyc文件



python -c "import compileall; compileall.compile_dir('py文件存放目录的路径')"



Powered by ScribeFire.




0. Python(及其它高级的脚本语言)不存在把指令编译到本地代码的工具,但是总是可以发布可执行文件。

只支持windows平台,应该是大家听到最多的一个名字了,用户不少,所以有问题的话在它的mail list里面很容易找到答案。文档中提到了"无法找到某某code"、使用opengl等模块的问题

我觉得py2exe等等工具还是罗嗦得像唐僧,需要在配置文件中写上需要的数据文件。作者完全无视这样一个事实:我需要发布可执行文件的时候,程序已经完工了,所有的数据文件就在主程序所在目录下,所以多数情况下,根本不用到别的地方搜索。现在终于有人站了出来,PyPackage实际上并不是一个程序打包的工具,而只是简化py2exe的操作,甚至可以自动调用InnoSetup 5制作安装文件——不过这个软件并不智能,会打包很多不需要的文件

2005年9月,冰冻牡蛎更新:Giovanni Bajo获得Gordon McMillan's Installer的授权、版权改变为GPL,并在继续开发PYinstaller。2006年9月更新:这里可以看到Gordon McMillan's的原始网站的镜像



还没用过,只支持Python 1.4


Stand alone Python for Windows
会不会觉得Updated: Sun, 09 Apr 2000 18:39:54 -0600 扎眼?如果你看一看它的VC源代码,就不会这么想了——其实这是普遍适用于win系统的方法,无论是98、2000或者xp。也许也可以用到linux上——我不懂linux,如果真的可以这么做,还请告诉我。

支持linux平台的工具可能也支持mac os,或者直接使用这个py2app。具体就不知道了,只吃过苹果,还没玩过苹果呢

Movable Python

Shed Skin - A Python-to-C++ Compiler: 试验项目,windows上,连他的例子我都没有编译成功 :(。

Psyco: 给Python程序加速的东西,看不出对发布Python程序的直接好处,并且作者以后将致力于PyPy。

PyPy: 项目目标是纯Python实现的Python、速度比CPython快,将来可以帮助实现编译Python。

pyc: Python compiler in Python,一个用纯Python写的Python的bytecode编译器,可以优化输出的pyc文件。和PyPy一样,现在还看不出对发布Python程序的直接好处。只有py24的bytecode。pyc是pyvm这个新的python虚拟机的一部分。

Jungle: 使用GNU工具(as、ld和winres)把Python程序编译到windows的exe可执行文件。该可执行文件只使用基于python24的的pythonic.dll。猜测它支持的模块仅限于内部模块以及jungle.jgl列出的模块。只有可执行文件下载,而这个可执行文件也是用Jungle自己编译的。目前版本号都到1.10了,经常看0.xx的版本号,这个数字好大啊,娃哈哈。


for .NET的Python编译器(如Visual Python、IronPython),不过我可不喜欢为了一个芝麻大的软件安装.NET framework



我的观点是,纯Python程序,又不想用C语言(其实C语言程序也可以破解,所以最好的方法就是不发布任何程序,嘿嘿),可以试试pyobfuscate混淆源代码,增加可能被反编译获得的源代码的阅读难度。不过pyobfuscate也好久没有更新了,娃哈哈。而实际上,没必要考虑别人会获得源代码的问题。 考虑(尤其是在自己的程序还没有写出来的时候)别人会反编译自己的Python程序,有点杞人忧天。


首先我相信,目前没有软件可以很好反编译Python 2.4及之后的版本生成的字节码,所以采用新版本Python“编译”到可执行文件,是安全的。




Friday, 23 November 2007

Bugatti Veyron top speed test (408Km/h)

To download the full version visit

Blogged with Flock


在amarok 或者 banshee 等播放器中 导入的mp3 很多都是乱码。看起来很别扭,今天找到了解决的方法 找到了一款java编写的小程序。


  下载ID3iconv 0.2.1 Binary

  cd到 mp3文件夹 这个很关键 不cd进去 是不行的 会出错。
  执行命令 sudo java -jar ~/id3iconv-0.2.1.jar -e gbk -removev1 *.mp3

  如果 程序出错 很有可能是java环境的错误,可以配置一下环境。



  sudo apt-get install sun-java6-jre


  sudo apt-get install sun-java6-jdk


  sudo update-alternatives --config java


Powered by ScribeFire.

Thursday, 22 November 2007


Crossonline below is my Blog ID, just change it to yours, it will work. Anything wrong, please comment to let me know, thanks.



  • 更改C:\WINDOWS\system32\drivers\etc\hosts,添加
  • 最近部分地区的电信好像是又把blogspot.com给封了,至少在极速客那里很多人反应,河北网通这里还是好好的,可以正常访问。不过看到极速客提供的比较费神费力的修改Hosts的方法,我很乐意分享一下我是怎样访问被封杀的blogspot的。首先打开Notepad(或者其他的编辑器),写入如下内容:
    function FindProxyForURL(url,host){
    if(dnsDomainIs(host, "")){
    return "PROXY";
    另 存为proxy.pac到C盘的根目录下,以Firefox为例,打开Firefox,依次点击Tools->Options-> Advanced->Network->Settings...->选中Automatic proxy configuration URL,在下面填写:
    ,再点Reload,再点Ok,一路 Ok下去,就可以了。这个方法的巧妙之处(其实一点都不巧妙啦)就在于不用像极速客介绍的那样修改一堆有的没的的Hosts,只要一个“.”就保证了所有 blogspot的子域名可以没有限制的访问(内含GFW关键字的除外),嗯,Enjoy。

    P.S. Linux用户应该不需要Linux版本了吧,照葫芦画瓢对与Linux用户来说应该是再简单不过了,XD

    function FindProxyForURL(url,host){
    if(dnsDomainIs(host, "")){
    return "PROXY";
    if(dnsDomainIs(host, "")){
    return "PROXY";
    然 后保存,重启浏览器就可以了。这个原理是利用了该域名的多服务器的特征,每个服务器对应一个IP,GFW只是封杀了其中的一个IP地址,默认的那个,其他 的还是好好的,所以可以用这种方法进行访问,但也取决于网站本身,比如vox.com之前还支持,后来其IP地址为“”的服务 器修改了设置,所以上方法就不能用了。以此类推,同志们还可以去Hack一下Technorati等等其他好的网站的其他服务器的IP地址,这样照着修改 一下就能畅通无阻的访问了。此致,敬礼。
使用firefox和其插件access flickr.

Creating .deb-Packages With Checkinstall

Version 1.0

Author: Falko Timme <ft [at] falkotimme [dot] com>
Last edited 02/04/2005

Checkinstall is a nice tool to create simple .deb-packages that you can use in your local network (e.g. if you have to install the same piece of software on multiple computers running Debian). It lets you compile and install software from the sources like before, but with the difference that you end up with a simple Debian package which also means that you can easily uninstall the software you just compiled by running dpkg -r!

I will demonstrate the use of checkinstall by compiling and installing the anti-virus software ClamAV on a Debian system.

This howto is meant as a practical guide; it does not cover the theoretical backgrounds. They are treated in a lot of other documents in the web.

This document comes without warranty of any kind!


1 Install Checkinstall

It is as easy as 1-2-3:

apt-get install checkinstall

If your system tells you that it does not know a package called checkinstall then add the following line to /etc/apt/sources.list:

deb woody checkinstall

and run

apt-get update

Then try again to install checkinstall.


2 Install ClamAV

We need the ClamAV sources . We will install the software from the /tmp directory.

cd /tmp
apt-get install libgmp3 libgmp3-dev
groupadd clamav
useradd -g clamav -s /bin/false -c "Clam AntiVirus" clamav
tar xvfz clamav-0.81.tar.gz
cd clamav-0.81/
./configure --sysconfdir=/etc

(Please note: ./configure --help gives a list of all configuration options available.)


Now comes the main difference: instead of make install we run

checkinstall -D make install

Answer the question "The package documentation directory ./doc-pak does not exist.
Should I create a default set of package docs? [y]:"
with y.

Then enter a description for your package (e.g. ClamAV 0.81). A summary of the configuration options for your .deb-package will come up:

You can change them here or just hit enter to continue. Now ClamAV will be installed plus a Debian package will be created which you can find in the installation directory /tmp/clamav-0.81 as the final checkinstall summary states:

Now you can copy clamav-0.81_0.81-1_i386.deb to other Debian computers and run

dpkg -i /path/to/clamav-0.81_0.81-1_i386.deb

to install it. If you want to remove it, just run

dpkg -r clamav-0.81

This even works on the computer you compiled ClamAV on! This is a nice way to install software from the sources and remove it if you are unsatisfied with the result.

Blogged with Flock

Wine Review: DirectX 9.0c on Linux with Wine

Microsoft DirectX is a collection of application programming interfaces for handling tasks related to multimedia, especially game programming and video, on Microsoft platforms. Originally, the names of these APIs all began with Direct, such as Direct3D, DirectDraw, DirectMusic, DirectPlay, DirectSound, and so forth. DirectX, then, was the generic term for all of these Direct-something APIs, and that term became the name of the collection. Over the intervening years, some of these APIs have been deprecated and replaced, so that this naming convention is no longer absolute. In fact, the X has caught on to the point that it has replaced Direct as the common part in the names of new DirectX technologies, including XAct, XInput, and so forth.

Direct3D (the 3D graphics API within DirectX) is widely used in the development of computer games for Microsoft Windows, Microsoft Xbox, and Microsoft Xbox 360. Direct3D is also used by other software applications for visualization and graphics tasks, most notably among the engineering sector for CAD/CAM, because of its ability to quickly render high-quality 3D graphics using DirectX-compatible graphics hardware. As Direct3D is the most widely recognized API in DirectX, it is not uncommon to see the name DirectX used in place of Direct3D.

Wine configuration

This is with a clean configuration directory and running in a 1024x768 virtual desktop.

$ winecfg

Once the .wine directory is built the configuration tool will start and you can set a virtual desktop in the graphics tab if you wish. This is a good time to also set your Audio driver in the Audio tab.

next up is to install a native mscoree.dll and streamci.dll into /system32 from a windows install and set then to native Windows.

Go to ~/.wine/drive_c/windows/system32 and rename d3d8, d3d9, ddraw, dsound, dsound.vxd, quartz dlls to *.bak

You will need to set a large number of dlls to native for the install to work properly. Here is the full list of dlls that need to be set.


Installing Directx

Download DirectX 9.0c November release from here.

The directx_nov2007_redist.exe executable will extract the installer files to a directory of your choice.

tom@tuxonfire ~ $ wine directx_nov2007_redist.exe
fixme:advapi:DecryptFileA "z:\\home\\tom\\directx-9\\" 00000000
fixme:midi:OSS_MidiInit Synthesizer supports MIDI in. Not yet supported.
tom@tuxonfire ~ $

Now cd to the directory where you choose to extract the DirectX installer and run DXSETUP.EXE.

tom@tuxonfire ~ $ cd /home/tom/directx-9
tom@tuxonfire ~/directx-9 $ wine DXSETUP.EXE
fixme:midi:OSS_MidiInit Synthesizer supports MIDI in. Not yet supported.

Run winecfg again and set d3d8, d3d9, ddrawex, dinut, dinput8 to builtin wine.

Now lets run dxdiag.exe

tom@tuxonfire ~/directx-9 $ cd /home/tom/.wine/drive_c/windows/system32
tom@tuxonfire ~/.wine/drive_c/windows/system32 $ wine dxdiag.exe
fixme:ole:CoInitializeSecurity ((nil),-1,(nil),(nil),1,3,(nil),0,(nil)) - stub!

We can now test ddraw, ddraw 3D, D3D8, and D3D9

Direct Sound test:

Now we need to install gm.dls to test Direct Music, this driver file goes into ~/.wine/drive_c/windows/system32/drivers

Direct Play test:

You will notice in system32 d3dx9_24.dll up to d3dx9_36.dll is now installed, this really helps when you run into a game that needs these additional DirectX dlls.

Now you have the option to run most DirectX dlls in native or builtin mode, for example if you have a game that's crashing on the builtin Wine quartz.dll you can test the game with the native Windows dll to see if this will improve the situation.

Keep in mind d3d8, d3d9, ddraw will only work as builtin, and in most cases you should try to use builtin dsound and dinput. I have had limited success with (dsound and dinput) in native Windows mode btw... The reason why these dlls have to be used in builtin mode is there need for direct access to your hardware. direct music and direct play can be used in native windows mode in most circumstances.

Feel free to comment about this post at the wine-forum.

Blogged with Flock

Wednesday, 21 November 2007

flash animation in Flash IDE

To download the full version visit


Mozilla Labs Blog » Blog Archive » Prism

Personal computing is currently in a state of transition. While traditionally users have interacted mostly with desktop applications, more and more of them are using web applications. But the latter often fit awkwardly into the document-centric interface of web browsers. And they are surrounded with controls–like back and forward buttons and a location bar–that have nothing to do with interacting with the application itself.


Mozilla Labs is launching a series of experiments to bridge the divide in the user experience between web applications and desktop apps and to explore new usability models as the line between traditional desktop and new web applications continues to blur.

Unlike Adobe AIR and Microsoft Silverlight, we’re not building a proprietary platform to replace the web. We think the web is a powerful and open platform for this sort of innovation, so our goal is to identify and facilitate the development of enhancements that bring the advantages of desktop apps to the web platform.

The first of these experiments is based on Webrunner, which we’ve moved into the Mozilla Labs code repository and renamed to Prism.



Prism is an application that lets users split web applications out of their browser and run them directly on their desktop.


Prism lets users add their favorite web apps to their desktop environment:


When invoked, these applications run in their own window:


They are accessible with Control-Tab, Command-Tab, and Exposé, just like desktop apps. And users can still access these same applications from any web browser when they are away from their own computers.

The Best of Both Worlds

Prism isn’t a new platform, it’s simply the web platform integrated into the desktop experience. Web developers don’t have to target it separately, because any application that can run in a modern standards-compliant web browser can run in Prism. Prism is built on Firefox, so it supports rich internet technologies like HTML, JavaScript, CSS, and <canvas> and runs on Windows, Mac OS X, and Linux.

And while Prism focuses on how web apps can integrate into the desktop experience, we’re also working to increase the capabilities of those apps by adding functionality to the Web itself, such as providing support for offline data storage and access to 3D graphics hardware.


The User Experience

We’re also thinking about how to better integrate Prism with Firefox, enabling one-click “make this a desktop app” functionality that preserves a user’s preferences, saved passwords, cookies, add-ons, and customizations. Ideally you shouldn’t even have to download Prism, it should just be built into your browser.


We’re working on an extension for Firefox that provides some of this functionality. For more information about the user experience we hope to achieve in Prism, see Alex Faaborg’s blog post. For some of the technical details and new features found in Prism, see Mark Finkle’s blog post.

Getting Started with Prism

We have an early prototype for this working today on Windows, with work continuing on Mac and Linux (for which we should have builds available soon).

To try out the prototype, download and install it: Download Prism for Windows.

Then start Prism. It will display an Install Web Application dialog.


Enter the URL of the application you want to use in Prism (e.g., a name for the application (e.g. Gmail), and pick where you’d like to create shortcuts to the application.

Then press the OK button. Prism will create shortcuts to the application in the locations you specified and then start the application.

How to Get Involved

Prism is just the first of many experiments we hope to conduct around improving the usability of web applications. It’s open source, like everything we do, and we’re interested in hearing from and working with anyone interested in further developing this concept.

  • Discuss, debate and add to the design in the forum. Report bugs in Bugzilla.
  • Get the source code, extend it, fix bugs and/or submit patches.

    The project lead for Prism is Mark Finkle and contributors include Cesar Oliveira, Wladimir Palant, Sylvain Pasche, Alex Faaborg, and Myk Melez.

Blogged with Flock


关于Linux操作系统下C语言编程的注意事项 — IT技术 - 赛迪网












  glib 库是gtk+和gnome的基础库,并具是跨平台的,在linux、unix和windows下都可以用。glib库对于linux平台开发的影响就像 MFC对windows平台开发的影响一样,很多开源项目都大量的使用了glib库,包括gimp、gnome、gaim、evolution和 linux下的集群软件heartbeat。因为glib库自带有基本的数据结构实现,所以在学习glib库的时候可以顺便学习一下基本的数据结构(包括链表、树、队列和hash表)。




  readline 库是bash shell用的库,如果要开发命令行程序,那么使用readline库可以减少很多工作量,比如bash里的命令行自动补全,在readline里就已经有实现,当然你也可以用自己的实现替代库的行为。readline库有很多网站介绍的,只要google一下readline就可以找到一堆了。


  curses 库以前是vi程序的一部分,后来从vi里提取出来成为一个独立的库。curses库对于编写终端相关的程序特别有用,比如要在终端某一行某一列定位输出,改变终端字体的颜色和终端模式。linux下的curses库用的是GNU实现的ncurses(new curses的意思)。  

  这两个库是开发GUI应用程序的基础库,现在linux下的大部份GUI程序都是基于这两个库开发的,对于它们 的学习也是很有必要的。




Powered by ScribeFire.

Monday, 19 November 2007

Windows Network Trafic Management (to be contiuned and commented)

In windows to show the network trafic:
netsh interface ipv4 show subinterfaces

Blogged with Flock

gMOVE series

Google has recently updated the migration tools from Google Apps to "move email from anywhere – not just IMAP systems – to the Premier, Education or Partner Editions of Google Apps." An example of solution that uses the API is gMOVE from LimitNone, a tool that migrates your email, contacts and calendars from Outlook to Google Apps. gMOVE also migrates the tasks from Outlook to an iGoogle gadget.

The tool costs $19 and it works with any Google Apps account. If you post an insightful comment that explains why do you want to migrate from Outlook to Google Apps, you could get gMOVE for free. Don't forget to include your email address so I can contact you.

LimitNone also has a free tool that lets you move from a Gmail account to another Gmail account or to Google Apps: it transfers your messages, filters, contacts and calendar events.

Blogged with Flock

Sunday, 18 November 2007





  3.在XP的命令提示符状态下运行 X:\boot\bootsect /nt60 x: (X即移动硬盘分区盘符)这一步是让移动硬盘成为可引导分区



Blogged with Flock

Welcome to Firebug 1.0

Blogged with Flock

Maintainable JavaScript

Blogged with Flock

JavaScript Video Tutorial III 3

Blogged with Flock

JavaScript Video Tutorial III 2

Blogged with Flock

My photo
London, United Kingdom

Facebook & Twitter