Results tagged “coding” from The Cattle Grid

Using the Dojo loader to include your own JavaScript module is very handy, and also works around several problems related to loading JavaScript code directly via the <script> tag. Often, however, you want to be able to load your modules across domains, so you need to write them in xd fashion. In itself, it's not a big issue as, with Dojo 1.2.0, a non-xd code such as this:

(function(){
    dojo.provide("cryo.Tree");
    dojo.provide("cryo.ForestStoreModel");

    dojo.require("dijit.Tree");
    
    dojo.declare("cryo.ForestStoreModel", dijit.tree.ForestStoreModel, {
        // class definition
    });

    dojo.declare("cryo.Tree", dijit.Tree, {
        // class definition
    });
})();

just needs to become as follows to work with the Dojo cross-domain loader:

dojo._xdResourceLoaded(function(){ return {
    depends: [
        ["provide", "cryo.Tree"],
        ["provide", "cryo.ForestStoreModel"],
        ["require", "dijit.Tree"]
    ],
    defineResource: function(dojo) {
    
    dojo.provide("cryo.Tree");
    dojo.provide("cryo.ForestStoreModel");

    dojo.require("dijit.Tree");
    dojo.declare("cryo.ForestStoreModel", dijit.tree.ForestStoreModel, {
        // class definition
    });

    dojo.declare("cryo.Tree", dijit.Tree, {
        // class definition
    });
})();

Easy enough, but what usually happens is that you work with non-xd files while developing, while using the cross-domain features in production. Or maybe the opposite. Or something similar. Anyhow, in this case you most likely don't want to maintain two copies of the same JavaScript module where only header and footer are different. For sure I don't, so I wrote a small Perl script which converts non-xd modules to xd-enabled ones automatically by performing the following tasks:

  • It parses dojo.require and dojo.provide statements in order to create the xd header.
  • It substitutes the header with an xd one containing the information obtained in the parsing operation.
  • It substitutes the closing parentheses with others which match the new header.

OK, I know, there's also the Dojo Build System, but I didn't want to install Ant and a ton of Java-related dependencies for a task which requires 20 lines of code.

This script is a quick hack so it has caveats:

  • It's a quickly (and therefore poorly) coded dirty hack.
  • Read the code before using it and edit it if needed.
  • It's supposed to work if the code is formatted a bit differently than the examples above, but there's no guarantee - I just tried out some variations.
  • It produces xd code only suitable for Dojo 1.2.0 (but changing it for 1.1.1 is trivial)

On the other hand, using it makes no harm to your existing code: it will either work and produce (possibly broken) output files, or produce no files at all. So, I would say it is safe to try it.

Usage:

make_xd.pl file1.js file2.js ... filen.js

You can pass one or more files on the command line: the script will produce filename.xd.js starting from filename.js, which is left untouched.

Click here to download the script.

If you improve this script, please let me know.

Using reCAPTCHA with Perl

|

You all know: spam is a PITA. It just sucks because if you have a blog users won't like to read it any longer with all that junk. It also hurts if you collect user registrations or other data, as you'll need to filter the collected data and it always changes how software should understand what is spam and what isn't (as spam changes).

CAPTCHAs" have been somewhat a solution for some years. Requiring you to type a word which is in a picture, they should be able to tell if you're a human or a piece of software. First CAPTCHAs were simple and easy to ready, but soon OCR software was able to read them too; so they became more and more complex, featuring noise, distorted words, fancy colours, etc. The art of designing a CAPTCHA is fairly simple: it should be unreadable by a machine and as simple as possible to read for a human, as you surely don't want anybody to be unable to use your web site no matter how stupid they might be because they are unable to figure out a few letters on an image.

Since it's a bit of a pain to always have to change and improve your CAPTCHA images in order to keep spammers outside, I recently began exploring reCAPTCHA.

This article is about reCAPTCHA and is usage with Perl both directly with Captcha::reCAPTCHA and with HTML::FormFu.

Italian Perl Workshop 2008

|

After a year-lasting pause, Italian Perl Mongers are glad to announce a new edition of The Perl Workshop. As usual, the workshop will be held in Pisa. It will take place at the end of the Summer, on September 18 and 19.

Workshop attendance is free of charge.

We're looking for people interested in speaking at the workshop, or simply for talk ideas. Of course, we're also looking for people who just come to listen to the speakers:

This is the official web site, with CFP and other information:

http://conferences.yapceurope.org/ipw2008/

Mastering Perl

|

Mastering Perl
brian d foy
O'Reilly Media, 2007
ISBN-13: 978-0-596-52724-2
US$ 39.99

Rating: 4/5 (very good)

In recent years, O'Reilly pace regarding the publishing of Perl-related books has slowed down quite a lot. This is likely not because of O'Reilly fault, but it's probably due to the fact that Perl is a mature language for which there is a lot of literature which is still up-to-date. For instance, the 3rd edition of Programming Perl was published in 2001 and is still a reliable reference for the current version of the language - even though that is going to change a bit within a few days, with the release of perl 5.10.

Anyway, it seems there's still to write about Perl as a language as opposed to projects or software powered by Perl, and that it what the book is about: the language and how to use it at best. It's a collection of tips, best practices and suggestions, and can fit into the same category as two other O'Reilly titles: Perl Hacks and Perl Best Practices.

Part of this book is devoted to the usual (and important) areas: writing secure and high-performance programs, debugging, error handling, logging and documentation writing. For all of this, several options are usually described by the author, and they range from rolling your own solution using the core perl compiler to using CPAN modules to automate part of, if not all, the work. For example, the section regarding the profiling of Perl programs explains first what profiling is about and illustrates a general approach at the task, and then how to profile database code with DBI::Profile; it then goes to the full-featured solution involving Devel::DProf and closes with suggestions on how to write your own profiler module.

This book can help you organize your applications better. For instance, do you embed your configuration variables at the top of your programs or in an external Perl module? Think of a different approach by reading chapter 11, and start using configuration files (which can overridden with command-line options) as the whole Unix world does - there are plenty of formats to choose from. Using Windows? Use the Windows Registry. Using MaxOS X? Use the plist format. You can do all of this with ready to use modules, and this book explains you how to get started with this.

The most interesting parts of the book lie in it's "niche" chapters, which explains aspects of Perl which are not needed by most programmers, but of which every programmer would surely benefit. Have you always thought that working with bits was something for mad assembly or C++ coders? Wrong! Chapter 16 will introduce you to binary numbers, bit operators and vectors. You might also want to take a look at chapter 6 which teaches you how to make your code clear and how to de-obfuscate other people's code (all right, obfuscation is a virtue, but there should be limits ;-)).

All in all this book can be very useful to improve the way you use Perl (the language) and perl (the compiler), and is a worth reading, which then becomes a nice reference.

The Catalyst hosting web page

|

Finding reliable hosting for Catalyst applications can sometimes be tricky, and choosing bad providers can create several problems to you and/or your company. I therefore started to maintain a page on the Catalyst community wiki devoted to web hosting of Cat applications:

http://dev.catalystframework.org/wiki/annotated_list_of_catalyst-friendly_web_hosting_providers

It's still in the works, but features a commented and rated list of providers for shared, VPS and dedicated hosting. Contribution if open to everybody, so if you have write access to the Catalyst wiki you can just add you providers and comments (if you add comments, put yours as the first and update the rating on the main page). If you don't have write access you can contact a Catalyst dev to get it, or send me the data and I'll update the page.

I hope it'll become a useful resource!

Information age society tends to grab most of, if not all, the time you have at your disposal, and often still asks for more. Since time is your most important resource, you need to manage it aptly, and - surprise - if you are an independent (that is, you work on your own) coder, you can do that.

If the past 12 years of coding on my own, I enjoyed good and suffered bad times. I hereby summarize some practices which work well for me, and which should help you increasing the good moments and decreasing the bad ones.

Perl 6: Junctions

|

I recently began playing a bit with pugs, the current implementation of Perl 6. Junctions seem to be a great feature: among other things, they allow to write much cleaner or conditionals. Here's some Perl 5 code:

#!/usr/bin/perl

for my $num (1..8) {
    if ( $num == 3 || $num == 4 || $num == 6 ) {
        print "$num is ok!\n";
    }
}

and the corresponding Perl 6:

#!/usr/bin/pugs

for 1..8 -> $num {
    if ( $num == 3|4|6 ) {
        say "$num is ok!";
    }
}

The junction can also be created from an array:

#!/usr/bin/pugs

my @mylist = <3 4 6>;

for 1..8 -> $num {
    if ( $num == any(@mylist) ) {
        say "$num is ok!";
    }
}

Ahhh, syntactic sugar... :-) And you can have some it even in Perl 5 with the (lightweight) module Perl6::Junction.

