Older blog entries for ralsina (starting at number 694)

Python Trick: the Fundict (or the Diction)

Suppose you have made the choice in the past of exposing a dictionary as part of an object's interface. So, people are doing things like:

object.data[foo]['bar']

And now you want people to not have to specify foo because it can be obtained from somewhere else. In fact, what you want now is to expose something like this:

object.data(bar, foo='foo')

Here's an idea on how to do that without breaking the old code:

class fundict(dict):
    def __call__(self, bar, foo='foo'):
        return self[foo][bar]

That's a dictionary that's also a callable, and thus indistinguishable from a function. A function-dictionary. A fundict. And of couse, you could also do it the other way around, and implement a function that works as a dictionary. A dictionary-function, a diction. But since that's more work, I used this one.

Syndicated 2013-03-08 18:13:41 from Lateral Opinion

Twitter Card Support in Nikola

This feature for Nikola was implemented by @amokleben, and now, if you ask twitter your site can have it too.

What are Twitter Cards? Did you notice that for some sites, when you click on tweets that have links, you get a small preview of the content? Well, that's a twitter card.

This still needs a little improvement to support the richer "media" cards, but it does work:

http://direct.ralsina.com.ar/galleries/random/twitter-card.png

You don't have to do anything in your site, but setting the "description" metadata to your posts helps make this more accurate (and it also works for google+)

Syndicated 2013-03-05 06:31:57 from Lateral Opinion

Nikola 5.4 is out!

I am thrilled to announce the release of version 5.4 of Nikola, a static site/blog generator

Here's the (incomplete!) changelog for this release [1]:

