Sunday, February 26, 2006

Some more things I love about Ruby

First of all, I love %w{ }. It is wonderful. When prototyping it makes me save lot of digits. I know it's a bit perlish (exspecially because you can also %w[ ] or %w/ /), but it is a great feature.
The %x{ } for commands (and ``). Yeah, perlish. But I needed it in some system automation scripts in Python. I know I could use subprocess... but sometimes I need something more stupid. I wrote a class for this (and you can find it in my blog).
Regexps... I'm a python fan... but I have to admit perl's syntax makes a lot of sense (and it is the one I have in sed or vim too, at least to some degree). Quite like that syntax in a cleaner environment.
Having the % operator on strings is good. It resembles me Python. I suppose it's a bit less powerful (I think it works only with lists, but since you can use #{} in ruby strings, the need for dictionaries is small). Moreover some of the most un-pythonic code I wrote is due to "creating" dictionaries. If you don't take care, you may find yourself with troubles. Of course even the #{} can be abused and so be source of problems.
<< on strings and arrays. I quite liked streams in C++. Yeah, not the same thing, but...
I'll write more later... (there are also things I don't like, but I should study more to fully understand them).

Thursday, February 23, 2006

Ruby vs. Python? [no, Ruby vs. Ruby ]

In fact this is not a Ruby vs. Python list. I know not enought Ruby and I love Python to much :). It's more a picture of the first impressions I had on Ruby after I seriously began studying it.

This is a quick list of thoughts. I'm probably adding more stuff later. In fact I'm reaaly amazed. Ruby is really hackish, but it's also neat and clean. It may sound strange... but I'm afraid I'm gonna love ruby more than Python: it addresses many of the things I come to dislike in Python.

[from the future: this did not happen...; kind of a summer love, back then]