There's a shop now on CafePress which sells some nice things with the Catalyst logo on them, so now I can but a polo and bring my faith with me everywhere. ;-)

By the way, there's also a new Catalyst vs RoR "article".

OK, so you're a coder and you want to work in my company. What would be your favorite working environment? An office where you're all alone, or dot-com era open space?

I started to think about this some weeks ago, as the programmers in my company began to tell me their concentration (and, therefore, productivity) was suffering because of the environmental noise. We have open spaces, we've always had open spaces, and everybody seemed to like them. But then, until recently, I was the only programmer, and I usually work on my own, buried into my home basement instead of the main office. I wanted to discover how this problem is solved in the Valley, and it turned out they use offices, or at least cubicles, and no open spaces at all for programmers: no more, now that the dot-com era is over.

In the end, two important truths surface:

  • Anyone who needs to concentrate can't stay in a place where other people come and go, talk, listen to music (from different sources at the same time, maybe).
  • A coder needs to concentrate.

Open Spaces Are Evil For Coders

A tear for the Turbo compilers

|

It seems the Turbo compilers are back, and there's even a free version of them. When I read the announcement, and saw the photos of the boxes so similar to the ones of the beginning of the 90s, I was about to drop a tear on the keyboard for the comeback of the products that inspired my first efforts at coding, as well as those of almost all my generation.

