jueves, 29 de diciembre de 2011

Invincible Perl



Have you seen the talk about DoSsing websites just using crafted data on forms (POST)? It's the trending topic of this week.

Well, here you have a couple of links related to this talk and some extra info.

The interesting thing that surprised me (or not so) on that article/talk is that the only language they tested that's not vulnerable to this attack is.... guess what? Perl. Here's the extract of the article:

Julian and Alexander did a great job with checking many programming languages used for web applications for their hash table implementation and hash functions. For all of them they checked, they managed to find a lot of keys mapping to the same output, except for Perl. Perl uses a randomized hash function, i.e. the hash doesn’t only depend on the key, but also on an additional value, that is chosen at startup of the application at random. All other languages also store the query parameters send in an HTTP GET or POST request in an hash table, so that a request with many query parameters all mapping to the same hash value will slowly fill such a hash table, before the first line of code written by the application programmer will be executed. Filling this hash table will usually take several minutes on a decent CPU, so that even a fast web server can be kept busy using a slow connection.

And here you have HN comments

+1 for Perl!
Between offtopic and related here's another nice talk from 28C3 that's having place these days in Berlin.

martes, 27 de diciembre de 2011

Git, the stupid content tracker, or not so


After roughly a year of using git daily, one has already crossed the "WTF!?" side and now is in the "It's obvious" land.

After getting help from all coworkers I had last year, lots (I mean *LOTS*) of reading, and many moments of "Am I the only one in the world that doesn't get this?", all regular processes go without thinking now, and I know pretty much what is happening under the hood.

Some things are still a bit raw on the edges, but mostly because they aren't used so often (submodules, bisect...), but I digress...

Thing is that using and knowing git gives you extra power, not directly related to versioning code. As Linus said: "git is the stupid content tracker", it manages blobs of bytes.

  • git grep: Probably faster than grep -ri, and more focused to what you surely want to search. I've already integrated it with emacs, and try to use it more and more, instead of rgrep, or ack.
  • git ls: great for the kind of find-file-in-project functionality.
  • git log -Sfoo : Search throughout the history
  • git log -p : modifications in context
  • git annex: manage whatever content
  • using git to deploy: There's capistrano, and puppet, and chef, and... but git can handle it if configured properly. Probably this can end in a mess if you need to trigger many things when deploying. You know, there are hooks and everything, and you cand build your poor-man-capistrano. It's just your choice. But definately for mostly static sites, it's a nice thing to keep in mind.
  • Not really a git feature, but thanks to magit, or fugitive, you can have a pretty painless integration with your workflow, so it's a win. And you feel safer

Have more tricks? Comment!

Ok, after a bit more than a month, there's a post precisely on that. Nothing new in the article, but there are nice insights in YC comments

domingo, 11 de diciembre de 2011

martes, 22 de noviembre de 2011

tramp + shell = win

Did you ever notice that tramp is a great piece of elisp? I hope so.

The nice thing I discovered today is that it's highly tighted to the whole system, and if you just m-x shell when you're in a file opened through tramp, it'll open a shell in the remote system.

Super nice.

domingo, 20 de noviembre de 2011

Creating a simple common lisp application

After giving a further look at common lisp (a bit of PAIP, and PCL), I've found a project that can be a nice 1st app for me.

To develop a common lisp app, first you need to set up the environment and choose the toolchain. These have been my decisions. Tips are pretty appreciated.

Requirements

The requirements are the bare minimum for common lisp. I use SBCL myself, and don't know much of the differences between implementations. sbcl works just fine.

Editor

I use emacs 24, with slime, paredit and autocomplete. Use whatever you feel like but notepad. Obviously, emacs is recommended :)

Libs

Use quickload to find and load libraries. It's surprisingly easy and straightforward to use.

Project

quickproject to initialize the project is a nice way to avoid writting bolierplate, and to make sure your project will be loadable through ,load-system.

Tests

I tried a couple of testing packages for common lisp, and decided to go with lisp-unit due to its simplicity and availability in ql repos.

Code repository

The code is being hosted in a private git repo in bitbucket. They give you unlimited public/private (*yes*, private) repos, using git/hg, with issue tracking and all, for free. It seems a nice nice alternative to github. great to host projects in early stage where you don't feel like sharing the code to the world.

That's it for now. There's no public code for the moment... There's nothing to see here :)

sábado, 12 de noviembre de 2011

change emacs url-browser

When you click an url in emacs, it'll open a browser with that url. That's fine.

Problems arise when you have multiple browsers and they fight to be your preferred one. In a coworker's box, it tries to open konqueror (WTF?!).

One way to fix the issue is changing browse-url-browser-function.


(setq browse-url-browser-function 'browse-url-generic
browse-url-generic-program "chromium-browser")


Not only that, but the nice thing would be that emacs reused a browser if you have one opened (firefox or chrome) and opened a new one (chrome) otherwise.

I've been messing a bit with proced.el to find out how to list external processes programmatically, but had no luck. If I find out how, I 'll modify this post with new info.

If you have related info, please, comment :)

Thanks to Davazp that pointed me to list-system-processes function, I just wrote the code to use an already opened browser to open a given url.



A good quickreference to look for function signature differences between elisp, scheme and cl is here. It helps quite a lot

domingo, 6 de noviembre de 2011

Metacircular game of life.W00t!

Here are a couple of links on game of life info.

First of all, a game of Life implemented in one line of APL, explained, so you can even try to understand it. Then, a couple of articles on cellular automatas, explaining game of life basics and not-so-basics.



And the really amazing stuff: Metacircular GoL

domingo, 23 de octubre de 2011

Introduction to (modern) Perl (course)



Barcelona Perl Mongers are organizing a 8 hours course on Perl intended for programmers that have no or little experience in Perl. It's not an introductory course to programming.

The course will be on November 5th, at UPC (Barcelona). 25 Euros for the course, and an exclusive T-Shirt.

I'll be there, maybe just listening, or helping answering questions.



viernes, 14 de octubre de 2011

I still think Perl

The other day, a friend asked how to split a string by commas, but only if they aren't inside a tag, say enclosed by '<' and '>'. I tried python, but somehow regexes are so hardwired in my head, that I can't work with languages that do not have regexen so hardwired in their heart.

Here it is. Tiny, but gets the job done. And that's what perl is for. a regex with lookbehind stuffed into split. No problem sir!

lunes, 10 de octubre de 2011

steve, the web, and innovation.



It's been less than a week a genius left us yada yada yada.....

Since last October 5, I've been thinking a lot about Alan Kay and I was waiting to see some references from sites talking about MrJobs to Mr.Kay.

Well, today I've seen it, and this post will be just a kudos to people knowing the real story, that Steve had great qualities, and was visionary in a very bright way, but he didn't invent the future. You know...

But the internetz has gone crazy on this, so I wanted to point out a couple of curiosities I've seen since then.

- First, a HN screenshot I did the 'day of the facts'.
- Then a post talking about Alan Kay, linked from a 'outstanding articles' widget, pairing with Steve.
- Now a great and long post about great things that happened at XEROX PARC, and things Jobs saw there, and how he implemented then in Apple. He didn't invent the mouse, but simplified it (in fact, Xerox didn't invent it either), he didn't invent GUI, but adopted it, and he didn't invent the iPad, but 'implemented' it, in the exact moment there was market for it.

Cya!



