Sunday, 5 July 2009

Scala, the Google App Engine and an iPhone client...

In this Blog I wanted to explore Scala on the Google App Engine. The Google App Engine has supported Java (as well as Python) for a little while now. There have been a few blogs about running Scala on the App engine and I wanted to further demonstrate this by taking a simple Java Servlet and converting it to a Scala based web application suitable for the App Engine.

The Google App Engine home is here http://code.google.com/appengine/ and contains excellent documentation on how to get stated. I don't want to repeat the documentation, so I'll just point out the essentials relevant to this blog.

The Getting Started guide can be found here: http://code.google.com/appengine/docs/java/gettingstarted/ for Java, and a Python equivalent is available too.

This example is based on the previous blog, the Sieve of Eratosthenes as a simple prime number generator. The request accepts one parameter n whose integer value is the upper limit to generate all the primes until (from 2). The response output is JSON encoded to create a simple web service.


Starting with the very basics, the recommended project directory structure is of the form:


|-src
|---META-INF
|---primes
|-war
|---WEB-INF
|-----classes
|-------META-INF
|-------primes
|-----lib



For any Web App for the Google App Engine, one additional GAE specific file is required alongside the standard web.xml deployment descriptor. This file is called appengine-web.xml and contains the name of the Application, for example:


<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<application>primes-chillipower-com</application>
<version>1</version>
</appengine-web-app>


In this simple GAE deployment descriptor the main thing is that the name of the application is specified, in this example the application was called 'primes-chillipower-com'.

Applications must be created on the App Engine, this can be done here: http://appengine.google.com/

Note that there are some limitations currently, you are allowed up to a maximum of 10 applications and applications can not be deleted once created!


The simple Java version:

In the simple Java version we can place a simple Servlet in the src directory and build using ant.


Example Java servlet:


package primes;

import java.io.IOException;
import javax.servlet.http.*;

public class PrimesServletJ extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");

int n = 100;

String nStr = req.getParameter("n");

try {

n = Integer.parseInt(nStr);
}
catch (Exception e) {}

int[] primes = primes(n);

resp.getWriter().println("{ \"n\" : \"" + n + "\",");
resp.getWriter().println(" \"primes\" : [ ");

for (int i = 0; i < primes.length; i++) {
String sep = (i < primes.length - 1) ? ", " : "";
resp.getWriter().println(" { \"" + i + "\" : \"" + primes[i] + "\" }" + sep);
}

resp.getWriter().println(" ] }");
}

public static int[] primes(int n) {

// initially assume all integers are prime
boolean[] isPrime = new boolean[n + 1];

for (int i = 2; i <= n; i++) {
isPrime[i] = true;
}

// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 2; i*i <= n; i++) {

// if i is prime, then mark multiples of i as nonprime
// suffices to consider mutiples i, i+1, ..., N/i
if (isPrime[i]) {
for (int j = i; i * j <= n; j++) {
isPrime[i * j] = false;
}
}
}

// count primes
int primeCount = 0;
for (int i = 2; i <= n; i++) {
if (isPrime[i]) primeCount++;
}

System.out.println("The number of primes <= " + n + " is " + primeCount);

int[] primes = new int[primeCount];
int idx = 0;
for (int i = 0; i <= n; i++) {
if (isPrime[i] == true) {

primes[idx] = i;
idx++;
}
}

return primes;
}

public static void main(String[] args) {

int n = 100;

if (args.length > 0 && args[0] != null) {
n = Integer.parseInt(args[0]);
}

int[] primes = primes(n);

for (int p : primes) {
System.out.println("Prime: " + p);
}
}
}



The ant build script goes in the root of the project, to start with I based mine on the example on the Google App Engine documentation here http://code.google.com/appengine/docs/java/tools/ant.html#Uploading_and_Other_AppCfg_Tasks

Using the standard ant script the project can be compiled and even run locally using the SDK.

ant compile

ant runserver


If you start the dev app server locally, it will be accessibly using a URL of the form:

http://localhost:8080/yourappcontextpath


Where the port 8080 is the default and can be changed in the script.