It's maybe too late for Turbos to gain momentum again, but they could appeal to younger coders especially in the free Explorer version (the Professional is not that expensive, anyway). I would find Turbo C# useful for the applications I write, but unfortunately it's Windows-only, as Borland decided to drop the Linux versions of their compilers and to stay on the Windows side.

When the first generation of Turbos came out, Borland was innovative, while now it seems it's following the steps of others (i.e. Microsoft, which also features free IDEs) with some delay. Making their products available to non-Windows users as well would probably mean innovation again, let's see if the new Borland has the guts to walk that way...

I wrote something about SQL::Abstract in this recent article, so I will now show the features of a small module which works perfectly well with the above mentioned one, but also without it: DBIx::Simple. This package provides a nicer interface to DBI, and allows to use SQL::Abstract to build queries (but does not require it).

DBI works just fine, but it sometimes gets boring to write the code which uses it: most of time you have to prepare_cached your query and then execute it; to retrieve the data you have to use fetchall_arrayref or one of the similar long-named methods, often passing them the needed parameters. DBIx::Simple makes all of this... simpler. For example, if you need to fetch some rows into an hashref you just write:

use DBIx::Simple;

my $db = DBIx::Simple->new(
    'dbi:mysql:database=mydb;host=myhost', 'myuser', 'mypass'
);

my $res = $db->query(
    'select id, username, address from users where role = ?',
    'customer'
);

my $rows = $res->hashes;
wAddress
I recently stumbled on the Making Wrong Code Look Wrong article, which reminded me about the Pascal coding I was doing with my friends on MS-DOS and Windows 3.x back in 1993. At that time we were using Hungarian notation widely, partly because of studying on the mythical Programming Windows book by Charles Petzold; now, reading this article, I finally understand that the notation we were using was not the one meant by Microsoft's programmer Charles Simonyi (who invented it), but a far less useful variation of it used by many coders, including Petzold. We were having a lot of fun, anyway!

Now Hungarian notation is not used anymore, as it's even discouraged by Microsoft. However, reading this article is a must-do for every coder, especially for the nostalgic ones. ;-)

You can probably figure out easily how to make a plural of a word in the English language, and when to put a or an as the indefinite article. However, it's not that easy when you need to do that dinamically on words provided by an user or coming from some other source. Also, you have no elegant way to automatically print something like this:

Your ranch contains no cows.
Your ranch contains 1 cow.
Your ranch contains 4 cows.

with a single print statement. Lingua::EN::Inflect provides all these features, so it allows to write proper English plurals even when you don't know the words you have to inflect. Just say:

use Lingua::EN::Inflect qw/:ALL/;

for my $n(0, 1, 4) {
    print 'Your ranch contains ' . NO( 'cow', $n ) . ".\n";
}

The output of this code is exactly the text shown above. Even though this is a very useful feature, Lingua::EN::Inflect offers many more utilities to work with plurals in the English language. Keep on reading to discover the gory details.

