Monday, January 21, 2008

Real-life Python

I just came home all tired and the minute I saw the place it hit me---I didn't
tidy up in ages. There were books everywhere, clothes all over the place, dirty
dishes... As I'm always tired when I come home from work, I never feel like cleaning
the place up. Somehow Python came up in my head as the solution to my problem (well,
not really a solution:) ). What if we could execute Python code in real life. I
mean, wouldn't it be great if we could do something like:


apartment.sort()
dishes.wash()

As I of course didn't feel like cleaning, I decided I'd better spend my time writing
about how I would use Python in real life. Beside cleaning the house, I think Python
could be of great help in the following problems as well.

Understanding women
Did you ever have a fight with your girlfirend/wife (it's a rhetorical question,
of course you did)? Did you ever wonder "What is going on in that mind of hers"?
Well, think about this one:

print girlfriend.__doc__

And if that didn't help, wouldn't it be great to be able to do something like

import dis
print dis.dis(girlfriend.think)

This would not only help you understand her, but also enable you to predict how
will she react. That's right, no more "What did I do wrong"---just look at the
code and you will know.

The answer to life
For all those in doubt as to whether they are wasting their life going to church
every Sunday, here's an ellegant Pythonic solution:

import time
if life.endswith(death):
while alive:
party()
time.sleep(12*60*60)
die()
else:
import random
religions = [christianity, islam, buddhism, hinduism]
myReligion = random.choice(religions)
for day in allDays:
if day != sunday:
be_humble()
else:
repent_sins(myReligion)
#no more days, end of time is here
go_to_heaven(myReligion)


What would you use Python for in real life?






Wednesday, January 9, 2008

How to insert watermark in LaTeX

For my first post this year, I'll start off with something a bit different. This time we'll take a look at how to insert a watermark in a document using LaTeX. Note here that by watermark I mean some text that will appear on the background of each page of the document.
As with everything else in the wonderful world of LaTeX, there are more ways to do this. I know of two, which I will write about here. The first one is fairly simple, just include the package draftcopy and voila. Here's a minimal example of how it works:


\documentclass{article}
\usepackage{draftcopy}

\title{Lorem ipsum}

\begin{document}
\maketitle

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

\end{document}


Running the previous example through LaTeX gives the following output:

Note that running pdflatex on this example will NOT insert the watermark. I use LaTeX->dvi->ps->pdf route to obtain the pdf.
Of course the draftcopy package gives a lot of options to customize the watermark, of which I believe \draftcopyName is the most useful. If you want the word ENTWURF to be printed instead of DRAFT, which is used by default, you would add the line "\draftcopyName{ENTWURF}{155}" in the preamble. The number 155 is the scaling factor for the font---play around with it to get the scaling you want.
For those that like to do it the hard way (like me:) ), here is a piece of code that does pretty much the same thing:

\AddToShipoutPicture{%
\setlength{\@tempdimb}{.5\paperwidth}%
\setlength{\@tempdimc}{.5\paperheight}%
\setlength{\unitlength}{1pt}%
\put(\strip@pt\@tempdimb,\strip@pt\@tempdimc){%
\makebox(600,-700){\rotatebox{45}{\textcolor[gray]{0.75}%
{\fontsize{6cm}{6cm}\selectfont{DRAFT}}}}%
}%
}

To use this code, you have to include the following packages: graphicx, eso-pic, and type1cm. Here is a minimal example:

\documentclass{article}

\usepackage{graphicx}
\usepackage{type1cm}
\usepackage{eso-pic}
\usepackage{color}

\makeatletter
\AddToShipoutPicture{%
\setlength{\@tempdimb}{.5\paperwidth}%
\setlength{\@tempdimc}{.5\paperheight}%
\setlength{\unitlength}{1pt}%
\put(\strip@pt\@tempdimb,\strip@pt\@tempdimc){%
\makebox(0,0){\rotatebox{45}{\textcolor[gray]{0.75}%
{\fontsize{6cm}{6cm}\selectfont{DRAFT}}}}%
}%
}
\makeatother

\title{Lorem ipsum}