The App Engine SDK comes with appcfg.sh script in the bin directory, which can be used to perform operations such as uploading your app to the App Engine.


../../../../tools/appengine-java-sdk-1.2.1/bin/appcfg.sh update war


The Scala version:

The main tasks in converting this conventional Java Servlet based web app to a Scala based one is to:
  • Rewrite the Java Servlet in Scala.
  • Reconfigure the ant build.xml to modify the classpath to include the Scala libraries and to run the Scala scalac compiler to create the Java .class files from the .scala source files.

Since the Servlet API is a Java based API, there will of course be some reference to Java based classes in the Scala Servlet.


Example Scala based Servlet:


package primes

import javax.servlet.http._


class PrimesServlet extends HttpServlet {
override def doGet(request: HttpServletRequest, response: HttpServletResponse) = {

var n = 100

try {
val nStr = request.getParameter("n");
n = Integer.parseInt(nStr);
} catch {
case e : Exception => {
println("Exception e " + e.getMessage())
}
}

val ps = primes take n
val out = response.getWriter()

out.println("{ \"n\" : \"" + n + "\", \"primes\" : [")

var i = 0
for (p <- ps) {
val sep = if (i < ps.length - 1) ", " else ""
out.println(" { \"" + i + "\" : \"" + p + "\" }" + sep)
i = i + 1
}

out.println(" ] } ")
}

def primes = {
def sieve(is: Stream[Int]): Stream[Int] = {
val h = is.head
Stream.cons(h, sieve(is filter (_ % h > 0)))
}

sieve(Stream.from(2))
}
}





Example modified and build.xml file:


<project>
<property name="scala.home" location="/Users/chillipower_uk/dev/tools/scala/scala-2.7.5.final/" />
<property name="sdk.dir" location="/Users/chillipower_uk/dev/tools/appengine-java-sdk-1.2.1/" />

<import file="${sdk.dir}/config/user/ant-macros.xml" />

<path id="project.classpath">
<pathelement path="war/WEB-INF/classes" />
<fileset dir="war/WEB-INF/lib">
<include name="**/*.jar" />
</fileset>
<fileset dir="${sdk.dir}/lib">
<include name="shared/**/*.jar" />
</fileset>
</path>

<!-- Copy over Scala jars -->
<target name="init">
<property
name="scala-library.jar"
value="${scala.home}/lib/scala-library.jar"
/>
<path id="build.classpath">
<pathelement location="${scala-library.jar}" />

<pathelement location="${build.dir}" />
</path>
<taskdef resource="scala/tools/ant/antlib.xml">
<classpath>
<pathelement location="${scala.home}/lib/scala-compiler.jar" />
<pathelement location="${scala-library.jar}" />
</classpath>
</taskdef>
</target>

<!-- Copy Scala JARs -->
<target name="copyscala"
description="Copies the Scala JARs to the WAR.">
<copy
todir="war/WEB-INF/lib"
flatten="true">
<fileset dir="${scala.home}/lib">
<include name="**/scala-library.jar" />
</fileset>
</copy>
</target>

<!-- Copy App engine jars -->
<target name="copyjars"
description="Copies the App Engine JARs to the WAR.">
<copy
todir="war/WEB-INF/lib"
flatten="true">
<fileset dir="${sdk.dir}/lib/user">
<include name="**/*.jar" />
</fileset>
</copy>
</target>

<target name="compile" depends="copyscala, copyjars, init"
description="Compiles Java source and copies other source files to the WAR.">
<mkdir dir="war/WEB-INF/classes" />
<copy todir="war/WEB-INF/classes">
<fileset dir="src">
<exclude name="**/*.scala" />
<exclude name="**/*.java" />
</fileset>
</copy>
<scalac
srcdir="src"
destdir="war/WEB-INF/classes"
classpathref="project.classpath"
/>

<!--
<copy todir="war/WEB-INF/classes">
<fileset dir="src">
<exclude name="**/*.scala" />
<exclude name="**/*.java" />
</fileset>
</copy> -->
<javac
srcdir="src"
destdir="war/WEB-INF/classes"
classpathref="project.classpath"
debug="on" />

