vendredi 28 mai 2010

Generating badges for upcoming seminar ;)

#!/usr/bin/env python

import sys
from csv import reader
from mako.template import Template

def help(script_name):
    print "Usage: %s <csv-file> <badge-template>" % script_name

def write_page(template, num, person):
    f = open('badges%05d.svg' % num, 'w')
    f.write(template.render(**person))
    f.close()

def process_file(csv_file, template_file):
    rows = reader(open(csv_file, "rb"))
    template = Template(filename=template_file)
    person_cnt = 0
    pages_cnt = 1
    person = dict()
    for row in rows:
        person['name%d' % person_cnt] = row[0].strip()
        person['surname%d' % person_cnt] = row[1].strip()
        person['organization%d' % person_cnt] = row[2].strip()
        person_cnt += 1
        if person_cnt == 4:
            write_page(template, pages_cnt, person)
            person_cnt = 0
            pages_cnt += 1
    if person_cnt != 0:
        write_page(template, pages_cnt, person)

if __name__ == '__main__':
    if len(sys.argv) < 3:
        help()
    else:
        process_file(sys.argv[1], sys.argv[2])

mardi 25 mai 2010

FOP & Jython

#!/usr/bin/env jython

import sys

from java.io import File, FileOutputStream, BufferedOutputStream

# JAXP
from javax.xml.transform import Transformer, TransformerFactory, Source, Result
from javax.xml.transform.stream import StreamSource
from javax.xml.transform.sax import SAXResult

# FOP
from org.apache.fop.apps import FOUserAgent, Fop, FopFactory, MimeConstants

xmlfile = File("projectteam.xml")
xsltfile = File("projectteam2fo.xsl")
pdffile = File("out.pdf")

fopFactory = FopFactory.newInstance()
foUserAgent = fopFactory.newFOUserAgent()

out = FileOutputStream(pdffile)
out = BufferedOutputStream(out)

fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out)
factory = TransformerFactory.newInstance()
transformer = factory.newTransformer(StreamSource(xsltfile))
transformer.setParameter("versionParam", "2.0");
src = StreamSource(xmlfile)
res = SAXResult(fop.getDefaultHandler())
transformer.transform(src, res)

out.close()

Quite funny, but there's the bug in Jython ClassLoader so we have to place all FOP jars in CLASSPATH instead of sys.path.append(...) way.

lundi 3 mai 2010

Project Euler #35

let is_prime n =
  if n < 0 then
    false
  else
    let lim = int_of_float (sqrt (float_of_int n)) in
    let rec check_mod i l =
      if i > l then
        true
      else
        if n mod i = 0 then
          false
        else
          true && (check_mod (succ i) l)
    in
    check_mod 2 lim;;

let primes n =
  let rec inner_primes i =
    if i > n then
      []
    else
      if is_prime i then
        [i] @ inner_primes (succ i)
      else
        inner_primes (succ i)
  in
  inner_primes 2;;

let circulations n = 
  let rec circulate str =
    let str_len = String.length str in
    if str_len = 1 then
      [int_of_string n]
    else
      let variant = (String.sub str 1 (str_len - 1)) ^ (String.sub str 0 1) in
      if variant = n then
        [(int_of_string variant)]
      else
        [(int_of_string variant)] @ (circulate variant)
  in
  circulate n;;

(*
let is_circular n primes = 
  let number_string = string_of_int n in
  let variants = circulations number_string in
  List.fold_left 
    (&&) 
    true 
    (List.map 
      (fun x -> List.exists (fun y -> (x = y)) primes) 
      variants);;
*)

let is_circular n =
  let number_string = string_of_int n in
  let variants = circulations number_string in
  List.fold_left (&&) true (List.map (is_prime) variants);;

let primes_till_1e6 = primes 1000000;;
let test_primes = primes_till_1e6;;

Printf.printf "%d\n" 
    (List.fold_left 
       (+) 
       0 
       (List.map 
         (fun x -> if (is_circular x) then 1 else 0 ) 
         test_primes));;
Strange thing: List.exists is quite slow, so when I switched from using List.exists (commented out) to just plain is_prime in is_circular it became possible to get result in a minute. Or maybe I just can't use List.exists properly.

samedi 1 mai 2010

Project Euler #27

#load "nums.cma"

open Big_int;;

type triple = { a: big_int; 
                b: big_int; 
                len: big_int };;

let is_prime n =
  if lt_big_int n zero_big_int then
    false
  else
    let lim = sqrt_big_int n in
    let rec check_mod i l =
      if gt_big_int i  l then
        true
      else
        if eq_big_int (mod_big_int n i) zero_big_int then
          false
        else
          true && (check_mod (succ_big_int i) l)
    in
    check_mod (big_int_of_int 2) lim;;
      
let primes n =
  let rec inner_primes i =
    if gt_big_int i n then
      []
    else
      if is_prime i then
        [i] @ inner_primes (succ_big_int i)
      else
        inner_primes (succ_big_int i)
  in
  inner_primes (big_int_of_int 2);;

let make_form a b = 
  fun n -> 
    add_big_int 
      (mult_big_int n n) 
      (add_big_int (mult_big_int a n) b);;

let sequence_length f =
  let rec advance_sequence n =
    if not (is_prime (f n)) then
      zero_big_int
    else
      add_big_int 
        unit_big_int (advance_sequence (succ_big_int n))
  in
  advance_sequence (big_int_of_int 0);;

let triple_max a b =
  if gt_big_int a.len b.len then
    a
  else
    b;;

let find_longest_sequence i1 i2 n =
  let rec make_lengths_list i =
    if gt_big_int i i2 then
      []
    else
      [{ a=i; b=n; len=sequence_length (make_form i n); }] @ 
      (make_lengths_list (succ_big_int i))
  in
  List.fold_left (triple_max) 
    { a=zero_big_int; b=zero_big_int; len=zero_big_int; } 
    (make_lengths_list i1);;

let bs = primes (big_int_of_int 1000);;
let a1 = big_int_of_string "-999";;
let a2 = big_int_of_string "999";;

let max_ab = List.fold_left (triple_max) 
    { a=zero_big_int; b=zero_big_int; len=zero_big_int; } 
    (List.map (find_longest_sequence a1 a2) bs);;

Printf.printf "%s\n" 
    (string_of_big_int (mult_big_int max_ab.a max_ab.b));;