Btw, if you wanna know more about Kay and friends, here is another post on this blog with amazing videos, or just check the internetz, or just download pharo/squeak.

Ready, set, Dart!



Today there's been the first official press info and release of Dart language. A class-based language developed by google.

Features: OOP, class-based, optionally typed, and thought for the web. It seems it'll have a client side debugger. (Hello amber! :p )

Lars Bak has been strongly involved in Dart, and given his smalltalk past life, it's sensible to say that we'll see some familiar things in there.

Today is the first day of AI classes in the standford open course. For the moment, browsing the notes of the first class...



See the flash bar in the top? :)

domingo, 9 de octubre de 2011

Emacs 24 is frozen

Emacs 24 entered the feature freeze state a couple of weeks ago, so it's the moment to install it and start fiddling with its new features (I want to try the editable occur buffer, and some asynchronous goodies for gnus).

There have been a couple of posts in planet emacsen that explain how easy is to install it in debian or ubuntu (natty).

The thing is that I use an older ubuntu version and I had to compile it myself. Not very problematic, but here's the couple of libs that I had to install before being able to compile it. Obviously, you'll need the usual binutils and dev tools. also you'll need these packages.

apt-get install autoconf texinfo libxpm-dev libgif-dev libgtk2.0-dev xserver-xorg-dev xorg-dev libfontconfig-dev libfreetype-dev libxft-dev # probably, not everything is needed, but once you warm up, apt-get is too easy.

Then, just get the code from the repo, and configure install in proper directory:

git clone https://github.com/emacsmirror/emacs.git 
cd emacs
./autogen.sh
./configure --prefix=~/emacs-24
make install


Now you have your emacs in ~/emacs-24/bin/emacs, and hopefully, everything will work from the beginning. I had to disable a couple of lines in my .emacs file, but just minor things.

Now it's time to try emacs-starter-kit 2.

martes, 4 de octubre de 2011

Is it really that bad? Seems so

In the last couple of days there's been quite a lot of ranting about overly complex software we have to manage daily. It applies to software we use (super-complex UI and over-featured apps) and software we develop Does it really make sense to deal with so many layers of added complexity to deal with mostly simple (conceptually) problems.

In those texts, they talk about 'old friends' like boost, SDL, Xcode, Objective-C, never-ending-toolchains, and supercomplex interfaces to third party software (APIs, security layers, etc.).

In my opinion, and without having spent as many years as those guys (or commenters at HN) on computers, it's true that the starting barrier to any new environment seems overly complex for the functionality we get. Most of the times, external tools solve deficiences of languages. Being a tool geek myself (probably, I have spent more hours than you trying and configuring window managers and editors), I have the feeling that entering most of new environments is more complex than it should be.

Want to do a rails app? no problem, you just have to handle a few technologies/tools:
ruby, rails, cucumber, rspec, rack, passenger, bundler, rvm, gems, html, js, ajax, css. Then, keeping compatibility with Chrome, firefox, safari, opera and, God forbid, IE.

Not bad, eh?

Well, if you want to write the views in a more confortable way, you can use haml, sass, compass, coffescript, that will compile to their ancestors, and will make you a happier person.

You see? (I hope you get the sarcasm)

Every now and then I think about Dan Ingalls quote:

"An operating system is a collection of things that don't fit into a language. There shouldn't be one"


And drool when thinking about smalltalk.

martes, 27 de septiembre de 2011

Bihain de uindou

Demasiadas veces mirando por su ventana y quedándome en blanco. veo
que algo se mueve ahé dentro, y veo la ventana mirándome, y la veo a
ella mirandome a través de la ventana. A veces, incluso me veo a mi a
través de ella a través de la ventana.

Y aún no sé qué decir (me y le). Y te.

Señalar con el dedo y ver el nombre en verde.
Clicar. Cerrar. Clicar. Cerrar. Y repetir.

sábado, 17 de septiembre de 2011

Amber language (former jtalk), digging deeper


Lots of changes have happened in jtalk world since last week.
  • Jtalk is now Amber. The project has changed its name when the 0.9 release happened. That means that the repo is now different, and the website too.
  • JQuery bindings have been removed from the system. Now we can access javascript objects directly, and use asJQuery in the same way, so there's no drawback, only the way to deal with jquery is more smalltalkish. Counter new appendToJQuery: 'body' asJQuery works perfectly, so no problem.