</target>

<target name="datanucleusenhance" depends="compile"
description="Performs JDO enhancement on compiled data classes.">
<enhance_war war="war" />
</target>

<target name="runserver" depends="datanucleusenhance"
description="Starts the development server.">
<dev_appserver war="war" />
</target>

<target name="update" depends="datanucleusenhance"
description="Uploads the application to App Engine.">
<appcfg action="update" war="war" />
</target>

<target name="update_indexes" depends="datanucleusenhance"
description="Uploads just the datastore index configuration to App Engine.">
<appcfg action="update_indexes" war="war" />
</target>

<target name="rollback" depends="datanucleusenhance"
description="Rolls back an interrupted application update.">
<appcfg action="rollback" war="war" />
</target>

<target name="request_logs"
description="Downloads log data from App Engine for the application.">
<appcfg action="request_logs" war="war">
<options>
<arg value="--num_days=5"/>
</options>
<args>
<arg value="logs.txt"/>
</args>
</appcfg>
</target>

</project>




Example request and output:

Request: http://primes-chillipower-com.appspot.com/primes?n=50


{ "n" : "50", "primes" : [ { "0" : "2" }, { "1" : "3" }, { "2" : "5" }, { "3" : "7" }, { "4" : "11" }, { "5" : "13" }, { "6" : "17" }, { "7" : "19" }, { "8" : "23" }, { "9" : "29" }, { "10" : "31" }, { "11" : "37" }, { "12" : "41" }, { "13" : "43" }, { "14" : "47" }, { "15" : "53" }, { "16" : "59" }, { "17" : "61" }, { "18" : "67" }, { "19" : "71" }, { "20" : "73" }, { "21" : "79" }, { "22" : "83" }, { "23" : "89" }, { "24" : "97" }, { "25" : "101" }, { "26" : "103" }, { "27" : "107" }, { "28" : "109" }, { "29" : "113" }, { "30" : "127" }, { "31" : "131" }, { "32" : "137" }, { "33" : "139" }, { "34" : "149" }, { "35" : "151" }, { "36" : "157" }, { "37" : "163" }, { "38" : "167" }, { "39" : "173" }, { "40" : "179" }, { "41" : "181" }, { "42" : "191" }, { "43" : "193" }, { "44" : "197" }, { "45" : "199" }, { "46" : "211" }, { "47" : "223" }, { "48" : "227" }, { "49" : "229" } ] }



The iPhone client:

I'm currently developing using the iPhone 3.1 beta SDK. I'm not going to post all the source code the the simple client, but rather give some essential snippets relevant to the invocation of the simple JSON web service once deployed on the Google App Engine.

To Consume this JSON in an iPhone app, we can use the JSON Objective-C library, which is available on Google code here http://code.google.com/p/json-framework/wiki/FAQ



- (void)loadData {
[super viewDidLoad];

NSString *urlString = [NSString stringWithFormat:@"http://primes-chillipower-com.appspot.com/primes?n=1000"];
NSURL *url = [NSURL URLWithString:urlString];

NSDictionary *primesResponse = (NSDictionary *)[JsonClientHelper fetchJSONValueForURL:url];

if (primesResponse != nil) {

NSArray *primeEntries = [primesResponse objectForKey:@"primes"];

NSMutableArray *primesTemp = [[NSMutableArray alloc] init];
[primesTemp retain];

for (int i = 0; i < [primeEntries count]; i++) {

NSDictionary *primeEntry = (NSDictionary*)[primeEntries objectAtIndex:i];

NSString *key = [NSString stringWithFormat:@"%d", i];

NSString *p = [primeEntry objectForKey:key];

NSString *msg = [NSString stringWithFormat:@"Prime %d = %@", i, p];

NSLog(msg);

[primesTemp addObject:p];
}

primes = [primesTemp copy];

[primesTemp release];
}
}




The above code makes a request to the JSON web service on the App Engine and decodes the response, which once decoded using the JSON library is contained in Dictionaries (NSDictionary) and Arrays (NSArray).


Where JsonClientHelper contains a basic class helper method fetchJSONValueForURL to fetch and decode a JSON response from the supplied URL.