\begin{document}
\maketitle

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

\end{document}

Be sure not to forget the \makeatletter and \makeatother commands. Unlike with draftcopy, running pdflatex on this example WILL insert the watermark in the pdf. I find this code nice because I can directly tinker with the various options. For example, if I want to change the angle of the text, I'll change the number inside the \rotatebox, if I want to move the text around the page, I'll change the two numbers inside \makebox, if I want to change the grayscale, I'll change the number inside \textcolor, etc.
UPDATE: The above code, as Ivijay pointed out, puts the word DRAFT on every page of the document. If you want it to appear on only one, you should use the
AddToShipoutPicture*
instead of
AddToShipoutPicture
. This command only adds the watermark to one page (first one if you leave the watermark code in your preamble).

UPDATE: Neno wants to know how to use a picture instead of text. Well, it's just a matter of replacing the lines

\makebox(0,0){\rotatebox{45}{\textcolor[gray]{0.75}%
{\fontsize{6cm}{6cm}\selectfont{DRAFT}}}}%

with something like

\includegraphics{image.eps}

Of course, you might have to play around with adjusting the width and height of the picture, depending on its size. Also, you might want to change tempdimb and tempdimc to properly position the image.

UPDATE: hcr suggests using draftwatermark package to do this sort of thing. I've just had a look at the package, and using it really seems simple. For most of the things I did here, there is a nice command that does that. However, some things are missing from the package. First, the color of the text is always grey (you can choose the grey scale, but can't have the watermark text in, say, red. There does not seem to be a way to change the typeface of the font for the watermark text, and the text is always centered, you can't move it around. And finally, there is no way you could insert a picture as a watermark (which is what Neno wanted to do), and IMHO this could be a big issue for many people who may want their company's logo as a watermark. So anyway, draftwatermark is a great choice if you just want to insert a word (centered) in the background of each page. If you need anything more sophisticated than that, you will have to do something in the line of what I described here.

UPDATE: Amy wants to know is there a way to put the watermark only on some pages, preferably using something like \begin{watermark} and \end{watermark}. Well, Amy, there is no easy solution to your problem. One thing you could do is use \AddToShipoutPicture* that places the watermark only on one page, and then paste the code wherever you need it. Of course, this is ugly. I have managed to hack together some solution that seems to work, but the code is really ugly and I don't advise anyone to use it unless you really need to :). So, here goes:

\documentclass{article}

\usepackage{graphicx}
\usepackage{type1cm}
\usepackage{eso-pic}
\usepackage{color}
\usepackage{everypage}

\newenvironment{water}{\AddEverypageHook{\waterb}}{\AddThispageHook{\waterb}\AddEverypageHook{\watere}}

\makeatletter
\newcommand{\waterb}{
\AddToShipoutPicture*{%
\setlength{\@tempdimb}{.5\paperwidth}%
\setlength{\@tempdimc}{.5\paperheight}%
\setlength{\unitlength}{1pt}%
\put(\strip@pt\@tempdimb,\strip@pt\@tempdimc){%
\makebox(0,0){\rotatebox{45}{\textcolor[gray]{0.75}%
{\fontsize{6cm}{6cm}\selectfont{DRAFT}}}}%
}%
}}
\makeatother

\makeatletter
\newcommand{\watere}{
\AddToShipoutPicture*{%
\setlength{\@tempdimb}{.5\paperwidth}%
\setlength{\@tempdimc}{.5\paperheight}%
\setlength{\unitlength}{1pt}%
\put(\strip@pt\@tempdimb,\strip@pt\@tempdimc){%
\makebox(0,0){\rotatebox{45}{\textcolor[gray]{1}%
{\fontsize{6cm}{6cm}\selectfont{DRAFT}}}}%
}%
}}
\makeatother

\title{Lorem ipsum}

\begin{document}

page one

\newpage

\begin{water}
First watermarked page
\newpage
Second watermarked page
\newpage
Third watermarked page
\end{water}

\newpage

This page should not be watermarked
\end{document}

Well, Amy, let me know if this works for you...