Creating functions
If you want to know a bit more on amber, you have to keep in mind that it's a smalltalk, so you can explore everything in your IDE. Let's try to find out a bit more on how the compilation from smalltalk to js works. This will allow us to debug our in a lower level than usual, and find glitches in our codes, or detect where our closure is missing the variables (when interfacing with js, sometimes it's useful to see the whole js code, and make conclusions on js).

Let's create a new class Foo with a method that gets a block (callback) and executes it. Now, to find out how it's compiled, we'll make amber print the compiled source of the method:
(Foo methodDictionary at: 'get:') fn compiledSource "print it".

If we print it, the result will be the js source of the method



You can try variations like returning explicit values, try to pass instVars to the closure, and see what is the translation to js. This helps sometimes to find out your way.

Can I inspect?
Inspector is there, but for the moment, it's in very early stage.

Debugger
Debugger is also there, also in early development. You can see the stacktrace, and inspect the methods, but not changing values and so.

NodeJS

We can use amber for the server side, running the generated javascript on node.js. Due to the hability of Amber to interoperate with plain js, we can use a shitload of libraries from amber. Here follow a couple of examples of amber on node.js

Server
Nicolas Petton wrote a fileserver meant to be used in the node.js side. This allows us to commit changes to our files transparently without the need of webdav,python(see last post), or any external server. It's Amber all way down.

The usage is fairly easy. Just cd to the root amber directory and run ./bin/server, that will run ./server/FileServer* things.

IRCBot
Trying the node.js part of amber, we can try to build a small program, and as no programming language is complete unless it has a IRC bot in it, let's solve this issue:) Btw, I hacked a couple of emacs functions to deal with st files a bit better.

domingo, 11 de septiembre de 2011

can your editor^W OS do this?



Here is an emacs feature that it's hard to believe until you see it working.

m-x butterfly


Unbelievable, no?

Well, let's link this amazing functionality to the gesturing strokes-mode.

m-x strokes-mode
m-x strokes-global-set-stroke


Then, click in the buffer that appeared, and draw(drag) a circle with your mouse. when you end, press the right button.

now emacs will ask you for a command. Now it's the butterfly turn. write 'butterfly'.

Ok, now you have configured and amazing mouse gesture that will flip bits on your hard drive only by reproducing the figure (circle) you just did before.

in any buffer, press shift and draw a circle dragging the second mouse button (mouse wheel probably).

ENJOY!

PS: I've changed the shortcut from the second button to first, and now I can use my tablet to manage emacs. And here's another great thing of the ubiquity of emacs: You can use it to manage things related to irc,jabber,mail,text editing, playlist managing and even pdf reading. neat.

viernes, 9 de septiembre de 2011

emacs and smalltalk, a bit closer

Today I've been hacking around with jtalk. Implementing something for the node.js backend means that probably you'll be using your editor of choice.

I've downloaded paolo bonzini's smalltalk-mode.el

I've hacked some shortcuts to navigate through classes using emacs narrowing feature.

Here's the hack:

jueves, 8 de septiembre de 2011

HN Frenzy

HackerNews is not in its greatest moments lately, but today, lots of diferent great articles/links appeared. It's a bit overflow of info in just one moment, you open a handful of links and you face.



Not in HN but a tiny example of how cool is the project that's driving some of smalltalkers to sleep 4 hours per night.Jtalk. Credits on that go to Bromagosa

lunes, 5 de septiembre de 2011

Routing tutorials in rails 2.X

For me, one of the most confusing things in Rails is routing. The DSL, all those automagic methods, abuse of method_missing (it's starting to feel usual), and RESTful conventions, mixed with namespacing,

I've found three detailed tutorials (well, series of tutorials) that seem to explain all what's needed to get into the routing thing. Here are the links to

under-the-hood-rails-routing-dsl
under-the-hood-route-recognition-in-rails
under-the-hood-route-generation-in-rails

A couple of articles on extending routing system
monkey-patching-rails-extending-routes-1
monkey-patching-rails-extending-routes-2

Here's the starting point of a super-detailed explanation and hands on tutorial on rails 2.X routing.

beginners-tutorial-routing-in-rails-20-with-rest-part-1-of-n

There are 6 parts in this last tutorial.

Btw, both blogs seem good sources of information. Good explanation on different topics, always quite detailed, and well written. For example, here's a series of posts on AJAX (from the bottom up).

Bye!

domingo, 4 de septiembre de 2011

Jtalk tutorial. (Valid until the end of this week)





TL;DR
write this in a workspace, select, and click 'DoIt'. Instant reward.
Counter new appendToJQuery: 'body' asJQuery




You know Smalltalk, it is an object oriented programming language developed at Xerox PARC during the 70's by Alan Kay, Dan Ingalls and other brillant guys. It is known that Kay, and probably other members of the team, was born from the leg of Zeus. Jtalk is an implementation of Smalltalk that runs on top of JavaScript, developed by Nicolas Petton. It allows the use of Smalltalk for client side applications. Even more, Jtalk allows you to use the famous IDE from the Smalltalk world directly in your browser. It compiles to JavaScript, and follows Pharo, a fork of the Squeak Smalltalk implementation.

The canonical "Hello World" looks like this:


You create a subclass of Widget, and you implement the #renderOn: method. Jtalk will pass an HtmlCanvas instance that we call html in our code. This object provides some "brushes" allowing to "paint" into the html canvas by message passing. We created a div element by sending the div message to html. The div element has it's class and id attributes defined, and it contains a h1 element. Everything is performed by passing messages to the html object. Those familiar with the Seaside web framework will recognize the html canvas. After the HelloWorld class is
defined, you can see it in the browser by appending an instance to the page's body using JQuery:

HelloWorld new appendToJQuery: 'body' asJQuery


A JQuery object is created by passing the #asJQuery message to the string object 'body'. Then we pass the #append message to the JQuery object, with an instance of HelloWorld as argument. You can evaluate this expression in the Workspace and see it in action.

Another way to do the same is going to JQuery class, and send the #body message.

Where is the Counter?
If you know Seaside you'll want to look at the Counter example. I will reproduce the example from the Jtalk website, which you can find also with the IDE's class browser. It is a good example because it shows how you can write stateful applications in Samalltalk, by simply using its object system as you would do in any application:

As in Seaside, the button definition is beautiful. Since the object itself holds the state of the application, you simply bind a Smalltlak code block to the onclick event, and Jtalk will take it from there.

Interacting with the DOM with JQuery and JS evaluation

As you can see, there is JQuery support provided by the JQuery class. We just used it for appending a piece of html to the body element of our page. There is support for a good part of the JQuery api, as you can see by browsing the methods implemented in the JQuery class. You can do DOM insertion, css manipulation, event handling, etc. If something you like is not implemented, you can evaluate JS code by enclosing it with the "<" and ">" characters. A wrapper for ajax is also available:



Here we create an Ajax object and then we send some messages to it. As you can see, we use Samlltalk blocks as callbacks, this blocks are compiled to JavaScript anonymous functions for execution. There are other messages availables in an Ajax object, like #onCompleteDo. Dictionary like syntax is provided for passing additional settings to the Ajax object:



As test, I wrote a small HTTP service interfacing a CouchDb instance. I did it in Python using the small but cool Flask framework:



Please consider it almost pseudo code. You can note its very simple stuff. We serve the Jtalk DE at "/", and we provide access to the database in "/get/<doc_id>". Now, we could build a small wrapper for accessing this service:



We provide a single method called get:onSuccess: allowing the client code to request a document and executing a callback block on the resulting data. Smalltalk blocks are constructed using brackets, and they are like anonymous functions. Temporary named arguments are declared with the :argName, and after the bar you can write any Smalltalk statement. Our onSuccessDo callback takes the data received form the Ajax request as argument. This data comes in JSON format, so we
use an instance of the Smalltalk object to translate this to a Jtalk object, and then we pass that to the block provided by the client code, which we called "aBlock".

An experiment using Rasta.js for data persistence

Rasta.js
is a very simple key/value storage service. It provides a REST API and a client library:

<script src="http://rastajs.errorjs.com/rasta.min.js" type="text/javascript">

We can use this for looking at how can we delegate execution to a JavaScript object and also for providing some data persistence to a static website.



That was easy. The Rasta class has one instance variable, called "rasta". Instance attributes are private in Smalltalk, you have to implement methods if you want to access them from the outside. But in this case, our rasta attribute is for internal use, we don't need the stinky accessors. The Rasta.js API provides two simple JS functions:

Rasta.get('age', function(val){
/* val == '100' */
})

Rasta.set('age','100', function(){
/* */
})
Since they use an upper cased name, and in Smalltalk those are reserved for classes, we have to use a special trick. Jtalk will get confused if you try to evaluate "Rasta" directly. This not happens with lower case JS names, which are available directly in the Jtalk IDE (you can try
console log: 'fooBar' for an example in the Workspace.) So, we will use our "rasta" instance attribute for storing the JS object, we use the <jsobject> notation for getting a sort of proxy object which will delegate messages in the JS one, and we can access it under the "rasta"
name in our messages. Now we can use the Rasta.js KISS service for our data storage:
database := Rasta new.
database get: 'aKey' onSuccess: [ :data | 'div#container' asJQuery append: data ].

Ok, usualy you will want to format the data. We can wrap this into a Widget subclass and implement a #renderOn: method. At this point we can put all these features together in our mind: you get a nice programming environment which promotes good code practices like layers and concerns separation, clean and readable syntax, testing facilities, and who knows
what, with an IDE accessible directly from the browser.

On code persistence

I will just say it. If you press "F5" (or "r" if you are a hacker) you will lose your code. The IDE features a "Commit category" button, which sends a PUT request with the compiled ST in the body. But as Jtalk is focused in client side coding, it is your responsability to handle the
request and save the code into the "js/" folder, next to the Jtalk library. I will show you the "almost pseudo code" thing again, with Flask and Python:



Note that I used the secure_filename from werkzeug to sanitize the data, since I use it to build the path. You don't want to allow write to your .zshrc or similar.

Concluding

Jtalk can help you to write heavy client side applications by taking advantage of the ancient wisdom from the Smalltalk world. It still has some sharp edges but it is there for you to try it. Allows you to write stateful client code easily, and to port known and tested patterns to
the web browser, for great justice. And there is a plus. Jtalk is part of a legendary story, the Smalltalk one. After all, I have told you, these guys came from the leg of a god.

A moving target

In the couple of days that Rodrigo Bistolfi and me have been experimenting with Jtalk and writing this article (In fact he wrote most of the article), a bunch of things changed already, or are going to change shortly. For example, Capitalized Javascript objects are parsed now without problems in Jtalk. On the JQuery side, Nicolas Petton recently said that JQuery binding is going to disappear from jtalk bundle. It seems we'll be able to fetch DOM nodes directly with jtalk. So better be up to date with the jtalk git repo, because jtalk is moving fast.

Btw, there's a lot more related to Jtalk. Goran Krampe wrote jtalkc, that compiles jtalk code to js able to run in node.js. I haven't digged on that yet, but seems it also opens a shitload of possibilities... :)

Cya!

jueves, 1 de septiembre de 2011

more git workflows. Getting closer to sanity

Toady, a new article of git workflows appeared in HN. The nice thing of it is that at my workplace, we use exactly the same workflow. I just post it here for future reference

And now that we're at it, I link another git workflow related post that talks about merge --squash. A nice thing to make your history cleaner

Btw, I recently discovered a couple of interesting git man pages: gittutorial and gitworkflows. Interesting information there too.

martes, 23 de agosto de 2011

ESUG in: 2011 on: Edinburgh



ESUG 2011 is over, and I'm back from my holidays, with a couple of interesting bits about the smalltalk world, and lots of energy.

Here are the talks that impressed me most:

- Martin McClure explained Maglev smalltalk to ruby ffi. It seems maglev is more than a simple smalltalk vm. In fact it runs ruby code and smalltalk code seamlessly (at least, that's what I understood). Unfortunately, it only exist in 64-bit shape, so I couldn't try it myself. The core of the presentation though was the nice FFI that VMWare guys (former GemStoners) prepared to run Ruby code from Smalltalk.

As most of you know, Ruby is heavily influenced by smalltalk. In fact, so much that Martin and friends were able to make one object for both worlds. So String class is the same for ruby and smalltalk. Objects are the same, but the names are different, so SmallInteger for smalltalk, is fixnum for Ruby. 'super' pointer is also different, enabling to build variations in hierarchies and supporting singleton classes for ruby.

Lots of nice tricks that enable us to use ruby objects as smalltalk ones.

- Bifrost. Jorge Ressia is implementing great improvements in the reflexivity side of Pharo. Being able to treat data as code is one of the aims of bifrost. Not losing the link on logs and where a log entry comes from, or being able to hook on variable usage when debugging... Thanks to Bernat I was able to try it in my own pharo image. (Bifrost is only the framework, you have to install the programs separately)

- Jtalk. I think this was the killer talk of this ESUG. Goran Krampe and Nicolas Petton presented their (mostly Nico's) smalltalk implementation in js. Running smalltalk in browser is not only being able to write smalltalkish syntax. It means you have a full stack smalltalk in your browser. Many firebug features will come for free in Jtalk. Goran showed some experiments he's doing with node.js and jtalk compiler to js. Yes, you're able to write smalltalk for the server side. Probably I'll post more about jtalk, so keep tunned.

There were a lot of other interesting presentations, like Gerardo and Javier live garbage collection tweaks(writing garbage collectors in smalltalk and rebinding garbage collector on your live system), redline (smalltalk in your jvm) and Coral (pharo for those who can type).

It's great stuff all way down!

domingo, 21 de agosto de 2011

Cellular automatas and me

2 weeks ago I started to read Philosophy and simulation by Manuel DeLanda (thanks eskerda).

About one month ago I watched jdelgado's talk at Campus Party talking about science in science fiction, and he talks a bit about cellular automata too:


So I started to experiment a bit with cellular automatas myself, and implemented a Conway game of life in smalltalk. At first I wanted to write a very flexible (1d,2d,...nd) cellular automata engine, but once I had the 2d Game of life implemented, I realized that doing 1d things is easier if you do it with strings, or just lists (lisp lists, for example).

Well, so I implemented a 1d cellular automata in common lisp (nice exercise) and tried some interesting rules for the majority problem jdelgado mentions in his talk.

At first I thought majority problem had a defined proper solution, but searching on the internetz, it seems it's not trivial at all, and I couldn't find anything that takes me further than rule 184, that splits the list in a group of 0's and 1's.

If you want the implementation of the smalltalk GoL, ask for it (it's not that easy to paste smalltalk code on the web, you know...), or just download any already existent implementations on squeaksource, like Bernat's one.

martes, 16 de agosto de 2011

git push -f to master and you're a dead man

Just came back from the half of my holidays, and came with a quite long TODO list.

One item of the list was a wrapper for git that avoids pushing -f the master branch.

At my new $job (yes, I changed again, you'll be noticed properly when I have more time to write), we use a minimal version of git-flow and we run tests on remote (personal) branches.

That means that sometimes, you have to git push -f to your personal remote branch, and possibly delete history. There's no problem if you do it in your personal branch, but as dumbans we err, and myself, being new to all this git fancy stuff, I was a bit worried about it.

I've come with a solution that should work fairly well and transparently. A wrapper for git that nops dangerous commands.

It's perl, and here it is.




Despite being destructive, I like the equals method, kind of lispy, but using shift as a car/cdr solution.

To make the wrapper work, rename it to 'git', make it executable, and put it somewhere in your path, before /usr/bin/git executable.

martes, 9 de agosto de 2011

Back to the future. Xerox PARC innovations.

From time to time. I spend an afternoon doing some monographic research of a great Computer Scientist, or simply people I've seen some day in TED, and would like to know more about him/her.

Sometimes it's Joe Armstrong, sometimes it's Guy Steele, but Alan Kay and friends take these afternoons more often than others.

Here are 3 Conferences by Alan Kay and one from Dan Ingalls. Those two men (and their collegues at Xerox PARC) have done probably more for our field than any other single group in the 70 years of history of CS (or call it tinkering, or computer tekne)


Alan Kay at TED talk, sharing his ideas about ideas. 2007


If you liked it (you SHOULD like it), here you can see a longer talk about Alan's last work (STEPS)

Here's Dan Ingalls talking about his work at PARC Place. Great stuff too.
And another Kay's talk about great innovations of the 60's and 70's. In XXI century, we haven't exploited many of these ideas yet.
If you know of other related talks, please, put links in comments.


lunes, 18 de julio de 2011

More presentation tools

A little reminder of a couple of tools I should try for my next presentation (tbh, I don't have any presentation in near future, but..)
We'll see when someone writes org-mode + shower helpers.

sábado, 16 de julio de 2011

open rails files from console to $EDITOR

You're in the console, run rake test, and appear a bunch of file paths cluttered with line numbers, colons, and no spaces between them. Well, lest turn the no-space-between them thing in a WIN for us.

Errors and failures show in different formats when running tests (not a very *intelligent* thing if you ask me, but...). Well, a simple regex and we have 'pe' , powered-emacslient, path-edit, or whatever. In my shell, double click any of the two versions and 'pe ', and you're sitting again on your editor. placed in the correct line.

.. app/models/bar.rb:88:in ..
.. [test/unit/foo_test.rb:9]: ..



'e' is the original emacsclient script I use for other files. Unifying both scripts in one is left as exercise to the reader.

I want to spend an afternoon hacking a urxvt plugin to fetch for strings ressembling paths, and be able to open them using just keyboard, but that's a thing for another day.

jueves, 14 de julio de 2011

Sending links when you cannot send files.

I've been reviewing my ~/bin directory and felt like sharing some of the little scripts there.

Today, here's a little Perl script that helps me when having to give a file (screenshot or something) to someone @work. Most people do it by mail, or using jabber protocol. Unfortunately, emacs-jabber does not allow sending nor receiving files, and opening mail client and attaching files is waaay to slow and boring.

The way I work with this situation is having a simple http server in my computer, and moving the file there. then, I paste the link to my coworker, and he/she just has to click it and download.

The http server lives inside emacs. Oh yeah, that's irrelevant. But I had to say it.

Well, here's a script I wrote in 2 minutes.



Hashing the name is to avoid name guessing. I think I got this idea from a Mark Fowler's post that was doing something like this with dropbox.

miércoles, 6 de julio de 2011

Snapshots motherf*cker, do you speak it?


Today, I'll just snap a recipe for a use case that starts to crop up when evolving from a total git beginner to not-so-noob-git-user. git reset

Here's the diagram:



Ok, now screw it.

The main problem when thinking about how git works is thinking in the wrong way. You've been told hundreds of times that git works differently from EVERY other versioning system around, and you keep forgetting these concepts every now and then.

The diagram before is a diagram of where git moves your changes when you do a given reset command. git reset --soft foo moves the changes from commit 'foo' till HEAD to the index.

YOU'RE THINKING IT WRONG.

Remeber that you've been told that git records only snapshots? Well, think about it. When you want to reset your repo to the past, if you have a clean working directory and index. HEAD,index and wd are all in the same state. That means that All trees contain the same. THE SAME. If you are thinking that your wd has some files, that the index is empty (Delta is null) and same (or kind of) for the repo, you're thinking it WRONG again.

Now, if you go and look git help reset, and this MJD's post about git reset.

Then it's kind of easy to understand what it does, and in which state will leave your repo, index and ass.

(take the italics notes as if you just reseted the most recent commit, if you reset to older ones, all changes are accumulated)
  • git reset --soft just updates your HEAD. Changes are in the stage, ready to be commited without that nice 'fdsajflkdsajflkasdf' commit message. You're in the moment before you commited.
  • git reset --mixed updates your HEAD and your index accordingly. That means that probably, if you're reseting to past commits all changes from the target commit till now will be only in your wd. You're in the moment before you added files.
  • git reset --hard updates everything. You're in the moment after you commited the commit (O RLY?) so you lost everything you did after the commit.

Btw, Take all this post with a grain of salt. I just had an 'AHA!' moment I had to share. Probably it's not *very* technically accurate. I haven't even tried what happens on detached heads and other bizarre situations... yeah, I'm a sucker.

man git-reset contains lots of tables and info, but IMHO, naming the states of files A B C D lead to harder understanding that if they'd have been D C B A.

And now, a doubt for the lazyweb:
git reset hard does not allow you to recover your state. gitk --all does not show anything from HEAD on. but git reflog does show it. And I'd swear gitk --all worked 2 days ago....

Addendum: Here's a great article on git reset that appeared a week after my finding. Really well explained, with graphics, tables and everything.

domingo, 3 de julio de 2011

El trabajo del futuro


Via RaulGB, veo que hay empresas tan avanzadas a su tiempo, que vienen del futuro, como la rubia de la lejia, o Levi Strauss con un Delorean, o H.G.Wells.

Me guardo la oferta, espero 3 años, me pillo una time machine, que seguro que estaran inventadas por entonces, y vuelvo a por el curro.

Esperad mi llamada el martes que viene. De vuestro tiempo.

sábado, 2 de julio de 2011

Resize window in emacs

I use emacs as much as I can. That's not really news, is it?

One of my use cases for emacs is chatting with friends. I use erc for IRC, and emacs-jabber for everything else.

One thing that annoys me a bit is that when my screen is split in two and want to shrink a bit one of the two windows.

There's c-x - (shrink-window-if-larger-than-buffer) but it's only useful for a handful of situations (IMHO)

Here is a little function I wrote to shrink a window to selected region. I find it useful to narrow windows to functions, paragraphs, or just narrowing a chat window to just 5 or 10 lines.



Select a region, and run it. Then c-l to recenter accordingly.

I mainly use it as a more visual narrow-to region.

Have fun

lunes, 27 de junio de 2011

read-only weekend

Pretty nice weekend:

Thursday night, a 'Gifted' concert with many of our friends attending.
Great St.Joan party.

From Friday to Sunday I didn't program anything but read a couple of
books. Yes, two. It's true both were quite easy reads and not very long.

One of them is OReilly's 'The productive programmer'. I found the
book a really easy read, but maybe it's beacause I already knew most
of the tricks. In fact I already knew I'd already know most of the
tricks. The second part of the book, though was a bit more abstract,
and I could make some use of the info there.

Points I found most interesting:

- Make a living doc. (From commit logs to wiki, for example)

- Learn to FOCUS. (I'll search for csikszentmihalyi's books)

- Composed Method and SLAP.


The other book I skimmed is more a long article than a book: Git Magic, by Ben Lynn.

It's a pretty nice source of info on git. Really concise and to the
point. Mostly beginner, but also contains some advanced tricks (with
the use cases explained), and a chapter on the git low-level stuff
(remember git from the bottom up?)

miércoles, 22 de junio de 2011

Don't quit emacs by accident


Today I read a blogpost by en emacser blogger (tsengf) about quitting emacs accidentally.

He writes a function to avoid closing emacs by accident when there's an opened file that belongs to any of your projects.

My approach is somewhat different:

Usually, when I have emacs opened, I have some processes running within it. That makes emacs warn me when I press c-x c-c by accident, and asks for confirmation (the same way as if I had unsaved buffers)

Anyway, sometimes my muscle memory screws everything, and presses 'y' without asking my conscious mind.

Here are a couple of solutions that work to some extend.

The first one is the radical one. Just do not shut up emacs. Yes, as strange as it seems, I rarely have to close emacs while my computer is on.


global-unset-key c-x c-c


Then you have to exit emacs with the name of the whole command save-buffers-kill-terminal


As a not-so-radical solution, my bet is for desktop-save to save every session in your home directory.


(defun desktop-save-main ()
(desktop-save "~/"))
(add-hook 'kill-emacs-hook 'desktop-save-main)


Then, if you want to recover the state of the previous session, you have to eval (desktop-read) or (desktop-read "~/") if you aren't on your home dir.

If you had sql sessions, erc sessions, or any other comint buffer... well... you lost them.

PS: If you happen to know how to make this blog/post appear on the emacsen planet, please comment, or mail me, or twitt it to some emacs aggregator.... or just twitt the post FEED ME MOAR RSS's!

jueves, 16 de junio de 2011

sleepsort for the lulz

Today I discovered a programmers' BBS on 4chan (It hit HN's front page).
There was a post talking about a sorting algorithm that the author called it 'sleepsort'
I couldn't believe I didn't thought of it before. In fact in a past post talking about Parallel::Iterator, I played with timers too.... I was sooo close :)



Lots of lols reading the full thread, with comments, optimizations, translations to other languages and puns there.

For example:

- complexity of the algo: O(highest_value_in_input)

- 40: Someone email this to Knuth.
- 41: >>40. Knuth doesn't do email anymore


Have fun.

martes, 14 de junio de 2011

vim.orthogonality > emacs.orthogonality

I already mentioned this same thing in other posts, but well, today I stumbled upon another example of it.

Vim is like a unix commanline, lots of little commands you can combine one to each other. It has the cognitive style of linux command line

bufdo,argadd,argdo... These are the 'pipes' of vim. multiplicity enablers that add functionality,commands and power in an exponential way.

When writing ReST docs to take notes at university, I used Vim, and I got used to underline titles with an add-hoc sequence I made up (yank line,paste,visual line, replace, char) . Vim doesn't need a specific command for it, because it's immediate, and like most vim combos, it's like talking to it in a funny slang.

On the other corner, emacs: as part of emacs-goodies (ubuntu package with a bundle of emacs plugins) There's under.el. A plugin that exports 'underhat-region'. A function that underlines a region with caret characters. The bad thing of underhat-region is that it's not parametrizable, but that's not the point. The fscking point is that in emacs you end up stumbling upon functionalities that are already there as commands, but probably sunken among zillions of other commands.

I'm more a vim-style guy myself, but couldn't resist emacs+vimpulse combination. I think I'm sold.

martes, 7 de junio de 2011

PAIP, special edition




I recently bought a copy of PAIP in dead tree format (as usual, a used one). When I received it, I was a little worried about the state of the book (it was expensive enough to be worried about it). I opened the package, glanced it and seemed pretty good. Nearly unused.

But when I opened it... OMG! The fist page contains a note from Peter Norvig!

FUCK YEAH!

lunes, 6 de junio de 2011

js can be fun(ctional) too. A new hope

Reviewing my latest gists, I re-discovered one in which I copied a js snippet that implemented foldr, one of those great higher order functions. As a proof of concept, I implemented some of the functions on 'Why functional programming matters' paper. In fact, I reimplemented nearly all builtins.scm (from my Half Assed Scheme implementation)



I recently took a quick look at coffeescript, and it seems very promising. Unfortunately, I didn't even try it (just the online interpreter). Maybe when I try rails 3.1

miércoles, 25 de mayo de 2011

Undo layouts in emacs

Once you're used to being able to undo and redo window layouts in your windowmanager (hello ratpoison!), You feel the need to have this same feature everywhere.


;;; winner-mode
(winner-mode 1)
(global-set-key (kbd "C-x 4 u") 'winner-undo)
(global-set-key (kbd "C-x 4 r") 'winner-redo)

martes, 24 de mayo de 2011

Slime configuration for common lisp

I recently bought a dead tree copy of Norvig's Book PAIP, and plan to dig harder on common lisp environment.

To set up a correct environment, there's emacs,slime and an implementation of common lisp. sbcl is my choice, for no big reason. It's just one of the free implementations.

Slime configurations are endless, but here's a decent one that mostly works for me.



Ah, there's a surprise in the book. I'll show you in a future post :)

lunes, 23 de mayo de 2011

Smalltalk tutorial on IRC

Last week at #emacs-es on Freenode I did a very-short-and-introductory-hands-on-workshop on smalltalk. Just in case you know spanish, here's the log, with names removed to protect the guilty.

martes, 17 de mayo de 2011

Ratpoison bindings without prefix key

My window manager of choice is ratpoison. It's a really minimalist tiling wm heavily inspired by gnu screen. As such, it has a prefix key (c-t by default) and most of the bindings mimic screen ones.

At work, I recently discovered that my boss uses ratpoison too (my project manager uses xmonad, great team, isn't it). He uses ratpoison with a different configuration scheme, banishing prefix key, and using definekey at toplevel for every command.

I'm not sure whether I like this configuration or not, but I'm going to try this for a few days, and see if it works ok or what. I've written some lines to enable toplevel bindings using the super key.

Avoiding c-t as a prefix key has its advantages, but now, 'super' key chords are all clobbered by ratpoison. We'll see how it works out.

Smoke Driven Development

He pensado que podríamos usar git
Con un poco de scrum y si aprendo TDD lo tenemos hecho en dos semanas
Un par de branches, un par de slots
Dos cartas porahi, un coaching porallá
Y despues, fiesta de final de proyecto, cardhú, putas y farlopa. Pago yo.

-- Alguno que yo me sé --

martes, 10 de mayo de 2011

latex code listings in org-mode

I already talked about inserting code listings in latex some time ago. At @work
(in a ruby meaning, not a perl one), I try to write as much as I can
in org, and then export it to html, or pdf.

org-mode is fully capable of assisting you when writing code listings,
and it will export them with fancy syntax highlighting. When exporting
to html, it uses htmlize (emacs-goodies if you're in ubuntu). But when
exporting to LaTeX, things are not so straightforward. Of course,
there's extensive documentation, but sometimes, you just don't want to
read through hundreds of details. You just want something that
'WorksForMe (c)'.

(setq org-export-latex-listings t)
(add-to-list 'org-export-latex-packages-alist '("" "listings"))
(add-to-list 'org-export-latex-packages-alist '("" "color"))


I don't know if it's enough or there's another configuration related
to this sunken in my .emacs (now 609 lines long), but you know... It
WorksForMe.

viernes, 6 de mayo de 2011

Technologically impaired office



Ok, I've already spent too much time trying to write a doc in openoffice to acknowledge that most of general user-friendly apps are for total technologically impaired ducks. It's not that there are no shortcuts for everything, its much more simple than that.

Every single function has a button for it. You want to indent a paragraph, ok, there's a button for it, outdent, another button... The fscking problem is I'm not in the mood of looking through all the buttons of all toolbars until I find it. And guess what? Selecting a paragraph and pressing tab, just blows you paragaph away and adds a tab.

My Technologically impaired solution.
foreach @line {press(tab,↓,←)}

Popups are the root of all evil. Well, openoffice will nag you when the cursor is on a table, a numeration, or god knows what.

Nested enumerations with styles, another shitstorm.... Copypastable formatting, font, background highlight and all the unwanted persistency of a place-and-format. You will get signs from the past red bold letters that lived in the place you're editing 3 centuries ago.

For this and much more, I declare myself technologically impaired.

martes, 26 de abril de 2011

Perl, paths, local::lib and why I got stuck for a week

When writting ratfinder2, I started testing it in console, and when the main structure kind of worked (the plugin system is for Yet Another Post(tm) ), I wrote the gui stuff, and plugged alltogether. Everything worked ok when run from console. but if the program is executed directly through a ratpoison binding, the script didn't work.

After some debugging time, and nothing seeming to make sense, trying && failing while(1..Inf);... the solution is here.

The thing is that when executing the perl script directly, .zshrc doesn't get executed, so the path isn't added. Be able to run the script we can use 'use lib "/home/rgrau/perl5/lib/perl5";', or otherwise call the script with the -I flag setting the appropiate path.

I suppose if you bind an icon on gnome/kde/windows to a perl program, you should be aware of that, and bind the icon to the appropiate command.

so now, my ratpoisonrc line is like


bind j exec perl -I/home/kidd/perl5/lib/perl5 ~/bin/rat-finder.pl
bind C-j exec perl -I/home/kidd/perl5/lib/perl5 ~/bin/rat-finder.pl


I know it seems obvious now, that you should tell your perl where the modules are, but once you forget about local::lib.... It can't be unforgotten :). The opposite of THIS

martes, 19 de abril de 2011

Open2 for dummies

Some days ago I started rewriting ratfinder, and I'm trying to make it cleaner, smarter, more extensible, and (why not) have more fun programming it.

The language of choice is still Perl5, because I'd like to keep in touch with the language, and keep learning new tools and libs for it. Ruby is ok, but honestly, if we're not talking about god's purity (those two old languages), Perl is my favourite bitch.

The first design decision was to make it extensible via a plugin system, where you provide a couple of methods, consume a role (Moose, yeah), and ratfinder2 will do 'the right thing'(tm).

I'll talk about the plugin system in another post, but today, I had a simpler problem (at least at first sight).

One of the multiple ways to spawn new processes in perl, is using the super-duper-overpowered-open primitive, with a pipe attached into the name of the process. I still remember One of Casiano's example on it. Quite mindblowing when you first see it.

But what happens when you want not only INput OR OUTput pipes but INput AND OUTput pipes for a process?

Hey, it's Perl, you know man, TIMTOWTDI. IPC::Run, Capture::Tiny, IPC::Cmd.... but the standard way is, for the moment, IPC::Open2.

It's usage may be trivial for you, but for me, the doc is a bit behind the times, as it uses GLOBS for handles, and the examples didn't clarify much for me.

The key concept for me is knowing that the whole thing works when your write pipe is closed (at least it seems so), so if you can't make your host process close it, you should close it by yourself.

Here's the part of relevant code in my Dmenu.pm



As usual, everything is public, undocumented, buggy, and it's on github.

lunes, 4 de abril de 2011

What you can't see CAN hurt you (or, at least, annoy you)



Most of the times, and programming in sane (cough, cough)
programming languages, things like whitespaces, tabs and newlines
won't do you much harm. they work as separators for tokens (unless
in a string).

But that doesn't mean that you can't get trapped into some gotchas
related to whitespaces or newlines. One example everyone has dealt
is lineFeed vs carryReturns vs CRLF.

There's a funny article from fxn on O'Reilly site talking about
the secrets and gotchas of newlines.


As a long time vim user, and nearly a year of using emacs (with
different intesities), I care a lot about my editor features, and
one feature that's really useful is the 'select paragraph'. Both
emacs and vim can do this out of the box, but there are some
problems when you aren't careful enough and leave apparently blank
lines that are full of spaces, tabs or any invisible characters.

In vim, you can delete all trailing whitespaces with a simple
regex. Of course, you can create a command to do it for you, or even
map some keybinding to execute %s/\s\+$// , but I'm ok with typing 10 chars for it.

In emacs, of course there's a command for deleting trailing whitespaces, and, guess what?
it's called delete-trailing-whitespaces :) .

If you want emacs to show trailing whitespaces, there's a buffer-local variable called
show-trailing-whitespace that you can set to true. Here's the official emacs doc

Emacs has a command called 'whitespace-cleanup' that bundles some sane (configurable) rules to clean most annoyances related to whitespaces.

viernes, 1 de abril de 2011

Modern Perl Toolchain, dip your toe

Yesterday, we had another Bcn PerlMongers meeting, and AlexM showed us some nifty tools he's using in a project he's into.



Basically these are what in the perlsphere is called Modern Perl Toolchain.



Forget about cpan asking tons of questions, forget about only one
location for modules.


With the help of:




And some plugins for dzilla, you get isolated perl instalations, with
their own modules (@INC), and a trully easy maintenance of
Boilerplate. In fact, it's as easy as it can get, because, you don't
have to do any dedicated maintenance for them.


I had tried some of the old ways to package apps, and so, and when I
saw the power of these 3 modules (I had already used cpanm, but..), I
felt we got an autoshaving yak.


Here are the slides that AlexM kindly uploaded today.


During the talk, some modules arouse to the conversation, and I
took a look at some of them:



similar to Casiano's Remote::Use, but probably easier in its usage. a big win.


That's the killer one for me. It hooks on die signal, and spawns a
REPL and you have then access to the whole environment. Great great great.


If you want to set 'breakpoints' you can hook warns instead of just exceptions.


And another cool feature is that you use it just enabling it from the commandline


perl -MCarp::REPL

martes, 22 de marzo de 2011

Managing the unmanageable with git

After 2 months using git regularly, there are a couple of things that I'd like to comment here, just for further adding on other posts.

Mostly, for me there's a first blocker that is understanding how the global thing works. To solve this, I can recommend git from the bottom up. a great introduction to git written quite differently from most other docs that want to explain the same. Understanding the low level stuff helps you getting intuition, and IMHO it's essential to get this kind of intuition when using such holistic systems.

Most tutorials give you the essential syntactic information that you can get from man (btw, man git-whatever will give you lots of info), but for me, knowing the workflow and how-to think gittish (or thinkgit if you prefer) is what bothered me most of the time.

You probably have heard about nvie's git workflow. I haven't tried it yet, and at work we use a simpler workflow based on a remote master branch, two local branches (master,working) and quite centralized flow.

Not being a git power user (I'd say I'm just scratching the surface) I'm going to write a couple of posts that are what I'd have needed when I started with it seriously.


Checkout - what happens when you checkout
Clean - oops, I think I messed something
Stash - Smashing the stash for fun and profit
Rebase - commit -am 'fdsda'
Bisect - It's always been that way NOT!


If you have suggestions or something to add, I hope you will comment. Remember, I'm learning as I write these posts, so you can and MUST collaborate!

lunes, 7 de marzo de 2011

Perl Higher Order Functions

I've been chit-chatting with a friend who's learning Perl5, and has written some little apps for his own needs. While reviewing his code (not that I'm a programming guru, but I help with what I can), I talked about Higher order functions, and we ended writting some throwaway code to explain the idea.

To clarify the concepts, I wrote some trivial scheme functions-as-data munging in scheme, and translated them to Perl.

What surprised me, was the "wow!" comments about concepts that aren't perl unique features, but general higher order procedures. Certainly, Java and C++ are 'a bit' behind Perl, Ruby, or Lisp, but it's fun to remember how mind blowing are these concepts to newcomers. I discover mind-blowing concepts quite frequently too.

We had a good afternoon, reviewing code, Quines, concurrency, talking about GEB (The book I'd take to a desert island along with SICP)...

Here's part of the code we've written (as a reminder). Nothing useful, but tiny proof of concept of HOP. Ah, btw, I recommened him to read chromatic's Modern Perl book. I recomend it to all of you in the Perlsphere. Great book.

domingo, 6 de marzo de 2011

Window navigation on Emacs

Last week I was talking about some emacs features with a coworker (while talking about General User Interfaces, pros and cons of WIMP), and ended with the doubt whether there is a way for easier window navigation on Emacs, or c-x o is the only way to go.

I talked about one of the greatest aid to frame/window navigation of screen and ratpoison, that is window numbering, and being able to switch to random windows instead of just sequentially.

Well, today I spent some time thinking about possible solutions, and searching for already implemented modes.

Guess what? There are a couple of ways already implemented (in default emacs, or as an extra downloadable package).

Windmove comes bundled with emacs since 21-dot-something, and in fact is what vimpulse uses for the c-w [hjkl] emulation.
(windmove-default-keybindings) ; enable shift-arrow
Expanding the concept further, there's also FrameMove, that integrates seamlessly with windmove. Here's a little extra info about it.

I found a couple of more esoteric plugins to navigate windows, but haven't tried them.
http://blog.lathi.net/articles/2007/11/07/jumping-to-specific-windows-in-emacs explains how to jump to windows by title. I suppose like ido-mode or anything-buffers.

There's also https://github.com/dimitri/switch-window , that seems to bring ratpoison's numbering of frames to emacs' windows. Nice idea. Here follows a screenshot of switch-window from it's homepage.

lunes, 28 de febrero de 2011

Programmer problem solving sequence

2010 developer’s problem solving sequence:

  1. Google
  2. Coworkers
  3. StackOverflow
  4. RTFM
  5. Think

It's funny because it's true.

Via HN -> JCook -> Philippe Leybaert

lunes, 21 de febrero de 2011

run interactive applications inside emacs

While implementing a more decent repl for HAScheme, I stumbled upon a nifty emacs feature: comint.

To run an interactive shell, get history for free, and completion (at least hippie-expand if you teach your emacs to use it), you just have to use make-comint.


(defun run-has ()
(interactive)
(make-comint "has" "/path/to/hascheme/script/lis.pl" nil "/path/to/hascheme/script/builtins.scm"))


the last parameter is the argv, you can fill it with whatever you want. In my case, the scheme file with some builtins.

On the hascheme side, I've been experimenting with tail call optimitzation, an improved repl with multiline support and with some cool debugging features. You'll know shortly about them if you follow this little blog of mine.

Well, and here's a screenshot of the comint buffer on hascheme. note the completion thing on the minibuffer.

martes, 8 de febrero de 2011

(let ((there be)) lisp)

I keep having lots of fun with hascheme. In the last couple of
days, I implemented quite a few things. Mostly they are syntax
sugar for things you could already do in HAS, or useful procedures
needed for my basic interpreter testing.


  • Perl side

    • (define (fun args) body) is now accepted as an alternative way
      to declare procedures.

    • (let) implemented. These bindings for local vars are just sintactic sugar for
      what you'd write in perl:
      sub { my $a=shift; … }->(initialval)


  • Scheme side
    Reread the 'Why functional programming matters' paper, and implemented:

    • make-counter, foldr

    • append, sum-list, length, map . All are specific cases of the previous


Reading chapter 4 of our MIT beloved book, I saw the next step, making a lazy
interpreter from this Half Assed one.

Ah, the repo

lunes, 7 de febrero de 2011

Put more vim into your emacs


I'm a vim editing model fan, but emacs is slowly crawling into my
life. emacs had viper (vi emulator) for ages, but it falls short if
you're a vim power user. Vi is not Vim.



For some time there's been vimpulse package that tried to narrow the
difference, adding Visual mode, and some other goodies. Recently,
vimpulse got reactivated, and now, we get text objects, and many
other features from our beloved text editor.



You can even use map, imap, vmap and the like;



the first thing I tried was mapping jk to esc, but the tip in the
vimpulse wiki didn't work. I managed to make it work with this line
in my .emacs file.



(vimpulse-imap "jk" 'viper-exit-insert-state)



Now, there's no need to reach the far escape key.

viernes, 4 de febrero de 2011

QuasiQuine

Little updates to Hascheme, I finally implemented cons, car, cdr,
and list as primitives, After implementing the prove that you can
have datastructures in a language without no more ground than
lambdas, I went for a bit more of efficiency (not that hascheme is
going to be in production ever, but you know…)



Another motivation to implement lists as primitives is that this
way, I can get a kind of homoiconicity. If conses are implemented
in the implemented language (scheme), a list will never be similar
to code, because Perl never sees the datastructure as something it
can deal with.



And what's the ultimate motivation for having all this stuff
working? fun.



I used a very common lisp quine to test that code and data are
implemented internally the same way. That gave a good testbed for
quote too. Unfortunately, using Perl Data::Dump* modules, I can't
tune how lists are printed, and the final nil gets printed too.



Well, here's the proof that Half Assed Scheme can do Half Assed
Quines.




Next step, testing that closures work. (I'm afraid they don't work quite well)

martes, 25 de enero de 2011

(cadr has)

I've been hacking on HAS a bit more, to push forward its functionality.
Mostly what's been achieved by now:


  • Perl side

    • (repl) primitive implemented. it acts as a debugger in some way,
      because it gives you the environment in the state of the moment
      when you executed it. I couldn't implement it in scheme itself
      because I have no eval available from scheme.

    • Read plain files. As I started implementing some functionality
      in scheme, A scheme file must be loaded at start. just enter the
      file name as a parameter. Last sexp should be (repl) to have
      your repl available.

    • Comments. ';' is the comment marker

    • = operator

    • nil. transformed to 0.

    • list. yeah. As HAScheme can't understand variable length
      arguments, I implemented it to make it more confortable to build
      lists. It's built on an ugly hack. More on that later.

  • Scheme side

    • cons, car, cdr. Implemented basic structures. Implemented as
      lambdas. as in SICP, somewhere in chapter 2 IIRC. Simple though
      impressive IMHO (and inefficient, but…)

    • print_list. conses down a list and prints each element in a
      line

I run it using builtins.scm as the first parameter, and then, repl is
yours, with lists and conses available for you.

Now the not-so-beautiful parts


If I want lists, I just have to nest conses, but who doesn't want a
litte luxury?.

To implement list, I've thought 3 possible solutions (haven't read

about how to implement them correctly, just brainstorming):


  • Variable actual arguments. If I could implement the dot (.) syntax
    for variable number of arguments, I could implement list as a
    simple scheme function. Problem is that I need lists to stash
    the resting parameters (hascheme lists, not Perl ), and I haven't thought how to bootstrap.

  • Write a new primitive (on the perl side) that builds the correct
    cons structures, on the perl side. Mind you, that list is VERY
    coupled to cons implementation. And quite fuzzy on the perl side
    too.

  • Substitute list for the appropiate number of conses (as a string),
    and let the already written parser do the job. That's the one I implemented.

Probably, I'll start from the scratch building another scheme interpreter, following BillHails book. Or at least, I'll go as far as my motivation and brain allow me.

That's all for now. Here's my other post about Hascheme, and the github repo.

Byez.

domingo, 23 de enero de 2011

I can has HAS (Half Assed Scheme)


If you've been reading along these bloglines, you already know I'm on
my way to learn lisp, and given that a typical exercise on the lispers
path is writing a scheme interpreter, I decided to try to impement a
scheme interpreter in perl. I had a great guidance of Peter Norvig's lispy tutorial, and more thoughtful explanations from Bill Hails' book.




I can't say I wrote it as quick as I thought I would, and it could
definately be clearer (OOP in such small projects is clearly
overengineering), but in the end, it works, and given the fact that I
hadn't been programming perl at work for 2 months, it's been a good exercice.



The relevant code is in 4 files,


  • script/lis.pl (REPL and primitives),

  • lib/hascheme/Reader.pm (Parsing)

  • lib/hascheme/Env.pm (environment, a tree structure built on hashes)

  • lib/hascheme/Evaluator.pm (special operators are treated here, and overall evaluation)



Anyway, here you are, the code is in a github repo. For now, It's
called half assed scheme, or hascheme, or HAS.

Related article: next post on HAS


Now, you can has HAS too.