+ (id)fetchJSONValueForURL:(NSURL *)url
{
NSString *jsonString = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];

id jsonValue = [jsonString JSONValue];

[jsonString release];

return jsonValue;
}

I hope this Blog has helped give some insight into creating a Scala based Web Application for the Google App Engine, as well as the consumption of JSON in an iPhone Objective-C client.

(I appologise for the formatting of the code in this blog, finding it awkward to get the code into the blog without it being mangled in some way!).


Resources:

Handy JSON Lint tool: http://www.jsonlint.com/

Scala Servlet development: http://blogs.oracle.com/aseembajaj/2008/08/scala_servlet_development.html

Scala on the Google App Engine: http://froth-and-java.blogspot.com/2009/04/scala-on-google-appengine.html


.

Friday, 3 July 2009

Scala, lazy evaluation and the Sieve of Eratosthenes

This blog posting is primarily concerned with looking at lazy evaluation in functional programing, what it means and how it can be put to use.

Lazy evaluation can be described as an expression that has a value, but that is not evaluated until it's actually needed. Conversely strict refers to the opposite property where all expressions are evaluated up front when declared.

Some functional languages are described as Pure Lazy (no, this is not a derogatory term!), to reflect the fact that all evaluation is performed on demand. Haskell is on such language. Scala has both aspects of strict evaluation and lazy evaluation, as such it couldn't be referred to as 'pure' in either sense.

The examples are based on the Sieve of Eratosthenes. Eratosthenes was an ancient Greek Mathmetician from 276 BC – c. 195 BC. The Sieve of Eratosthenes is a ancient algorithm for finding prime numbers from 2 .. n. Stated simply, this algorithm can be expressed as:


  • Create a list of all the numbers from 2 .. n.
  • Starting at p = 2
  • Strike out all multiples of p up until n from the list
  • Let p now be the first (lowest) number that has not been struck-off the list
  • Repeat the last two steps until p^2 > n
  • All remaining numbers not struck from the list are prime

In Haskell this can be expressed very elegantly and succinctly, as follows:

primes = sieve [2..]
sieve (p : xs) = p : sieve [x | x <− xs, x `mod` p > 0]


Note that [2..] creates an infinite steam of all the integers from 2 to infinity. You might think this is impossible and would create an out of memory error on the machine it ran on, but this is perfectly valid in a pure lazy language because none of the numbers are actually generated until they are requested!

In Scala there's not really a way to represent this quite so succinctly, but it is possibly to create a Lazy stream of numbers using:

var is = Stream from 2

which is essentially equivalent to Haskell's:

[2..]

Syntax.


Another important thing to note and be aware of is that Scala's List class is not a lazy list. Therefore, trying to make the equivalent of the Haskell algorithm in Scala using a List is not going to work.

Scala's Stream class however is Lazy, and so it can form the basic of the equivalent algorithm in Scala. To be specific, Scala's Stream class is strict about head and lazy about tail - which is ok since head contains a finite set of 0|1 elements.


The following Scala code shows two ways to implement the Sieve using Scala Lazy streams.


Example 1:


package primes;

/* Haskell...

primes = sieve [2..]
sieve (p : xs) = p : sieve [x | x <− xs, x `mod` p > 0]
*/
object Primes1 {

def primes : Stream[Int] = {

var is = Stream from 2

def sieve(numbers: Stream[Int]): Stream[Int] = {
Stream.cons(
numbers.head,
sieve(for (x <- numbers.tail if x % numbers.head > 0) yield x))
}

sieve(is)
}

def main(args : Array[String]) = {

primes take 100 foreach println
}
}

object Primes2 {
def primes = {
def sieve(is: Stream[Int]): Stream[Int] = {
val h = is.head
Stream.cons(h, sieve(is filter (_ % h > 0)))
}

sieve(Stream.from(2))
}

def main(args: Array[String]) {
println(primes take 100 toList)
}
}



Note the use of the 'take' method to extract the first 100 primes from the stream (so the program terminates!).


This second example shows how we can define a Lazy list like trait and then use it to implement the same, equivalent behavior:


Example 2:


package primes


object PrimesLazyTrait {

sealed trait Lazy[+A] {
def head: A = this match {
case Nil => error("head called on empty")
case Cons(h, _) => h()
}

def tail: Lazy[A] = this match {
case Nil => error("tail on empty")
case Cons(_, t) => t()
}

def filter(p: A => Boolean): Lazy[A] = this match {
case Nil => Nil
case Cons(h, t) => if(p(h())) Cons(h, () => t() filter p) else t() filter p
}

def foreach(f: A => Unit) {
this match {
case Nil =>
case Cons(h, t) => {
f(h())
t() foreach f
}
}
}

def toList: List[A] = this match {
case Nil => scala.Nil
case Cons(h, t) => h() :: t().toList
}
}

final case class Cons[+A](h: () => A, t: () => Lazy[A]) extends Lazy[A]
case object Nil extends Lazy[Nothing]

def from(n: Int): Lazy[Int] = Cons(() => n, () => from(n + 1))

def primes = {
def sieve(is: => Lazy[Int]): Lazy[Int] = {
lazy val h = is.head
Cons(() => h, () => sieve(is filter (_ % h > 0)))
}

sieve(from(2))
}

def main(args: Array[String]) {
primes foreach println
}
}




In this version we see the Lazy trait provides the necessary methods head, tail, filter, foreach and toList.


These little examples help demonstrate some of the power, elegance and conciseness of lazy functional programming - as well as the beauty of this Ancient Greek algorithm for finding primes.


The basic algorithms complexity is:

  • O((nlogn)(loglogn))

And has a memory requirement of:

  • O(n).

Without any optimization.


.

Monday, 15 June 2009

Scala actors, an introduction with some simple examples

The Scala programming language provides an Actor based framework for handling concurrency.

Scala's Actor model for concurrent programming was originally inspired by the Erlang programming language.

The actor model is a system of asynchronous message passing for concurrent programming, rather than the typical shared data and locks model. The shared data and locks model has some inherent difficulties that make programming in this way difficult and error prone. Major problems with shared data and locks include the well known dead-lock problem, as well as live locks and the general problem of locking shared mutable data without affecting program scalability and performance. Whilst Scala's actor messaging framework is build around asynchronous messaging, synchronous messaging is provided on top of this for convenience.

The Scala's actor model is based around an actor library and the Actor trait, along with some simple syntactical constructs for sending and receiving messages.

The actor library can be included into a project using:

import scala.actors.Actor._

The simplest way to start an actor is to declare an object/class that extends the class Actor and in the body of the actor declare an act() {} method to do the work. The actor x can then be started much like a thread, using x.start(). The act() method is much like the Java Thread's run() method.

A more succinct method is to declare a variable val x = actor {} and put the action definition directly between the braces (no act method required). What happens here is that actor is a helper method on Actor that creates and starts the actor - so there is no need to call x.start() explicitly when using this approach.

Actors can receive messages using the receive {} method. The receive message is passed a partial function to receive the messages. Typically the body of the receive method uses case pattern matching to determine what to do with the message.

A message can be sent to an actor using the ! operation. For example, an Int can be sent to actor x using: x ! 3

All actors get their own thread to call the receive function - this causes scalability problems when there are many actors with receive functions. The way to overcome this in Scala is to use the react() {} method instead. React is similar to receive except it doesn't not need a native thread to run and but must call itself when done to receive more messages - apart from this both are the same in that they both take a partial function.

Scala provides a convenience to avoid having to call act/react within a react method, this is the loop construct. This ends up looking as simple as:


loop {
react {
// message handling body goes here
}
}

Note that react itself does not end end by returning up the call stack in the normal way, all calls to react result in an exception.

Within a receive or react method, an actor can reply to the sender of the received message by messaging the special identifier "sender", which represents the source of the message.


Example 1:

This simple example shows the most basic way to create an actor, by extending Actor, creating an instance and calling start on it.


package scalaactors1

import scala.actors._

class Actor1 extends Actor {

def act {
var x = 1
while (true) {
println("actor1! " + x)
x = x + 1
Thread.sleep(500)
}
}
}