I don't even know how many SQL statements I wrote in my programming life so far. Embedding the SQL into your code, whatever language you use, makes it less readable, uglier and - especially if the complex queries - particularly inelegant. Even when coding in a MVC fashion (which is highly recommended in some cases, like web applications) you end up to just moving the ugly code to the model part of your program, while removing it entirely would probably be the best choice. The problem is that you actually need to query the database somehow, so you can't remove the SQL code; however, you can put something else in place of SQL statements. Let's see what, from the point of view of a Perl programmer of course. ;-)

There are modules which allow SQL abstraction by generating SQL code from data structures. They let you use an arbitrary complex structure to build an arbitrary complex query without inserting any database-related code into your Perl program. Note that this is different from what ORMs - Object Relational Mappers - do: the latter abstract the SQL database into objects, while what I'm talking about abstracts the queries. However, a good ORM such as DBIx::Class provides query abstraction as well, usually by relying on one of the modules available on CPAN. You'll probably want to use an ORM, but that's not what I'm discussing here.

In this short article I'll cover SQL::Abstract, which is also the module DBIx::Class uses. It is fairly easy to get used to it to write simple queries, and with a bit of thought also the complex queries can factored into Perl data structures. For instance if you have:

my $query = "SELECT users.name, users.phone, users.email
    FROM users
    WHERE users.id = 1 OR users.id = 2
    ORDER BY id
";
my $sth = $dbh->prepare($query) or die $dbh->errstr;
$sth->execute() or die $dbh->errstr;

You can write this instead with SQL::Abstract:

my $sql = SQL::Abstract->new();

my ($query, @bind) = $sql->select(
    'users',
    [ 'name', 'phone', 'email' ],
    { id => [ 1, 2 ] },
    [ 'id' ],
);
my $sth = $dbh->prepare($query) or die $dbh->errstr;
$sth->execute(@bind) or die $dbh->errstr;

You might protest that the code is longer, and it actually is a bit (even though code formatting contributes to that). It's however much clearer: there's no extra-Perl code around field names and values, and you can easily understand what the query does at first sight. The select method accepts four parameters: the name of the table on which you want to work, the fields you want to retrieve, the where clause, and the optional ordering of the results. You get, as return values, a string containing the query, and the array of the bound values which you need to use when calling execute().

After 3 years of silence I'm contributing again to CPAN. At that time I sent Net::C6Term, useful to write Perl programs that connect to the C6 Italian instant messaging network. However, Tin.It now changed the authentication system so it doesn't work anymore, and I'm therefore removing it.

I uploaded Image::VisualConfirmation, which can be used to create visual confirmation/challenge/captcha images. If you don't know, they are those anti-spam things which - when you submit a web form - force you to copy a text you see in an image in order to make sure you're an human an not a software: you can see one on the right.

There are other modules on CPAN which accomplish this same task (more or less). However, Image::VisualConfirmation is a lightweight wrapper over the Imager module: it creates the image, then you just get it, or get the Imager object and do whatever you want (further obfuscation, save to a file, ...). I hope it can be useful to somebody!

My Catalyst Gentoo ebuilds repository has now layman and gensync support, and it's listed in the official layman XML file.

Even though portage still seems quite far, it's not as impossible as it seemed before to see Catalyst into the official tree soon or after.

As usual, the beautiful HOWTO explains everything.

Threading in Perl

|

[ This is an article I wrote some time ago, so it's in Italian language. It was written in order to be published on a paper magazine-to-be, but then that magazine wasn't born at all. So, here it goes for free. ;-) ]

Questo articolo spiega i concetti principali della programmazione basata sui thread in Perl. Con le recenti versioni dell'interprete essi sono diventati infatti un'eccellete alternativa al forking

Buona lettura!

CPAN has some very interesting Perl module which allow to manipulate images, that is: convert between various graphic formats, resize, rotate, regulate contrast, colors, add primitives, watermarks, and all the such. Imager is one of them, and it's quite interesting as it's stable, easy to use, powerful, and well enough documented.

I created a little program, bdtouch, which makes use of some of the features of Imager. You can download the Perl source code here, or you can read on if you're interested in the explanation of some of its parts

Ruby on Rails on The Register

|

The Register has an article regarding Ruby on Rails, the popular Ruby-based MVC framework for web application development. It's an interview to the author, who explains why Rails is a good choice for most web applications when compared to PHP (on one side) and J2EE (on the other side).

Althout I use Catalyst, which is Perl-based and in my opinion better in many aspects, this article is quite interesting, and RoR is quite interesting too.

Tags

Find recent content on the main index or look in the archives to find all content.

Categories

Pages

Powered by Movable Type 4.23-en