Monday, December 31, 2007

Naive fibonacci in pypy

As this is my last post this year, I'll just keep it short. I've been busy doing all sorts of things, so here's just a fast revisit to our old friend, the naive fibonacci algorithm, this time featuring Pypy. I downloaded the 1.0.0 version and ran the by now famous naive fibonacci. To get to the point, it took 184 seconds. Yep, you read it right---3 minutes. The same thing that took 27 seconds in CPython 2.5, or around 3 seconds using Psyco. Now, I didn't read much about pypy, but as I understand it, it should be faster than the CPython implementation... And AFAIK, the guys that made psyco abandoned that project to go work on bringing similar functionality to pypy. Now, I hate to bitch (no, no I don't:) ), but this really seems kinda slow. What's going on here? It's probably the function call overhead that slows it down. One should look at the code of pypy and see what exactly they put on the stack each time... The point being, I'll stick to CPython for a while more, at least until the naive fib runs under 20 seconds :) ('Cos what's more important in life than running a fast fibonacci algorithm?)
Happy holidays everyone





Saturday, December 22, 2007

Python 3000 - how mutable is immutable?

I just downloaded Py3k alpha 2 and decided to play with it a bit. Well, beside the print becoming a function, things seemed to be more or less the same as in 2.5. Then I decided to play with the more esoteric thingies in Python.
It has been long known that Python immutables aren't really immutable. For example, if you enter the following code in 2.5:


a = ([1], 2)
a[0] += [2]


you will get an error. However, printing a reveals that it has indeed been modified (a is now ([1, 2], 2)). Ok, so what happened to this little bug/hack/feature/gotcha/whatever-you-want-to-call-it in Py3k? Well, entering the code above also raises the same error, and again it actually modifies a. Now, I don't know is this "feature" is documented anywhere, but I really don't see any point in it being a part of the language (if someone can give me an example where it would be useful to have this kind of behavior, let me know). So, why is it still present in Py3k, when it's been known for a while now? I guess someone either thinks this is a good thing or they just forgot about it, either way---guys please change this, it's annoying me :) (and what better motivation to change the language than a rant by some guy on the Internet that you never met or heard of?)
But, the fun doesn't stop here kids! Try the following:


a = ({1:2}, 2)
a[0][2] = 3


This little piece of code gets executed without any problems, both in 2.5 and in Py3k. I wonder what is the rationale behind the fact that if we try to change a list (in place) that is part of a tuple, we get an error, while changing a dict happens silently. Ok, I do admit that doing


a = ([1], 2)
a[0].append(2)


also doesn't throw an error, but this only confuses me more. So, I'd like to know---are tuples mutable or immutable? Or better yet, how mutable are immutables?
As a final thought, consider the following code:


a = ({1:2}, 2)
a[0][2] = a
print a


In 2.5, this code will execute with no problems, and printing a will yield in
({1: 2, 2: ({...}, 2)}, 2)
thereby showing us that we have an infinite dictionary on our hands (or that's what I think these three dots stand for). However, doing the same thing in Py3k (i.e., running the above code and trying to print a---remember that in Py3k print is a function), we get

Traceback (most recent call last):
File "", line 1, in
TypeError: __repr__ returned non-string (type bytes)

Whoa! WTF?? What does this mean? What ever it means it tells me nothing about what is actually happening here. As far as I can see, there is something wrong with the __repr__ function---it isn't cut out to handle this kind of objects. So, the first thing that came to my mind was "Hey, cool, they won't print infinite dictionaries any more. They'll allow their construction, but when I try to print them, I'll get an error (a weird one, to say the least, but an error still). This kinda suxx, but ok, I guess I'll have to live with it." No. I was wrong. Try

print(a[0])

The infinite dict in the first position of the tuple prints with no problems. So, why is it a problem to print the tuple (which basically has one number, two parenthesis, and one comma extra)? No idea. Of course, trying to print a[0][3] yields an error, print a[0][3][0] goes without a problem, and so on. I guess that's why they call it alpha version :) I sincerely hope that this won't be a part of the language when a stable release of Py3k is out.