object TestActors1 {

/**
* @param args the command line arguments
*/
def main(args: Array[String]) = {

println(">>main() - starting")

val actor1 = new Actor1()

actor1.start()

println("<<main() - ending")
}
}



Example 2:

This example creates a couple of actors using the val x = actor {} constructs. Each actor will automatically start and run concurrently, outputting a message and sleeping in an infinite loop. If you run this you can observe that the main thread starts and ends, the messages from the two actors are interleaved and run even after the main method has ended.


package scalaactors1

import scala.actors.Actor._

object TestActors2 {

/**
* @param args the command line arguments
*/
def main(args: Array[String]) = {

println(">>main() - starting")


val actor1 = actor {

var x = 1
while (true) {
println("actor1! " + x)
x = x + 1
Thread.sleep(500)
}
}

val actor2 = actor {

var x = 1
while (true) {
println("actor2! " + x)
x = x + 1
Thread.sleep(1000)
}
}

println("<<main() - ending")
}
}



Example 3:

This example is slightly more complex.

Actor kbReaderActor takes input from the keyboard (as Chars) and passes them one by one to the actor kbProcessorActor which prints out the received character and then uses a 3rd actor called sleep to sleep for the specified amount of time before then waking up the kbProcessorActor (to simulate some "work" that takes a finite amount of time to complete). Note that sleep signals the "sender" using a simple case class to represent the message type (with no arguments).



package scalaactors1

import scala.actors.Actor._

case class Wakeup // simple signalling case class


// simple actor example
object TestActors3 {

def main(args: Array[String]) = {

println(">>Starting")

val sleep = actor {

loop {
react {
case x : int => {
println("sleeping for " + x)

java.lang.Thread.sleep(x)

println("waking up sender...")

sender ! Wakeup
}
}
}
}

val keyProcessorActor = actor {

println(">>keyProcessorActor starting")

var key : Option[Char] = null

loop {

react {
case 'q' => exit() // 'q' signifies quit app!
case x : Char => println("keyProcessorActor received '" + x + "'")

sleep ! 1000 // ask the sleep actor to sleep, we will get a Wakeup call when done

// now wait for our wakeup
var r = false

do {
receive {
case Wakeup => r = true
}
} while (!r)
}
}

println("<<keyProcessorActor ending")
}

val kbReaderActor = actor {

println(">>kbReaderActor starting")

var key : Char = ' '

do {

println("kbReaderActor waiting for input")
val i = System.in.read()

key = i.asInstanceOf[Char]

println("Received input " + key)

// message actor1 with the key read from the console
keyProcessorActor ! key

} while (key != 'q')

println("<<kbReaderActor ending")
}

println("<<Application Ending")
}
}



.

Saturday, 6 June 2009

Quantum Entanglement, entanglement with 2 electron singlet

(and now for something completely different... Quantum mechanics and quantum entanglement)

Quantum Entanglement:
Entanglement with 2 element quantum singlet.

Having recently emailed Leonard Susskind (Stanford CA) with a question regarding entanglement of a 3rd element with a 2 element system in the quantum singlet state (an entangled pair).

Leonard Susskind is the Felix Bloch professor of theoretical physics at Stanford University in the field of string theory and quantum field theory http://en.wikipedia.org/wiki/Leonard_Susskind

Susskind is widely regarded as one of the fathers of String Theory.

So naturally, I was somewhat surprised when I actually got a detailed response, and the answer is very interesting and informative too! Like most things in Quantum mechanics, the result is not something that could be guest or anticipated, it's not something that could be expected using classical intuition or experience.


Here is the reply:

--

Let’s begin with the initial state consisting of two electrons in a singlet state |ud-du> .( I should include a factor of one-over-square-root-of-2 to normalize the state but it’s too hard to type in Word so I will leave it to you.) Now add another electron in the up state— |u). Also, in order to keep track of photons, lets indicate that there are no photons present with the notation |0}. The initial state is,

[ |ud-du> |u) ] |0}