Some stuff I like

  • Adding dynamically stuff to classes. The syntax is clean and obvious:
    class MyClass
      def aMethod
        puts "Called aMethod"
      end
    end
    
    m = MyClass.new
    
    begin
      m.aMethod2
    rescue NoMethodError => ex
      puts "Failed to call #{ex}"
    end
    
    class MyClass
      def aMethod2
          puts "Called aMethod2"
      end
    end
    
    [from the future: I actually hate this right now. Monkey patching is dangerous.
    I believe that having the nice syntax actually encourages a messy practice.
    I have seen too many ruby plugins/libraries fight because of this crap.]
  • m.aMethod2 In Python for example it is not that clean. The ruby code looks more like ObjectiveC categories (even if in fact you don't specify a category, of course, since ruby does not need categories).
  • private, protected, public modifiers. Being dynamic they do not limit me in any way (if I need I can dynamically change this)
    class MyClass
      protected
      def aMethod
        puts "Called aMethod"
      end
    end
    
    m = MyClass.new
    
    begin
      m.aMethod
    rescue NoMethodError => ex
      puts "Failed to call #{ex}"
    end
    
    class MyClass
      public :aMethod
    end
    
    [from the future: I don't really believe they are useful as long as you can
    change them dynamically. They are, by definition, not harmful as well.
    I wouldn't make a war if Python adds decorators to do this stuff. I wouldn't
    be pleased either]
  • m.aMethod Moreover I can't think to a cleaner syntax to do this. Of course one can argue that they aren't really necessary. Of course, but if you want they do give you a little bit of control, but they don't limit you in any way.
  • Object#freeze: if you suspect that some unknown portion of code is setting a variable to a bogus value, try freezing the variable. The culprit will then be caught during the attempt to modify the variable. I believe correct unit-testing makes this sort of debugging mostly useless.
  • I love postfixed control clauses. In fact if used with moderation they can augment code readbility (and of course if abused they make it less readable). However, it is pretty logigal to say do_something if something_else. In fact since ruby has blocks it is ok also to write:
    begin
        # some stuff
    end if condition
    
    maybe not everyone agrees
  • Accessors are great. Using attr and similar constructs is great. I also find quite more readable to "assign" with foo= than using more Javesque setFoo(val). In fact properties in Python work in a similar fashion, even if maybe a bit more verbose (however, I think they make it clearer how to document code, but this is a ruby aspect I've not yet exploited)
  • Gems: I think python needs something like that. Pimp is not that good, in my opinion, of course.

Stuff I don't know if I like or not

  • Not having to write parentheses with no-argument methods. I've not yet discovered if I like it or not.
  • All the $_... They are used a lot in Perl. I like it, but I'm afraid it can mess things up.

Stuff I dislike

  • I don't like passing strings to require. In fact it can have advantages, but I prefer the pythonic import foo to require "foo".
  • The try catch semantic of try/catch, makes me think to some kind of disguised goto. I'm sure I'm wrong... but
  • I'd like to have something like Perl use strict;. It's something I miss in Python (even if with pychecker you can just live without it). Now I've got to find some kind of "use strict" or "rubycheck".
  • Assignment is an expression. This directly leads to code like:
    a = true
    b = false
    print b if b=a
    
    and we imagine the programmer wanted to write:
    a = true
    b = false
    print b if b==a
    

  • However in Ruby almost everything is an expression, and it has quite a lot of advantages. So we have to tolerate the "=" for "==" problem.

get_sublist in prolog

The hardest thing when programming prolog, is to change your mind.
In fact declarative programming (while powerful) is hard to get in touch.
I always tend to think imperatively, even if I attended formal logic lessons in the University.
Now just a couple of easy things... I'm a beginner.

get_sublist(Start, Len, List, Sub) :- 
    append(L1, L2, List), 
    length(L1, Start), 
    append(Sub, _, L2), 
    length(Sub, Len).

This way you get a sublist. The style is declarative.
The efficience is .... well we ll'see later.

An "imperative" version is:
get_sublist(_, 0, _, []).
get_sublist(Start, Len, List, [H | Acc]) :- 
    nth0(Start, List, H), 
    succ(Start, NStart), succ(NLen, Len), 
    get_sublist(NStart, NLen, List, Acc). 

It's not as clean, but should be more efficient. It uses an accumulator variable.
In fact this algorithm is not really declarative.
We could say that it does the same thing than

def get_sublist(start, len, list, acc) 
    if len > 0 
        acc.push list[start] 
        nstart = start + 1 
        nlen = len - 1 
        get_sublist(nstart, nlen, list, acc) 
    end 
end 

Incidentally this is ruby code, you can test it with

l = [] 
get_sublist(2, 3, %w{ a b c d e f g}, l) 
l.each { |e| puts e} 

And now... lets see if we optimized or not.
This is comes from SWIProlog.

5 ?- time(get_sublist(2, 3, [a, b, c, d, e, f], Acc)). 
% 22 inferences, 0.00 CPU in 0.00 seconds (0% CPU, Infinite Lips) 
Acc = [c, d, e] 
Yes 
6 ?- time(get_sublist_old(2, 3, [a, b, c, d, e, f], Acc)). 
% 37 inferences, 0.00 CPU in 0.00 seconds (0% CPU, Infinite Lips) 
Acc = [c, d, e] 
Let's try with bigger numbers... 
24 ?- make_list(100000, L), time(get_sublist(2000, 500, L, Acc)). 
% 378,001 inferences, 0.33 CPU in 0.42 seconds (78% CPU, 1145458 Lips) 
L = [100000, 99999, 99998, 99997, 99996, 99995, 99994, 99993, 99992|...] 
Acc = [98000, 97999, 97998, 97997, 97996, 97995, 97994, 97993, 97992|...] 
Yes 
25 ?- make_list(100000, L), time(get_sublist_old(2000, 500, L, Acc)). 
% 15,007 inferences, 0.08 CPU in 0.09 seconds (87% CPU, 187587 Lips) 
L = [100000, 99999, 99998, 99997, 99996, 99995, 99994, 99993, 99992|...] 
Acc = [98000, 97999, 97998, 97997, 97996, 97995, 97994, 97993, 97992|...] 
Yes 
26 ?- make_list(100000, L), time(get_sublist_old(2000, 5000, L, Acc)). 
% 42,007 inferences, 0.56 CPU in 0.66 seconds (85% CPU, 75013 Lips) 
L = [100000, 99999, 99998, 99997, 99996, 99995, 99994, 99993, 99992|...] 
Acc = [98000, 97999, 97998, 97997, 97996, 97995, 97994, 97993, 97992|...] 
Yes 
27 ?- make_list(100000, L), time(get_sublist(2000, 5000, L, Acc)). 
% 7,530,001 inferences, 6.88 CPU in 8.82 seconds (78% CPU, 1094477 Lips) 
L = [100000, 99999, 99998, 99997, 99996, 99995, 99994, 99993, 99992|...] 
Acc = [98000, 97999, 97998, 97997, 97996, 97995, 97994, 97993, 97992|...] 
Yes 

It looks like we didn't optimize very much. :(
I should study more.

Window Shade X

Credo di non avere mai decantato pubblicamente questo piccolo software. Lo registrai per la modica cifra di 10 $ (molto moderate. Quando un programma è buono e mi piace, lo compro, anche se è commerciale [ posto che me lo possa permettere ]. Questo è ancora più valido se si tratta di software di piccole case o singoli sviluppatori che mettono passione nel loro lavoro.

È il caso di TextMate di Allan Odgaard e di BBEdit (questa per esempio è una media software house che si dedica da anni a sviluppare ottimo software per Mac). È il caso di Yojimbo, sempre di BareBones (questo lo sto ancora valutando nei 30 giorni di prova). È il caso di GraphicConverter, che ho usato a sorti alterne credo fin dalla versione 1 sui miei vecchissimi Mac (e adesso uso in quanto la licenza viene pagata da Apple se acquisto un Mac di fascia "pro"). È il caso di MacSOUP (anche se ultimamente mi sto stancando di quanto poco sia "aquoso", d'altra parte è uno di quei programmi che la licenza la paghi una volta e poi lo usi sempre).

Beh... fra questi ottimi software ci sono anche un paio di utility di Unsanity. Mi riferisco in particolar modo a FruitMenu e a WindowShade X. Dei due quello che uso più di frequente è senza dubbio il secondo. Altre utility interessanti di Unsanity sono ShapeShifter per cambiare il tema al MacOS e MenuMaster che sto valutando.

Window Shade X

Una delle cose che meno tollero di MacOS X è il dock. Lo trovo una brillante idea terribilmente sprecata. Al di la di ovvi problemi di coerenza di interfaccia (ad esempio al di la del separatore ci stanno finestre minimizzate, documenti, cartelle e cestino, mentre a mio avviso almeno le finestre dovrebbero essere da un'altra parte). Dicevo, le finestre da un'altra parte anche per ragioni di spazio.

Se si minimizzano molte finestre il dock si allunga e diviene quasi ingestibile. Questo problema viene risolto brillantemente da WindowShade X. Infatti permette di "minimizzare le finestre sul desktop: cosa intendo? Guardate l'immagine.

windowshade1.thumbnail-2006-02-23-18-52.png

In questo modo posso facilmente minimizzare le finestre (posso anche spostarle sul desktop come fossero icone). Per esempio posso "rebindare" il pulsantino giallo per fare questo e continuare a minimizzare sul dock con Mela-M.

Per chi se lo stesse chiedendo... si, la minimizzazione sul desktop è simile a quello che fanno alcuni window manger sotto X11, per esempio twm [ ovviamente in modo oltremodo più raffinato, come si può vedere dall'immagine ] oppure il mio amatissimo WindowMaker. Triste che oggi ci si sia tutti o quasi omologati su sistemi molto più pesanti anche su GNU/Linux (senza nulla togliere a GNOME e KDE, solo meno  "originali", per come la vedo io).

Un'altra funzione davvero comoda (la maggior parte delle volte uso questa) è minimizzare una finestra alla sua barra del titolo facendo doppioclick sulla stessa. Questo c'era in MacOS 9 e Apple lo ha (stupidamente?) tolto in MacOS X. È qualcosa presente anche su molti wmanager per X11, metacity per citarne uno.

Il tutto coopera perfettamente con Exposè e rende lavorare con molte finestre davvero comodo.

Altre funzioni sono quelle di fare diventare trasparente una finestra oppure di renderla "floating" sopra tutto il resto (per esempio una chat, un player audio minimizzato, boh). Insomma... davvero geniale WindowShade X.

Stattoo

Stattoo è una piccola utility fatta da Panic. Uno dei più celebri prodotti di Panic è Transmit, a detta di molti il miglior client FTP per Mac (io personalmente sono affezionato a Fetch, che come studente posso avere in licenza gratuita e che ho usato fin dalla versione 1.x nei primi anni '90, ma i meriti di Transmit sono indubbi).
Un'altra applicazione di Panic è Unison, ottimo newsreader per gruppi binari (per i le discussioni francamente lo trovo abbastanza povero, ma si stanno attrezzando). Ad ogni modo, ora è il turno di "Stattoo". Il prezzo è 12.9 $. L'applicativo stampa sul desktop alcune informazioni con una bella veste grafica.
stattoo-2006-02-23-18-52.jpg
Per ora sono disponibili:
  1. Ora
  2. Data
  3. Appuntamenti di iCal
  4. Ultime Mail di Mail o di un qualunque account pop/imap anche non specificato in Mail
  5. Lo stato di iTunes
  6. Lista degli ultimi software arrivati su VersionTracker
  7. Spazio occupato sui vari dischi
  8. Temperatura locale
  9. Stato della batteria
La maggior parte di queste features sono ottenibili in altro modo. Spesso con dei widget o dei programmi. Tuttavia Stattoo è molto più veloce di Dashboard e cerco di tenerci quanta più roba possibile.
Varrebbe la pena di comprarlo anche solo per i punti 3 e 4. E anche la batteria è comodissima. Inoltre si può "sollevare" Statoo in trasparenza sopra le altre finestre schiacciando un tasto.
stattoo2-2006-02-23-18-52.jpg
La cosa che però mi ha fatto decidere definitivamente per l'acquisto è stata la professionalità. Ho inviato una email facendo presente che per la mia città (Parma) non era disponibile un codice areoportuale ICAO (per le città non-USA viene usato questo per identificarle) e quindi non potevo usare il modulo "Weather".
In effetti non è che la mia città non avesse un codice ICAO, solo il sito da Panic consigliato per scoprire tali codici presentava solo il codice IATA (un'altra sigla, poco importa cosa siano effettivamente). Ho mandato una email per chiedere consigli, dicevo.
Un gentilissimo dipendente (o forse proprietario o programmatore) mi ha risposto dicendomi il codice ICAO della mia città. Ovviamente funziona tutto. Immagino che in caso di problemi (all'epoca non ero ancora registrato) siano altrettanto celeri. E questo deve essere il valore aggiunto delle piccole case software: idee, ben realizzate e rapporto "umano" con il cliente.

Ruby 0.0

Today I decided to take some time and have a look at Ruby. I found online a version of Programming Ruby and started reading it. In fact I knew I was going to like Ruby. In fact the first time I took contact with it I quite liked it, even if I didn't fully exploit its capabilities.

Well... let's see how it goes. Right at the moment the first thing I wrote is:

class Employee
    attr_reader :wage, :name
    attr_writer :wage
    def initialize(name, surname, wage)
        @name = name
        @surname = surname
        @wage = wage
    end
    def surname
        @surname
    end
    def to_s  
        "#{name} #{surname} (#{wage})"
    end
    protected :wage=
end

class Manager > Employee
    def initialize(name, surname, wage, employees=[])
        super(name, surname, wage)
        @employees = employees
    end
    def setWage(emp, wage)
        emp.wage = wage
        emp
    end
    def to_s
        super + @employees.collect{|e| "\n  #{e}"}.join("")
    end
end
mr = Employee.new("Jack", "Bravo", "1000€")
mc = Employee.new("Michael", "Charlie", "300€")
mngr = Manager.new("Angus", "Smith", "10000€", [mr, mc])
mngr.setWage(mc, "700€")
puts mngr

This post has been recently re-edit to test SyntaxHighliter.
Moreover, I want to stress that the design would be terrible.

People are *not* Employees or Managers. Their *role* is Employee or Manager.
This is a case when favouring inheritance over composition? is wrong.
More on this later!

Ruby arrays and matrices

One of the first things you learn when reading a book on Ruby is that "variables" hold references to objects. Consider
a = Foo.newb = a
Both a and b contain the same instance of the object. Fine. Simple. Java does the same and so does Python. You just know what that means and you know that if you want a copy instead (that is to say b and a should change indipendently) you must dup or clone them.
a = Foo.newb = a.dup
Now it comes to arrays. Ruby arrays are much like Python list. They are powerful objects. And have something Python lists do not have, some more constructor. From the ruby doc:
Array::newArray.new(size=0, obj=nil)Array.new(array)Array.new(size) {|index| block }
Returns a new array. In the first form, the new array is empty. In the second it is created with size copies of obj (that is, size references to the same obj). The third form creates a copy of the array passed as a parameter (the array is generated by calling to_ary on the parameter). In the last form, an array of the given size is created. Each element in this array is calculated by passing the element's index to the given block and storing the return value.
We analyze the very first constructor. It makes perfectly sense: consider this:
l = Array.new(5, "") # ["", "", "", "", ""]
l[1] ="foo"
l # ["", "foo", "", "", ""]
Now consider this:
l = Array.new(5, []) # [[], [], [], [], []]
els = %w{ el1 el2 el3 el4 el5 }
l.each_index { | index | l[index].push els[index] }
# [
# ["el1", "el2", "el3", "el4", "el5"],
# ["el1", "el2", "el3", "el4", "el5"],
# ["el1", "el2", "el3", "el4", "el5"],
# ["el1", "el2", "el3", "el4", "el5"],
# ["el1", "el2", "el3", "el4", "el5"]
# ]
This is the correct result. But this probably is not what we wanted to obtain. The "correct way to initialize l" would have been
l = Array.new(5) { | dummy | Array.new } # [[], [], [], [], []]
els = %w{ el1 el2 el3 el4 el5 }
l.each_index {| index | l[index].push els[index] }
# [["el1"], ["el2"], ["el3"], ["el4"], ["el5"]]
This time for each line we are creating a "new" empty list, not the very same one.
In this case you probably should have been using the Matrix class, anyway.

Opera 9 (preview)

La prima cosa che salta all'occhio è la nuova interfaccia. Più browser e meno "pacchetto integrato". Di default ci viene mostrato solo il minimo indispensabile come si vede nello screen
toolbaropera-2006-02-23-18-51.png
Le classiche toolbar sono comunque tutte accessibili attraverso il solito Menu.
La prima cosa che faremo sarà caricare una pagina. Qui rimarremo sorpresi. La velocità è impressionante (sicuramente la velocità percepita). Anche il resto del programma rimane decisamente reattivo.
Alcuni binding sono cambiati (per esempio adesso per aprire un nuovo tab possiamo usare Mela-T/Ctrl-T come su Firefox e Safari, mentre prima, se la memoria non mi inganna, era Mela-Option-N, con eventualmente sostituito Mela da Ctrl se sotto X11 o Windows).
I bookmark sono stati importati in un batter d'occhio. Bene. Per posta e altro non mi esprimo, non sono funzioni che uso, preferendo di gran lunga programmi apposta, come Apple Mail e NetNewswire -- newsfeed --).
Il problema più grosso temo sia *esportare* i bookmark. Passare da un altro browser ad Opera è facile, non altrettanto facile il contrario, purtroppo. L'ultima volta lo feci attraverso un servizio web esterno (questo) . Tale sito fra le varie cose offre un convertitore di file di bookmarks da e per moltissimi programmi diversi.
AJAX pare funzionare bene (a parte un problemuccio su Wordpress, qui, sulle immagini, ma cose "complesse" come per esempio l'editor di post WYSIWYG in javascript avanzato funziona decisamente bene).
Ribadisco... veloce, interessante. Vediamo Google cosa inventerà, perchè per adesso Opera 9 sembra una versione riveduta e corretta di Opera 8, ma non offre davvero quanto Firefox, ne è integrato come Safari.
Comunque da tenere sott'occhio senza dubbio.

About learning Cocoa

I first learnt about ObjectiveC and Open/GNUStep when I was basically a Linux user. That was quite a lot of time ago. I was a WindowMaker fan, and that was the way I learnt about GNUStep. However, I did not learn ObjectiveC nor GNUStep programming. In fact there was plenty of "wonderful" languages out there and I felt no need for another one. The few GUI applications I did were made with GTK1 and C (yes, GTK 2 did not exist yet and wx was not really widespread; the first time I installed Audacity on Slackware 8.1 I had to google for them) or Qt with C++.I was quite skeptical with interpreted languages too: I knew a bit of Lisp (more for academic reasons than for "real programming" -- that is to say I would not be able to write a piece of useful software; well, this isn't changed, anyway) and quite a lot of Perl (still I did not use to do what I considered "serious work": a few cgi and some system scripting). But I'm going off topic.

One day one of my friends showed me the Powerbook G4 and MacOS X (it was Jaguar, for those who care). After some time I bought my first Mac with MacOS X. Before being a Linux user I was a big fan of MacOS Classic (and the first machine I installed GNU/Linux on was an iMac), so I was really happy with the "new deal" of Apple. Still I planned to "install GNU/Linux as soon as possible". In fact this never happened (but one of this days when I have time and airport support is stable enough...).The first thing I did was to learn Objective C. I took a look at Carbon, but I wasn't amazed. I read Apple's guides about the language. They were clear and well done. Still to code GUI applications I needed a more detailed book (I'm kind of a perfectionist) since the Tutorial, although well done, is designed for absolute beginners. Anyway the Apple guide for the language ObjectiveC is here.

I still have no idea why I chose to learn it. In fact I was a "cross-platform gui". I still thought I would use both systems, so having my own applications on both of them was probably quite desirable. Moreover the QT MacOS port was young (it was released a couple of months after I bought the Mac, IIRC).In the same period I was learning Python too, and almost everything else (system tools, web sites, cross platform gui applications with awful Tk) was made with it. I found some similarities between the two languages (in fact I think they were more similarities between Python and Smalltalk, and only indirectly between Python and ObjectiveC). Still one thing was different. Python is a very high level language, but does not force you in anyway into some kind of framework.

In fact you can perfectly "translate" command line from C using the same POSIX APIs or, for example, "convert" a Qt + C++ program. The language Objective C in fact has the same properties. In fact I wrote a few command line utilities and found that the Foundation kit was a well designed environment that abstracted some POSIX interfaces. I quite liked it. And quite liked ObjectiveC.

The only thing I truly missed were namespaces (or analogue things). I spend a couple of days understanding the memory model and that was everything. I bought two books, "Cocoa in a Nutshell" (today I would not buy this) and "Cocoa Programming" by Anguish Buck and Yacktman. They were both good books. I do not use the Nutshell because Apple documentation is more recent today, not because it's not well done."Cocoa Programming" is a "big" book. There are lots of infos. Some of them are advanced topics (for example there are Chapters about optimizations -- you know, optimization hinders evolutions, but we want to run our software on something more portable than a mainframe).

The book focuses on how Cocoa was thought with Design Patterns (expecially those from the famous book), even if they change their name (and Anguish/Buck/Yacktman show which Cocoa pattern corresponds to a GOF pattern). I was already acquainted with DP, I read the "Design Patterns: EORSD" some time ago (and recently I bought the book and I'm reading it again). In fact Cocoa developing needs understanding of design patterns, but you can have a less theoretical approach to Cocoa.

I recently read Hillegass's "Cocoa Programming for MacOS X" and that is what I mean. It's more like a tutorial, but not as elementar as Apple one. It shows you some "real life" small applications that use key tecnologies. It shows Cocoa structure, main "patterns" (for example how to deal with a NSTableView -- and introduces the concept of delegation).While "Cocoa Programming" shows how much Cocoa can be powerful, Hillegass shows how much Cocoa is easy. There are many things that are not explained in the latter (even if it covers some topics I didn't find in the other book).

You may need (you probably need) a book like Anguish/Buck/Yacktman's "Cocoa Programming", but I strongly advise to start with "Cocoa Programming for MacOS X". It's not recent, but it's well done and complete. You can build a whole lot of applications reading it, and for example explains the Document Based Applications in a very simple yet complete way (for example in "Cocoa Programming" the authors implement classes that act quite like the NSDocument and friends to show you in details how it works, still I was not really able to understand how easy it is programming Doc-based apps with Cocoa; in fact I thought it was hard, since many explanation about how the "true" class works are embedded in the explanation of how to rewrite a subset of it.Another reason for reading "Cocoa Programming for MacOS X" is its length. Much shorter than the other one, you can read it in less than a week, and dive into programming with more skills. Some useful subjects in "Cocoa Programming" are not at the beginning and you must already know you have to skip chapters and go and read them.In fact I find the two books complement each other well. I've got a third book (well a fourth), but I'm not gonna speak about it this time.

  1. "Cocoa Programming" - Anguish/Buck/Yacktman
  2. "Cocoa Programming" for MacOS X" - Hillegass

Wonderful Terminal...

I just love it. Yeah... an old screen on my Mac.
http://ldopa.net/2006/01/14/glterminal/

Execute class: $(command) in python

Although you can easily do with module subprocess what I do with the following class:
  • If you have Python 2.3 you may not have subprocess
  • This class is much simpler than subprocess: it does just one thing.
  • You may want to pipe two commands in a fancier way
I wrote this because I needed to use Python to do some system automation and I needed something that acted like Perl and bash `` (in bash 2 you are supposed to do $(command) instead of `command` but it's syntactical sugar).
In my strive to be compatible with standard MacOS system (that uses 2.3 by default) I forgot it existed module subprocess. So I wrote this simple class.
Even if in production you may prefer to use subprocess you can consider this an example of streams in Python. This is a very simple example. If you want to really pipe two processes, use module subprocess. If you want to make streams in a C++ fashion you can take inspiration by this code, but you may want to do it line based (but this ain't no problem, in fact we are using properties, so you can do whatever you want with them -- an example later).
Stream acts like a Mixin (thanks Dialtone!). It defines __rshift__ and __lshift__ (that become >> and <<

class Stream(object):
    def __rshift__(self, rho):
        if isinstance(rho, Stream):
            rho.input = self.out
            return rho
        else:
            raise TypeError()

    def __lshift__(self, rho):
        if isinstance(rho, Stream):
            self.input = rho.out
            return self
        else: raise TypeError()

Remember: classes that subclass Stream must have an attribute named out and one named input. If you need something more complex, use properties to implicitly call functions every-time you access out or in. For example since I use lazy evaluation I do:
input = property(fset=set_input, fget=get_input)
out = property(fget=get_out)
err = property(fget=get_err)

Now have a look at the whole code:
import os

class Stream(object):
    def __rshift__(self, rho):
        if isinstance(rho, Stream):
            rho.input = self.out
            return rho
        else:
            raise TypeError()

    def __lshift__(self, rho):
        if isinstance(rho, Stream):
            self.input = rho.out
            return self
        else: raise TypeError()

class Execute(Stream):
    def __init__(self, command, *kargs, **prefs):
        self._commandString = ' '.join((command,) + kargs)
        self.has_run = False

    def _lazy_run(self):
        if self.has_run: 
            return
        self.has_run = True
        (self.sin, self.sout, self.serr) = os.popen3(self._commandString)
        self.sin.write(self.input)
        self.sin.close()
        self.out_list = list([line.strip() for line in self.sout])
        self.err_list = list([line.strip() for line in self.serr])

    def run(self):
        self._lazy_run()
        return self

    def _make_string(self, which):
        self._lazy_run()
        if hasattr(self, "%s_string" % which):
            return
        setattr(self, "%s_string" % which,
                '\n'.join(getattr(self, "%s_list"% which)))

    def set_input(self, s):
        if hasattr(self, "input"):
            self.input_ = "%s%s" % (self.input, str(s))
        else:
            self.input_ = str(s)

    def get_input(self):
        try:
            return self.input_
        except AttributeError:
            return ""

    def get_out(self):
        self._make_string("out")
        return self.out_string

    def get_err(self):
        self._make_string("err")
        return self.err_string


If you need to do different things, redefine (get|set)_(out|input|err).

List user defaults in MacOS X

The small script below uses PyObjC (it was born as a snippet in ipython to have a quick check to a pair of variables). Of course you can write the very same thing in ObjectiveC.

I strongly encourage to install PyObjC and ipython even if you do work with Cocoa and ObjectiveC, since you can use that to prototype your application and to test snippets of code.

#!/usr/bin/python

# -*- coding: utf-8 -*-

import sys

import Foundation

ud = Foundation.NSUserDefaults.standardUserDefaults()

d = ud.dictionaryRepresentation()

for k in d:

sys.stdout.write(k)

sys.stdout.write(":\t")

try:

print d[k]

except UnicodeEncodeError, e:

print d[k].encode('utf-8')

To have more information on PyObjC (that is to say Cocoa bindings for Python), go here.

You can find ipythonhere. ipython in an improved interactive shell, with powerful introspection capabilities. Since MacOS X Python by default comes with no support for readline, I advise to install the missing module for Python 2.3 (search google, I don't remember right now where to find it) or better install this version of Python 2.4, complete with the patch (on the same page).Of course you must set your path so that the "first" python is the new one (if you set PYTHON_ROOT and such, you must also fix them).

Remember when you "python setup.py install" a module (that is the typical command line to install a python package), it is installed for the python version called by default (find it out with which pyhon)

TextMate: the definitive editor?

Unfortunately it appears I've no time to talk about programming. It takes lot of time to think about something useful, to write examples and such. However, I promise I will doing it soon.

And yet I'm again talking about a text editor. In fact since most of my computer time is spent on an editor, this makes sense. It's the most crucial application to me (and the one I spend most time to learn using its full power).

I already said I discovered TextMate. The more I study the more I'm amazed. In fact it did substitute Aquamacs even for latex editing. The new bundle is perfectly integrated with Texniscope and "Command-B" opens in TextMate the pdf document compiled from the document I'm editing. That makes environment such that TexShop almost useless to me.

Emacs is more powerful. But most of the times I'm not using that power. It's my fault, of course. Still TextMate is always open on my Mac, and I started using it even for latex. That's the main reason. If I have to do a very long latex editing session I still do prefer Aquamacs.

The Python mode is now wonderful. It lets me check my sources with pychecker or with pyflakes. It allows me to run them from inside TextMate, lets me run unit-tests with one command. And even more. Right at the moment it's the best python programming environment I've ever met (a part from WingIDE).

The only thing I'm missing right now is a "prolog mode". And probably I have to work on TextMate/Xcode integration (it has been done, but I haven't done it yet). Oh, and I'm looking forward to see TextMate 2, that should have massive improvements on the "project management" side. And probably I'd like some more refined auto-completion with static languages. This could have somehow been added (TextMate can be extended and customized a lot, still in a really simple way), but I've not yet discovered if and how.

But the reason I wrote this is another. For years the "Text editors" with capital T have been Emacs and vim. BBEdit was a beautiful Mac editor, but first it is very web-oriented, second it is somehow less powerful in the way it deals with text.

On the windows platform I have not found really impressive text editors. There are a bunch that are powerful and easy to use. But in fact I installed vim (gvim) and I was happy with that. Most such editors were more concerned in "integrating" command line utilities (compilers, latex, interpreters) with the editor not to have the "programmer" opening the "DOS console" than pure text editing.

Newer editor for Linux (Kate for example) also paled in comparison with Emacs or vim. Now I'm wondering:

  1. Was I superficial? It is possible that no one did something that could be compared with vim or Emacs before TextMate? This seems really unlikely.
  2. Why haven't I spotted such editors? They exist? Let me know. I'm talking about "pure text editors", not about "IDEs".

Emacs bindings in Cocoa?

Key

Meaning

ctrl-q

Beeps. If pressed twice deletes selection.

ctrl-w

Cuts text

ctrl-e

Moves to end of line

ctrl-r

Beeps??

ctrl-t

Swaps near characters

ctrl-y

Pastes text

ctrl-u

Beeps??

ctrl-i

Beeps??

ctrl-o

Insert new line after current

ctrl-p

Moves cursor to previous line

ctrl-a

Moves to beginning of line

ctrl-s

Beeps??

ctrl-d

Deletes character on the right

ctrl-f

Moves forward one character

ctrl-g

Beeps??

ctrl-h

Deletes character on the left

ctrl-j

Beeps??

ctrl-k

Cuts line from cursor to the end

ctrl-l

Does nothing?

ctrl-z

Beeps??

ctrl-x

Beeps??

ctrl-c

Beeps??

ctrl-v

Moves half screen down

ctrl-b

Moves backward one character

ctrl-n

Moves cursor to next line

ctrl-m

Beeps??

GeekTool CPU Script

If you don't know what GeekTool is go here.It is very likely you'll find it useful. If you use Tiger, use this version that fixes a lot of issues.
GeekTool allows you to put a lot of interesting informations on the desktop. You can "print" logfiles on the desktop or you can put there pictures or, and that is what is interesting, put the output of a chosen command.For example I put a random fortune on the desktop. It easier to do download GeekTool and do it than reading an explanation.
An interesting feature that is in the documentation (so it's something you probably wouldn't read) is that scripts/commands placed in "~/Library/Application Support/GeekTool Scripts" need not to be specified with full path. So we will put the script "cpuload.py" in that directory and we will refer to it with "cpuload.py"
And now the script:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
class command(object):
def __init__(self, c):
self._command = c
fi, foe = os.popen4(self._command)
fi.close()
self.out = list([line.strip() for line in foe])
foe.close()
def cpu_load(string_list):
# a bit functional... not pythonic at all
return sum(map(lambda l: float(l.split()[2]),
string_list), 0)
def main():
ulist = command("ps -ux").out[1:]
slist = command("ps -aux").out[1:]
print "System CPU: ", cpu_load(slist), "%"
print "User CPU: ", cpu_load(ulist), "%"
if __name__ == "__main__":
main()
Class "command" is a stripped down version of a class I'm writing for another project. I also think that any script you write should be executable.

Tunatic (Italian)

Tunatic è un piccolo software non intrusivo che identifica le canzoni. Prende il suo output dal microfono e attraverso un database online le confronta con quelle che ha in memoria. I risultati sono sorprendentemente buoni.
Ho sottoposto canzoni di diverso genere musicale, e spesso le canzoni (tipicamente rock) sono state riconosciute anche dal solo riff. In compenso si trova più in difficoltà con parti "lead".
È invece stato assolutamente incapace di riconoscere canzoni (di altre) suontate dal sottoscritto. Anche con i live si trova abbastanza in difficoltà.
Potete anche arricchire il db, se trovate una canzone di cui sapete l'origine e che non è presente
Links
  • Stevie Wonder
    • Higher ground (ok)
    • Don't you worry about a thing (ok)
  • Nightwish
    • Come cover me (ok)
  • Saxon
    • The crusader (no)
    • Just let me rock (no)
  • Rhapsody
    • Forest of unicorns (ok)
    • Dargor, Shadowlord Of The Black
  • Helloween
    • The twilight of the Gods (ok)
    • March of time (no)
    • Future world (ok)
  • Dire Straits
    • Money for nothing [senza arrivare nemmeno al riff] (ok)
    • Two young lovers (no)
    • Les Boys (ok)
    • Solid rock (live) (no)
  • Royksopp
    • Alpha male (ok)
    • A beautiful day without you (ok)
    • So easy (ok)
  • Tim Buckley
    • Gypsy woman (no)
    • Dream letter (yes)
  • Cat Stevens
    • Father and son (yes)
    • Miles from nowhere (yes)
  • Chieftains
    • O'Sullivans March (no)
  • Bandabardò
    • Ewa (no)
    • Sette sono i re (no)
  • Orbital
    • Halcyon (yes)

Inner float.... (CSS)

I feel so stupid. I never thought there was a simple solution like this. I have to find out "why" it works. It is probably written somewhere here. It's late night I'm not going to do it now.
I read the answer in this page (and it is here I got the previous link). Thanks to Gomi to point me the solution. I would have linked the original post, but it unfortunately uses Archive: no and x-no-archive: yes, so no google groups.

Io e Netbeans

Per una serie di casi del destino anche il sottoscritto si è ritrovato costretto ad usare Java. D'altra parte era stato ampiamente previsto, e la cosa non mi ha trovato più impreparato di un tot.
Complessivamente mi sono assuefatto all'ambiente. Il linguaggio è abbastanza "stupido", ma va bene nella maggioranza dei casi. Certo, avendo dei templates decorosi... la mia opinione sui generics di Java non è certo delle migliori.
D'altra parte la piattaforma regge bene. La libreria continua ad essere ben fatta. E complessivamente anche Swing mi piace abbastanza. Non è troppo cervellotica da usare (mai usato Carbon?), e si comporta entro grandi linee bene ovunque (mai provato Tk?).
Proprio riguardo alle GUI si possono apprezzare alcune dei maggiori vantaggi di NetBeans 5. Il nuovo GUI editor, Matisse, è semplicemente favoloso. Sicuramente sta al pari con InterfaceBuilder dei Developer's Tools di Apple, forse è anche migliore.
Matisse
65209328_42292f33bc_m-2006-02-23-18-45.jpg
Qui un piccolo screenshot di Matisse. Fare le GUI è davvero semplice.Si tratta di disporre i controlli all'interno della finestra. NetBeans automaticamente mostra delle guide, per disporli "bene" in relazione fra loro.Per esempio NetBeans tenterà di suggerire che tre campi di testo uno sopra l'altro finiranno allineati e così via.
L'utente poi potrà specificare quali controlli vorrà che si ridimensionino con la finestra e quali no, e quali vuole che siano "ancorati" ad un qualche bordo, in modo che si spostino con la finestra stessa.
Anche se la spiegazione non rende l'idea, posso garantire che il tutto ora è davvero molto semplice e comodo, niente a che fare con il famoso GridBagLayout (in pratica i Layout sono caduti in disuso, a quanto pare)
Tutte le proprietà dei controlli, codice da inserire prima o dopo per inizializzarli e la scelta del costruttore possono essere fatti direttamente da Matisse.
Refactoring
Finalmente anche NetBeans ha aggiunto le funzioni di refactoring che eravamo soliti trovare su Eclipse. Non c'è molto da aggiungere, fanno il loro dovere, punto e basta.
Altro...
Altro non ho ancora avuto il modo di provarlo. In effetti Java continua a non essere il mio ambiente naturale, per quanto mi stia sforzando di affrontarlo con mente aperta. Sono in grado di vederne i pregi, ma mi balzano anche all'occhio i difetti.
Allo stesso modo devo dire di NetBeans che è davvero un bel progetto, un IDE ben fatto di cui più lo si usa, più si scoprono utili funzioni e interessanti scorciatoie.
Purtroppo è terribilmente mastodontico. Sembra di manovrare un camion, è lento e spesso si ferma a pensare davvero troppo. A causa dei limiti di Java diventa sostanzialmente impensabile scrivere il codice semplicemente con un editor di testi, ma la tentazione è forte. TextMate è maneggevole, snello, veloce. Risponde ai miei comandi.
NetBeans ha i suoi tempi. La cosa che continua a torturarmi è... ma abbiamo davvero bisogno di una piattaforma che ha bisogno di centinaia di megabyte di IDE per sopperire alle sue mancanze? A quanto pare si, ma c'è qualcosa che mi suggerisce all'orecchio che mi hanno fregato (con questo Matisse è comunque fantastico, e mi piacerebbe averlo a disposizione anche per le mie GUI Python, Swing è una libreria abbastanza buona -- specie adesso che usa il freeform layoyt ).
Attenzione!
Se usate NetBeans 5 sotto MacOS, ricordatevi di copiare il jar org-jdesktop-layout.jar dentro il classpath standard della vostra versione di Java, altrimenti non riuscirete a combinare nulla.

Latex + Emacs vs. MathType + Word

Recently I had to write two simple scientific documents. Their subject and structure was similar, so I decided to compare Latex + Emacs and Word + MathType.

Emacs was Aquamacs, standard version, configured to work with Texniscope. You can read my last two posts about Aquamacs w/th Latex and Texniscope. Aquamacs is itself almost configured: of course to use its extended capabilities you should already know Emacs. If you are a novice, you may want to try TextMate or BBEdit instead, or maybe TexShop (search google for them ☺).

Please notice than when I speak about Emacs, I assume Auctex is configured and working. This is the case with Aquamacs, which comes with Auctex bundled. Other Emacs installations already include it (and if you use GNU/Linux or FreeBSD it should be easy to install the package).

MathType was able to handle the equations: for example some equations used in computer science are really hard to express with MathType. So this is not a test intended to prove that latex is more powerfull. This is known.

While Word is a wordprocessor meant to write and quickly format texts (this is not perfecly true, since Word includes some functions that are part of a publishing software), Latex is a full environment meant to produce documents ready to be published.

We already know that Latex is more powerfull than word. We are now comparing Latex and Word on Word's own field: small simple documents.

Crashes

The main problem I found with Word + MathType were errors. MathType tends to crash in unexpected ways. This is not usually a problem: the rest of the document is not touched (and Word itself does not hang) and you lose only the last minutes of work.

The first thing you do is close Word and reopen it. Everything will work as usual. Unfortunately crashes anger me a lot, and I tend not to be able to continue working. I find overly annoyinh to redo the same job twice.

On the other side Latex and Emacs never crashed. In fact I have never seen Emacs crashing in my whole life.

References

Using references with MathType and Word is not difficult. You can create a numbered equation, then say you want a reference to an equation and double click the equation number. This is pretty simple: unfortunately if you have a long Word document, you have to manually find the equation you want to reference, and this is not quick. You have to manually find the equation.

With Emacs you can say you want to put the reference of an equation and it will present a list of all equation (you can read the label and the equation itself) from which you chose which equation to reference.

If you use Emacs(Auctex) facilities to create sections, subsections and such, the editor encourages you to label them. This way you can also reference theorems and sections. Moreover it's terribly simple to use, while Word's referencing facilities are less powerful and more complicated to use.

Symbols

This is not a problem, in this case: in this document we are using only basical symbols. If you need more symbols, while amslatex (which comes with standard latex distributions) provides them, MathType does not (well, you have to find a font that uses them, change the font and everything).

Bugs aka "Copy and Paste"

With MathType and Word you cannot copy equations. This is a known bug. If you just select an equation within Word and copy or cut and paste it, Word will say it's not able to save on "current volume". Changing volume does not help. You have to "convert" all equations. It is a command from MathType menu in Word, easy to call, but slow to complete, if you have many equations.

This bug usually does not apply if you drag n drop, but I'm afraid this is not always true.

If you want to copy and paste, you have to double-click on the equation to open it in MathType, copy the equation in MathType, create another equation in Word (and this opens it in MathType), paste the old equation in the new one. I don't like this.

Copying equations (or part of them) with Latex is simple and fast.

WYSIWYG

Of course Word + MathType is a full WYSIWYG environment. Emacs is too. You can "preview" equations and pictures in the document (that is to say inside Emacs buffer you see the rendered equations). Of course to do this you need an Emacs with graphic capabilities, for example Aquamacs or X11 GNU Emacs or XEmacs; it does not work with the textual version ☺.

Conclusion

Of course to use Latex you need to learn Latex (but to learn how to use advanced Word features, you have to study too). And to use Emacs, you need to understand a bit how it works, even if an environment like Aquamacs can be used with little knowledge about Emacs (don't know similar Emacs versions for Windows, still I suppose they exist).

But this allows you to be much more productive in the middle and long term. Moreover Aquamacs (or Emacs) is free and so it is Latex. Word + MathType costs a lot. Moreover Emacs + Latex is cross platform. You can work with people using Macs, Windows, Linux, FreeBSD, everything they like. You can edit their documents and you can easily publish your results in PDF on the web. You can also send your files to an editor, until some time ago Latex was one of the few formats accepted by scientific magazines.

TextMate 1.5 is out

New TextMate version is out. It is a big improvement over the last stable (I happen not to know which version number it had, since I've always been on the edge with betas -- and with no problems, update system is wonderful )

These are some of its new features (following list is copy & pasted from TextMate website)

You are supposed to go and it!

More informations here

MagicLantern: image viewer

MagicLantern is a small GPL'd image viewer. It's Cocoa and it's fast to load. In this sense it can be used as a replacement of Preview as the default image viewer.
Another useful feature is it's ability to navigate through images in the same folder. Open one and use arrows to view them all.
The worst thing of MagicLantern are icons it puts to documents if you chose to use it as a default image viewer. They have the same icon of the application, and while it is good as an application icon, it's quite inappropriate for documents.
First it does not appear as a "document icon" (most document have the usual rectangular shape with an edge folded and that identifies them immediteley as documents), second different kind of images (eg tif and jpg) do not have different icons. If you don't use extensions or you keep them hidden it is not immediate to understand which kind of image you are dealing with.
I'm not a graphician, but a programmer, so I'm not the right person to draw the icons (and in my software I have similar problems), so I hope someone will do the icons.

Texniscope (DVI previewer)

Texniscope is a beautifull DVI (and PDF) viewer. It is free and well integrated with MacOS X.
I needed such an application. In the X11 world there is plenty of dvi previewers (xdvi, kdvi), but for the MacOS there were none, a part from MacDVI, shareware and ported from the old MacOS (and less user-friedly than its X11 counterparts).
Texniscope also support source specials, you can have a read at my post here.

Aquamacs 0.9.7 is out (Printing + Latex + ... )

Download/Scarica

Among new features, you can print right out of the box (using Preview.app) and Auctex is beautifully integrated with Emacs. In fact it is the more user-friendly and more complete latex editing environment I've ever used.

And don't forget to read this, if you want to make it even more user-friendly.

In short:

  1. Copied txs-search.el in my ~/.elisp directory (which is loaded inside Emacs with (add-to-list 'load-path "~/.elisp")
  2. Loaded txs-search.el in Emacs adding in .emacs(require 'txs-search)
  3. Added shortcut with (add-hook 'tex-mode-hook (lambda ()(local-set-key "\C-c\C-j" 'txs-jump-to-line))). This does not work, I have to call directly Meta-X txs-jump-to-line. I also tried different keybindings, with no success.
  4. Changed editor line inside Texniscope, and cancelled useless option for alternative editor (read this in the tutorial I linked above)
  5. Compiled dvis with -src-specials option: everything works as expected (except that I'm not able to enable source specials with pdf, I'll have to take a look at it)

In the end I have to thank David Reitter for the tutorial for Emacs/Texniscope, which I suppose is taken from a mail/post he did.

More on Aquamacs (frames and dired)

This is a short tip from the wiki (and most of the notes here will come from the wiki)

After some time, I found quite annoying the way Aquamacs manages frames and windows when I use it as a filemanager (which is something Emacs is really good at) -- in fact this ain't a problem, since I rarely use it that way and I can quickly change behavior with a menu toggle --.

If you would like it to behave like "traditional Emacs" you may want to read this tip

Since I was speaking about dired mode, I add it here: another tip. With this you can open files using mac os open command.

Mac Emacs (Aquamac)

Unfortunately enough this seems to be going to be a "text editor blog", with BBEdit post, this post and almost finished post about TextMate.

In fact I already told Mac Emacs versions do seem to miss something, and this is the reason why I chose to buy TextMate (a cheap 39$ affair).

Right now I'm just trying to convince myself that TextMate was worth 39$. I mean, probably if I discovered Aquamacs earlier (the first version I tried long time ago were "new") I would not have bought it (even if once I was a vi fan -- and in fact I still am, for some things).

And not because I don't like TextMate anymore... just because Aquamacs is free and is free software [ which is good ].

Aquamacs

You can download Aquamacs here.

I told how weird do seem Emacs key bindings on MacOS (in fact they look odd everywhere outside Emacs). Some of them are pretty standard, readline supports them by default (and so most command line applications do) and Cocoa controls also do (that is to say they work in any text editor.).

I'm talking about ctrl-a, ctrl-e, etc.

But you are never going to convince a Mac user he has to ctrl-x ctrl-s to save or ctrl-x ctrl-c to quit.

So Aquamacs uses standard Apple bindings. Command-C, Command-S, Command-Q. This way the command-key is not free. And meta has to be mapped on alt.

So if you have a not english keyboard, you may not be able to type square brackets, for example. And braces. In fact this is a serious design flaw, in my opinion.

In fact I found out the flaw was in the user (me) who did not read the wiki. Meta, Apple/Command, Option keys are fully configurable.

In my opinion if you are going to use Emacs, you expect to find Emacs key bindings. The more logical choice is to use Command for meta, and leave alt as alt, to enter braces (and on american keyboards accents.).

Still you may want (and it is my choice) to allow Command-key to be used for mac key shortcuts, but you want to pass option/alt to the OS (so that you can use [] and other characters). You do this with

(setq mac-pass-option-to-system t)

.

Should you have troubles with copying and pasting text from outside into Emacs or vice-versa, try to use

(setq x-select-enable-clipboard t)

In fact you can find lot of informations in the wiki:

Emacs wiki.

The nice thing was that you are able to use standard MacOS open and close dialogs, that is really nice.

But there is something even more beautiful features:

  • Frames are mapped to windows: when you open a file, you open it in a new window, and you can manage windows with Expose. Probably a hardcore Emacs user is not going to like this (but probably he will prefer some other more standard version).
  • Fonts: fonts are nice. It uses MacOS fonts and locales and unicode characters appear to be handled correctly (not sure for full unicode, for european >7bit characters, it works).
  • You also have transparencies. It's just a little nifty feature.
  • Cut and paste works as you expected, so does deleting a text selection. This is probably one of the single features users that are not used to Emacs are going to hate, even if it makes perfectly sense in the Emacs way of working.
  • Last but not least, you can associate files with Emacs, so you can use it as a standard MacOS text editor to open files double clicking in the finder.

I'm really impressed by this project: in fact it's enought Emacs you want get too confused if you are used to Emacs, but it's also enought Mac you can use it along your other Mac applications, without having to rethink basic commands (if you don't want to).

Right at the moment it is in my opinion the best Emacs version for the MacOS out there.

TextMate

BBEdit, vim, Emacs
Until recently I thought BBEdit was the best possible editor for the MacOS. I probably was influenced by my previous experiences (I used BBEdit years ago, before I switched to *nix). In fact I was amazed how simple was to do complex queries (in fact it was easier than vim from a psychological point of view), and project wise or directory based queries are as easy to do as standard queries.
Moreover in that period I needed a tool with good HTML and site management capabilities (and BBEdit has them both, and in fact for HTML projects is in my opinion still the best tool out there) and it is fully scriptable (and files can be partially generated by scripts, which is good).
These qualities made me forget about other things I looked for in an editor. That is to say: I want to use an editor that lets me code faster, helping me in manipulating text. BBEdit has extensive facilities, but most of them are really not immediate.
Basic text handling is somewhat poor (for example indenting). It's best feature (glossaries) are not really useful for what I do most of the time. Still I liked it. It was better integrated with the mac os environment. This is the main reason because I did not use Emacs or vim: I am quite skilled in both of them, for I had to work on machines where one of them was not available. Mac ports exist, but are somehow less "native".
Vim does open a single window per application, and if you want to have more windows you need more applications, and that is not extremely practical.
If you are interested in an Emacs version that is MacOS friendly, read this.
The key question is: it is that important to behave like a Mac application? What does it mean being a "mac application"?
You'll be reading a more complete post on Mac philosophy on this blog later on. Right at the moment we can summarize: Apple philosophy is to keep things simple but not simplistic.
About the Apple UI there are lots of documents out there, but it's no mystery that nor vim nor Emacs follow Apple guidelines (and that makes perfectly sense, it's not a critic).
An application well integrated in its environment, works better. It's easier to use, you already know shortcuts, drag n drop behaves as you expect, integration with LauncherServices is present and so on. That is the reason I preferred BBEdit to vim or Emacs (now both Emacs and vim have some integration features, but do not have them all), even if I was skilled in both and they both have features BBEdit hasn't (and the features BBEdit has they haven't are not so important to me, in fact I found out my use of BBEdit is really basic: I'm a lot more into TextMate).
TextMate
When I tried TextMate for the first time, I thrashed it almost immediately. It missed CVS and SVN support (and BBEdit SVN support was wonderful -- unfortunately I'm not using SVN anymore). In fact I did not give it any chance. I had just bought BBEdit and was learning it's more complex features.
I wasn't ready for TextMate.
Text editing
Text editing is smooth. You can use all Cocoa standard shortcuts (that borrow heavily from Emacs) and Cocoa spell-checking is builtin. Fonts are smooth and beautifull.
TextMate does "smart typing", that is to say when you type a bracket or quotes, both the opening and the closing bracket or quote is typed and the cursor is placed inside. The first times I met with this feature (and it was with some IDE's) I hated it. Now I can't live without and I do a lot of mistakes when typing with something that does not support it. In fact I think it makes you save a lot of typing and a lot of time.
TextMate has other smart features, for example you can edit more than one line in a time (and the key are rectangular selections of any kind)
Folding is supported, that is to say you can look at the code with the level of granularity you chose. You can collapse blocks you are not interested and expand them when you are not interested.
Another useful feature is auto-completion: it's not as sophisticated as some C++ and Java IDEs since it's based on typed text rather than "possible code", but it has the advantage it applies to non-static languages too (Perl, Python, Ruby).
In fact TextMate can be used to code in C or C++, Java (even if it lacks some useful features that are necessary do to poor language design), Perl, Python, Ruby and a lot of other languages. Moreover it can be easily extended to other languages.
The most interesting thing is that you can define macros that put inserted text in more than one place. The most simple example is with HTML. Most HTML tags are kind of <tag></tag>. With TextMate you just say insert a "tag pair" (that is to say <p></p>, since p is one of the most used tags), and the editor will insert the text, selecting the first "p". Then you can type the correct tag (for example h3, or maybe table) and the closing tag will be updated accordingly. This makes a lot less typing: and can be used in clever ways for other languages too (think about latex environments).
The last (well not really) interesting feature is macro completions. You can easily define macros and type only a few characters, then tab complete. This is great.
The beautiful thing is that TextMate can be easily extended. There is a lot of support for many languages (unfortunately not for Prolog, and that is something I miss a lot, even not enough to write my own bundle).
Organize code
TextMate has some basic project managing. It can be further extended with TmCodeBrowser.
It's improving in this field. It can also import projects from Apple's XCode.
To be completely sincere to manage this website I prefer BBEdit (however most "text editing" and maintenance is made with TextEdit). I miss an FTP browser (I know this is controversial and the "current" solution is to have TM interact with FTP clients, I also do this, but sometimes it is just to good to directly edit).
And remember that TextMate + BBEdit do cost less than Dreamweaver (and produce better code -- of course this does not apply if you write code manually with DW, but then I think TextMate text editing facilities are just superior).