Features

  • Twitter Card / Open Graph support.
  • Smart math support
  • New soundcould directive
  • Custom "read more" links
  • Better time display, timezone support
  • Better doit integration (Issue #151)
  • Make the whole listings folder browsable (Issue #128)
  • New GZIP_FILES/GZIP_EXTENSIONS options to create gzipped copies of some files (Issue #348)
  • New optional path parameter to new_post command.
  • Wordpress importer: option to not download files
  • Wordpress importer: option to squash newlines
  • Separated BLOG_URL into SITE_URL and BASE_URL
  • Added DISABLED_PLUGINS option (Issue #354)

Bugfixes

  • Added missing </div> in default theme templates.
  • Wordpress import: Description is left empty if no description is found.
  • When running the build command it is now possible to get help.
  • Load jQuery before bootstrap in JS bundle (Issue #327)
  • Generate valid HTML5 for redirects (Issue #276)
  • Fixed "nikola check"
  • Fixed internationalized RSS links
  • Make commands that need to be run in a site fail gracefully (Issue #342)
  • Use localized links on lxml fixer
  • Redirections created during the import from wordpress are now written to conf.py
  • Stop parsing metadata in post file on first blank line
  • Metadata handling cleanups by Tordek
  • Fixed blockquote font size inconsistency
  • Wordpress Import: Do not break indentation (issue #189)
  • Make things work even if SITE_URL has a path (Fix #307)
[1]There are also some extra bits of documentation, and a awesome beta theme called "site-reveal" based on bootstrap and reveal.js!

Syndicated 2013-03-04 18:40:24 from Lateral Opinion

Creating a Site (Not a Blog) with Nikola

One of the most frequent questions I get about Nikola is "but how do I create a site that's not a blog?". And of course, that's because the documentation is heavily blog-oriented. This document will change that ;-)

Since it started, Nikola has had the capabilities to create generic sites. For example, Nikola's own site is a fairly generic one. Let's go step by step on how you can do something like that.

Using 5.3?

This tutorial is based on Nikola from github master. Some details are not correct for the 5.3 release. Master works quite well most of the time, but you may want to wait until the 5.4 release in a few days (which will include an updated version of this document).

As usual when starting a nikola site, you start with nikola init which creates a empty semi-configured site:

$ nikola init mysite
Created empty site at mysite.

Then we go into the new mysite folder, and make the needed changes in the conf.py configuration file:

##############################################
# Configuration, please edit
##############################################


# Data about this site
BLOG_AUTHOR = "Roberto Alsina"
BLOG_TITLE = "Not a Blog"
# This is the main URL for your site. It will be used
# in a prominent link
SITE_URL = "http://notablog.ralsina.com.ar"
BLOG_EMAIL = "ralsina@kde.org"
BLOG_DESCRIPTION = "This is a demo site (not a blog) for Nikola."

#
# Some things in the middle you don't really need to change...
#

post_pages = (
    ("pages/*.txt", "", "story.tmpl", False),
)

And now we are ready to create our first page:

$ nikola new_post -p
Creating New Post
-----------------

Enter title: index
Your post's text is at:  pages/index.txt

Note

The -p option in the nikola new_post command means we are creating a page and not a blog post.

We can now build and preview our site:

$ nikola build
Scanning posts.done!
.  render_site:output/categories/index.html
.  render_sources:output/index.txt
.  render_rss:output/rss.xml
:
:
: [Much more of the same]

$ nikola serve
Serving HTTP on 127.0.0.1 port 8000 ...

And you can see your (very empty) site in http://localhost:8000

So, what's in that pages/index.txt file?

.. title: index
.. slug: index
.. date: 2013/03/01 10:26:17
.. tags:
.. link:
.. description:


Write your post here.

Title is the page title, slug is the name of the generated HTML file (in this case it would be index.html) the date doesn't matter much in not-blogs, same for tags and link. Description is useful for SEO purposes if you care for that.

And below, the content. By default you are expected to use reStructured text but Nikola supports a ton of formats, including Markdown, plain HTML, BBCode, Wiki, and Textile.

So, let's give the page a nicer title, and some fake content. Since the default Nikola theme (called "site") is based on bootstrap you can use anything you like from it:

.. title: Welcome To The Fake Site
.. slug: index
.. date: 2013/03/01 10:26:17
.. tags:
.. link:
.. description: Fake Site version 1, welcome page!


.. class:: hero-unit span6

.. admonition:: This is a Fake Site

    It pretends to be about things, but is really just an example.
    So, don't click this button, it leads nowhere.

    .. class:: btn

    Click Me!


.. class:: span5

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris non nunc turpis.
Phasellus a ullamcorper leo. Sed fringilla dapibus orci eu ornare. Quisque
gravida quam a mi dignissim consequat. Morbi sed iaculis mi. Vivamus ultrices
mattis euismod. Mauris aliquet magna eget mauris volutpat a egestas leo rhoncus.
In hac habitasse platea dictumst. Ut sed mi arcu. Nullam id massa eu orci
convallis accumsan. Nunc faucibus sodales justo ac ornare. In eu congue eros.
Pellentesque iaculis risus urna. Proin est lorem, scelerisque non elementum at,
semper vel velit. Phasellus consectetur orci vel tortor tempus imperdiet. Class
aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos
himenaeos.

[And more in the same vein]

TIP: Nice URLs

If you like your URLs without the ".html" then you want to create folders and put the pages in index.html inside them. Example:

nikola new_post -p pages/foo/index.txt

which will create a page you could access as "http://yoursite.com/foo"

And that's it. You will want to change the SIDEBAR_LINKS option to create a reasonable "menu" for your site, you will want to hack the theme (check nikola help bootswatch_theme for a quick & dirty solution), and you may want to add a blog later on, for company news or whatever.

TIP: So, how do I add a blog now?

First, change the post_pages option like this:

post_pages = (
    ("pages/*.txt", "", "story.tmpl", False),
    ("posts/*.txt", "blog", "post.tmpl", True),
)

And to avoid a conflict (because blogs try to generate /index.html:

INDEX_PATH = "blog"

Create a post with nikola new_post and that's it, you now have a blog in http://yoursite.com/blog (you may want to add links to it in SIDEBAR_LINKS of course).

You can see the finished site in http://notablog.ralsina.com.ar and its full configuration in http://ralsina.com.ar/listings/notablog/conf.py.html

I hope this was helpful!

Syndicated 2013-03-01 12:49:41 from Lateral Opinion

Load Testing Nikola

Nikola generates static sites, so load testing it is not very interesting, except as a benchmark for the difference between static and dynamic sites.

Today I was told about blitz.io and since a quick test is free, I thought, why not? The result is quite impressive: a cheap VPS, using gatling as a web server, which is almost configuration-free and not meant for extremely high loads, can handle roughly 9 million daily hits.

Let me say that again: 9 million hits. On a unconfigured $5 server. Here's the report

How much tuning does it take for a wordpress instance to serve that? On what hardware?

And that's only half the picture. Not only are Nikola's static pages incredibly light on your server, we have also spent a lot of effort trying to make individual pages load fast, for a better user experience. Some of the techniques used for fast-loading sites are:

  • Using webassets to bundle CSS and JS into single files.
  • Automatic support for CDNs for the common JS libraries
  • Support for transparently using HTML/CSS/JS/Image compression tools

So, if you try something like YSlow! on a Nikola site, it will give you a score of roughly 93 up to 98 (out of 100) depending on your webserver configuration.

BTW: I really want to get that up to 100. Really want it

So, remember, if your site can be served statically, it's going to be cheaper, faster, safer. And if you ever get 9 million hits a day, it will be available.

Disclaimer:
Blitz.io is sending me a t-shirt ;-)

Syndicated 2013-02-25 17:34:16 from Lateral Opinion

Colón Al Colón

Spanish only, sorry!


Un lugar común en la charla política argentina es "se gastan la plata en Fútbol para Todos en vez de cosas importantes". Siempre me hizo un poco de ruido, a ver si me sale explicar por qué.

Para empezar parte de una jerarquía de prioridades, hay cosas más importantes que otras, y una de ellas, el fútbol, es menos importante que alguna, y por lo tanto no habría que gastar dinero en ella. Eso es un argumento de calidad dudosa, ya que no se gasta dinero únicamente en la cosa más importante.

Imagináte que en tu casa se llega a un consenso, y deciden que la cosa más importante es la comida, y a continuación gastan el 100% de todos los sueldos en comida. Eso parece razonable? No. Las prioridades definen en qué se gasta más o menos y en algún caso si hay que cortar algo se cortará lo menos importante, pero "A es más importante que B" no es, a priori, motivo para no gastar nada en B.

Lo que sí sería motivo para no gastar nada en fútbol sería que provocara un daño. Por ejemplo, a mí me gustaría que el gobierno no gastara un peso en ejército, porque no veo que sirva para nada, e históricamente (digamos los últimos cien años) el ejército argentino y sus aledaños han sido claramente un factor negativo en la vida de la nación, desde bombardear Buenos Aires, a invadir Malvinas, derrocar gobiernos, etc. Aún si sos, ponéle, antiperonista, y creés que Perón es la causa de todos los males... bueno, el viene del ejército.

Pero no creo que el fútbol sea algo malo en sí mismo. No es como si estuvieran gastando la guita en petardos. Entonces, comparémoslo con algo similar. Comparémos a Colón (de Santa Fe) con el Colón.

En el fondo, tanto el fútbol (y Colón) como el Colón, son entretenimiento. Son circo. Los presupuestos son comparables (dentro de un orden de magnitud, o sea, no es que el fútbol cuesta cien veces más). Si bien el origen de los fondos es distinto, para este análisis no hace diferencia, es plata pública, plata de impuestos.

¿Qué nos dá el Colón, que no nos dá Colón? Nos dá ópera y ballet. Formas artísticas que al 93% (porcentaje inventado) no les mueve un pelo. Colón (no el colón) nos dá fútbol, apreciado por un porcentaje mucho mayor de la población.

El Colón nos da, dije, esas formas artísticas, apreciadas en gran parte por gente que, seamos sinceros, podría pagar por ellas. Sí, hay una cantidad de gente de clase media y baja que va al Colón. También hay un montón de oligarcas que van a ver espectáculos pagados por los impuestos de gente a la que no le interesa en lo más mínimo pagar por ellos. El Colón subvenciona el entretenimiento de los ricos.

Sí, también es cierto que Colón (el equipo) provee fútbol, que mucha gente (yo incluído) no tiene ningún interés en ver (especialmente a Colón), pero cada fin de semana más gente aprecia un partido del Sabalero que la audiencia de media temporada de lírica.

¿Entonces, si uno hiciera un cálculo utilitario, por qué habría que pagar por el Colón para pocos y no por Colón, para muchos? ¿Por qué nadie pide que cierren el Colón?

¿No hay una hipocresía ahí? ¿No hay un juicio de que el Colón es cultura mientras que el fútbol no lo es? ¿Es ése en realidad el argumento?

Yo, personalmente, nunca fuí a ver un espectáculo al Colón, igual que nunca fuí a ver a Colón (debo haber ido a ver a Unión 8 veces en 30 años, con la consiguiente desilusión paterna), pero sé que hay gente que aprecia cada una de esas cosas, y sé que el "problema" de no apreciarlas es mío. No de ellos. No está mal que les guste la lírica, o el ballet, o el Torneo Clausura.

Y no está mal que un gobierno le dé a la gente algo que les guste. No está mal que el Colón le dé a los porteños motivo de orgullo porque tienen ese teatro ahí, y a algunos el placer de ir a ver una función. No está mal que Colón le dé a los sabaleros motivo de orgullo porque están en primera, y el placer de ir a ver un partido. Y no está mal que un gobierno ponga plata para eso.

Aunque eso no sea tan importante como el Garrahan, o como repavimentar una ruta, o como pagar un policía. Por lo menos no la están gastando en el ejército.

Syndicated 2013-02-22 17:35:24 from Lateral Opinion

New Nikola Tutorial

Tim van der Linden has written a impressive tutorial about how he used Nikola to create his new site shisaa.jp

It documents the whole process from scratch, starting by downloading Nikola up to building your own theme.

Even if you are already using Nikola you may find some new stuff there, so take a read (also, his theme is so pretty :-)

Syndicated 2013-02-21 17:41:38 from Lateral Opinion

Math Works Now

Docutils has supported math rendering for a while now. That means Nikola should have supported it for a while too, but never did correctly because ... well, because noone ever tried, maybe?

Well, it does now, because Damian Avila has fixed it!

Read more...

Syndicated 2013-02-20 10:13:22 from Lateral Opinion

Nikola 5.3 released

I am happy to announce the release of version 5.3 of Nikola a static blog/site generator. It includes some minor features and a good amount of bugfixing. Upgrading to it should not cause you any trouble, as far as I know.

Here's the changelog:

Features

  • Bootstrap 2.3.0
  • Optionally use content distribution networks for jquery and twitter-bootstrap (USE_CDN option)
  • Improve progressive rendering by moving javascript to the bottom of pages
  • New Brazilian portuguese translation.
  • New planetoid experimental extra_plugin

Bugfixes

  • Make really sure we import the right conf.py
  • Make SLUG_TAG_PATH a config dep for most pages
  • Removed meta title tag for better HTML validation
  • Removed #999 background from footnote backlink.
  • Made footnote references be superscripted.
  • Centered figure's image and caption.
  • Removed outset border from admonitions.
  • Use default theme as last resource for messages/translations
  • DATE_FORMAT option was being ignored
  • Remove trailing "" on windows gallery links (Issue #298)
  • Inconsistent breadcrumbs in gallery pages (Issue #303)
  • Use source files as bundle dependencies instead of outputs (Issue #294)

Enjoy!

Syndicated 2013-02-19 12:49:20 from Lateral Opinion

685 older entries...

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!