Now let’s rearrange the symbols so as to group electrons 2 and 3 together. This is just a notational device. The initial state is

[ |u> |du) - |d>|uu) ] |0}

Now use the trivial identity

|du) = ½ |du-ud) + ½ |du+ud)

to rewrite it

[ |u> |du-ud) ] |0} + ½ [ |u> |du+ud) ] |0}

-[ |d>|uu) ] |0}


Now think of electron 2 and 3 as close one another, while electron 1 is off in the distance. In the first term 2-3 are in a singlet state. Nothing happens to it. In the other two terms the 2-3 system is orthogonal to the singlet. The 2-3 system will interact to emit a photon, and decay to the singlet in those cases, although the photons will be in different states in the two terms. Denoting the presence of the photon by |γ} and |γ’}, the final state will be

[ |u> |du-ud) ] |0} + ½ [ |u> |du-ud) ] |γ}

-[ |d>|du-ud)] |γ’} (note, there is missing sqrt2)

So what do we have in the end? A superposition of states in which the 2-3 system is in the singlet and

  1. electron 1 is up with no photon

  1. electron 1 is up with a photon in state |γ}

  1. electron 1 is down with a photon in state |γ’}.

If there is no photon or a photon in state |γ} then we know that electron 1 is up. If there is a photon in state |γ’} then e-1 must be down.

--

Having such a brilliantly and concise response was fantastic!

I've gone on to calculate the trivial equations to determine the probability in each state, as follows:

Given the probabilities of the 3 possibilities must add up to 1, taking the coefficients as lambda, the probability is given by lambda.lambda* which for real numbers is just lambda^2, so:

[ |u> |du-ud) ] |0} + ½ [ |u> |du-ud) ] |γ}
-[ |d>|du-ud)] |γ’} (note, there is missing sqrt2)

a. electron 1 is up with no photon


| 1 | 2
| ------------| = 1/4 = p1 = 0.25
| 2 sqrt(2) |

b. electron 1 is up with a photon in state |γ}

p2 = 0.25


c. electron 1 is down with a photon in state |γ’}.

| 1 | 2
| ------------| = 1/2 = p3 = 0.5
| sqrt(2) |


Google document:

http://docs.google.com/View?id=df4zskcg_25d8xtc9hp


The Stanford course "Modern Theoretical Physics - Fall 2006" by Leonard Susskind is available on iTunes-U (highly recommended!).


.

Basic Crib sheet for Mercurial hg

Mercurial (hg) is a distributed version control system, with many similarities to Subversion (svn). Being distributed, means people can work offline and still keep their version history local, merging changes with each other by exporting and importing the repository changes periodically.

Generally speaking mercurial is very simple and easy to use, but here are a few commands for quick reference:


Basic crib for Mecurial HG

Clone a repository from a web URL:

hg clone http://www.selenic.com/repo/hello my-hello

Clone from another local repository:

hg clone existing-repos clone-repos

Make a new repository:

hg init

Add files:

hg add

Committing changes:

hg commit (hg ci)

Pull changes from one repository to another:

hg pull

Note: this doesn't update the working directory, to do this update the working directory:

hg update (hg up)

Exporting and import:

hg export -o filename tip

hg import -o filename

Other common commands:

hg log
hg status (hg st)
hg diff
hg revert
hg (-q) tip


HG Editor, the editor for HG comments is determined in the following order:

HGEDITOR environment variable

editor configuration option in [ui] section (in hgrc or passed with --config ui.editor command-line option).

VISUAL environment variable

EDITOR environment variable

vi, if none of the above is set


References:

Mercurial home:

http://www.selenic.com/mercurial/wiki/Mercurial


Mecurial tutorial:

http://www.selenic.com/mercurial/wiki/Tutorial

Quick reference and cheat sheets:

http://www.selenic.com/mercurial/wiki/QuickReferenceCardsAndCheatSheets


.

Thursday, 4 June 2009

GlassFish v2.1 b60e crib sheet / installation notes

Recently, having been working on a project that's migrated from JBoss 4.2.2 to GlassFish v2.1, I needed to hand over a crib sheet / quick guide to people supporting the live system, so as it might be useful in general. Only really covering the basics, but here it is anyway:

GlassFish AS Basic Crib / notes:

Prerequisites:

  • Java JDK 6.x latest

GlassFish AS version V2.1 b60e Final Release

Download jar here http://java.net/download/javaee5/v2.1_branch/promoted/Linux/glassfish-installer-v2.1-b60e-linux.jar

For RHEL derived CentOS, recommended installation would be something like /usr/local/projectname/glassfish


Installation:

java -Xmx256m -jar glassfish-installer-v2.1-b60e-linux.jar

cd glassfish

chmod -R +x lib/ant/bin

lib/ant/bin/ant -f setup.xml

Follow the installer instructions, accepting EULA and any defaults presented...

This will unpack and install the server, creating a default domain called "domain1"

A domain is an administrative "unit" - possibly related to, but not the same as an actual domain.

All domains live in: {glassfish_home}/domains/

We need just one for now, so all our stuff will be in:

{glassfish_home}/domains/domain1/

the installation process will create a default empty domain, domain1 with a default config file, the main configuration file is called domain.xml

e.g. {glassfish_home}/domains/domain1/config.xml

This file may contain some host /installation specific information, as well as stuff specific to our application.


Starting and stopping GlassFish AS:

{glassfish_home}/bin/asadmin start-domain domain1

{glassfish_home}/bin/asadmin stop-domain domain1

If all is good you will see confirmation on the command prompt when started, such as:

Domain domain1 started


Managing GlassFish AS:

By default, the web based management console is available on port :4848

The default admin account is username = admin, password = adminadmin

URL is: http://{hostname}:4848


Web-app deployment options:

There are a few options, the main two are:

Manually, using autodeploy directory

Simply copy .war file to: {glassfish_home}/domains/domain1/autodeploy

Deploying via the admin console:

On main menu on left, click on and expand the Web Applications menu entry

Click on the Deploy button, typically when deploying from a local file, use the "Packaged file to be uploaded to the server" browse button to locate the local war file. Browse for the war file, select it and click Ok

When completed, the web app will appear in the application list (if all is well)

The other settings can be left as defaults. Optionally we can chose to pre-compile JSPs here etc.


Server Logs:

The main server logs appear in the domain under logs, i.e.

{glassfish_home}/domains/domain1/logs/server.log

Logs can also be viewed (and configured, including log rotation) via the admin console, under the Application Server menu entry


Monitoring and management:

JConsole:

GlassFish is a JMX compliant app server (listening by default to port 8686)

Using jconsole, remote connect to: http://{hostname}:8686

Using the same default account: admin/adminadmin

Admin console:

Under the Application Server in the main menu - there are entries for server Monitoring.

This includes a built in chart and call flow logging - which is potentially very useful for diagnostics and monitoring…


HTTPS / SSL:

GlassFish AS will do HTTPS out of the box (using a default Sun Microsystems certificate).

HTTPS is served by default on port :8181


Hopefully in the near future I'll but together something to cover clustering and load balancing too.



.

Wednesday, 3 June 2009

Super quick guide for creating self-signed certificates

Something I've done many times, but every time it's typically been so long in between that I've usually forgotten the specific details, so here is a super quick crib:

Create the private keys:


openssl genrsa -des3 -out server1.key 1024


Create a Certificate Signing Request (CSR):


openssl req -new -key server1.key -out server1.csr


Enter details, example below:


Country Name (2 letter code) [AU]:GB
State or Province Name (full name) [Some-State]:Kent
Locality Name (eg, city) []:Royal Tunbridge Wells
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Acme Co
Organizational Unit Name (eg, section) []:Financial Systems
Common Name (eg, YOUR name) []:www.myexactdomainname.com
Email Address []:louis.botterill@netbuilder.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:


Copy the passphrase protected key:


cp server1.key server1.key.org


Export the actual key without pass-phrase protection:


openssl rsa -in server1.key.org -out server1.key


Sign the CSR using the key to create a Certificate (.crt):


openssl x509 -req -days 365 -in server1.csr -signkey server1.key -out server1.crt


Easy huh! :)


.