Archive for the ‘Software’ Category

Manipulating the URL query string with Django and MultipleChoiceFields

Monday, February 6th, 2012

The problem: sometimes you want to add and remove URL parameters without knowing what’s already there. Say you are currently generating this URL:

/search/?q=foo&filter=bar&page=2

and, in that page, you have a button called Remove filters that should link to:

/search/?q=foo&page=2

The solution: this Django snippet implements a template tag called query_string that works like this:

{% query_string '' '' %}

where the first argument contains URL parameters that you want to add or modify, and the second one includes URL parameters that you want to remove.

Examples:


    Remove filters



    Go to page 3

The problem with this approach: while this approach has worked great for me for a while, I eventually hit a stumbling block: if you have a form for a group of checkboxes, and are submitting said form via GET, you will end up with an URL that looks like:

/search/?q=foo&opts=1&opts=2&opts=3

See how the opts parameter repeats several times? That’s a design flaw if you ask me, but that’s how HTTP seems to work.

When the URL parameters are pulled out of Django’s QueryDict, only the last one is preserved, i.e. opts=3, so you’d lose the tick on some checkboxes.

To prevent that, I have modified the query_string snippet. Here’s a version that works with MultipleChoiceFields, and multiple occurrences of the same URL parameter in general (I have replaced only the functions I modified. Please refer to the original snippet for the rest.)

class QueryStringNode(Node):
    def __init__(self, add,remove):
        self.add = add
        self.remove = remove

    def render(self, context):
        p_list = []
        p_dict = {}
        query = context["request"].GET
        for k in query:
            p_list.append([k, query.getlist(k)])
            p_dict[k] = query.getlist(k)

        return get_query_string(
            p_list, p_dict,
            self.add, self.remove,
            context)

def get_query_string(p_list, p_dict,
                    new_params, remove,
                    context):
    """
    Add and remove query parameters.
    From `django.contrib.admin`.
    """
    for r in remove:
        p_list = [[x[0], x[1]]\
            for x in p_list if not x[0].startswith(r)]
    for k, v in new_params.items():
        if k in p_dict and v is None:
            p_list = [[x[0], x[1]]\
                for x in p_list if not x[0] == k]
        elif k in p_dict and v is not None:
            for i in range(0, len(p_list)):
                if p_list[i][0] == k:
                    p_list[i][1] = [v]

        elif v is not None:
            p_list.append([k, [v]])

    for i in range(0, len(p_list)):
        if len(p_list[i][1]) == 1:
            p_list[i][1] = p_list[i][1][0]
        else:
            p_list[i][1] = mark_safe(
                '&'.join(
                    [u'%s=%s' % (p_list[i][0], k)
                        for k in p_list[i][1]]))
            p_list[i][0] = ''
        try:
            p_list[i][1] = template.Variable(
                p_list[i][1]).resolve(context)
        except:
            pass

    return mark_safe(
        '?' +
        '&'.join(
            [k[1] if k[0] == ''
                  else u'%s=%s' % (k[0], k[1])
                  for k in p_list]).replace(' ', '%20'))

Hope this helps.

Tango smilies for Conversations on the Nokia N900

Saturday, May 29th, 2010

One little known new feature of Maemo5 PR1.2 is the support for custom smilies in Conversations (<bragging>which I implemented</bragging>).

I have made a smiley theme based on Tango icons, but it’s not yet in the repositories. Here’s what it looks like:

Tango smilies

Tango smilies

You can install it by downloading this file: conversations-tango-smilies_0.1_all.deb, and copying it over to your N900.

Then open an X-Terminal, become root and do:

cd /home/user/MyDocs
dpkg -i conversations-tango-smilies_0.1_all.deb

Once it’s finished, switch to Conversation, go to Settings, and you will have a new button, called Smileys theme. You can select your newly installed Tango theme.

Note: the theme will not work with SMSs and Skype chats. All the other accounts, and SMSs, will use the new theme.

After setting the new theme, go to an IM conversation and see if the new icons are in the smiley picker. If not, a reboot should do.

Enjoy!

Tweakr 0.0.17-2 hits Maemo Extras!

Wednesday, March 10th, 2010

Tweakr has been finally promoted to Maemo Extras, check it out at http://maemo.org/downloads/product/Maemo5/tweakr/.

You can now easily install it from the App. manager. I’ll write up a new tutorial someday soon.

Tweakr 0.0.16

Wednesday, February 17th, 2010

Hi. I have released tweakr 0.0.16, which you should be able to install from Maemo Testing in a matter of minutes. A couple of bugs fixed and the Silent profile hardcoded is what’s new. Update!

Tweakr promoted to extras-testing

Sunday, January 24th, 2010

Hi, a quick update on Tweakr: it has now been promoted to extras-testing, since the reboot loop bug (thanks, hildon-home!) has been fixed.

Also a new feature present: the Profile button in the Status Menu gets replaced by Tweakr’s own button (which looks identical), so that you won’t have get your Status Menu too crowded.

Use Profile presets in the N900 with Tweakr

Monday, December 21st, 2009

A new feature in Tweakr allows you to extend the sound Profiles to more than just General and Silent.

Tweakr introduces the concept of Profile preset. Presets are Profile settings which can be saved, deleted and assigned to the General profile. This allows you to practically use as many profiles as you want on the N900.

The normal use-case is to first tune the General profile for the new preset you want to save, then open Tweakr and choose the Save current General profile to new preset button. This will allow you to save the settings of the General profile with a new name.

Screenshot-20091221-210945

After that, you will find a new button in your Status Menu, as shown in the following screenshot:

Screenshot-20091221-211001

You can now select whatever preset you have created before, and its settings will be applied to the General profile.

Screenshot-20091221-211006

If you’re not using Tweakr yet, go get it from its download page!

Introducing Tweakr

Saturday, December 19th, 2009

I have been working on a little utility package for Maemo 5, called Tweakr. It’s a Settings applet that lets you tweak little known settings that could otherwise be changed only by editing configuration files by hand.

It has a plugin architecture, so you could write your own plugin too. The ones I have so far are Desktop and Hardware keys.

Desktop

This plugin allows you to edit the labels of the bookmark shortcuts you have on your desktop.

Hardware keys

You can configure the behavior of the Power Key, and whether uncovering the camera lens unlocks the device.

More plugins and feature coming soon!

Here’s some screenshots:

Tweakr entry in the Settings

Tweakr

Win32 odyssey: who needs documentation?

Thursday, February 14th, 2008

During my coding adventures, I have just found myself having to port an existing Win32 application to CMake. After writing a mere 283 lines CMakeLists.txt file, and getting the application successfully compile, I fired it up to see if it worked, of course. I found it failing when doing a WSAAsyncSelect, and failing there didn’t seem to make any sense. So, to get to the point, I decided I’d just carefully compare the compiler’s options generated from CMake with the ones that were in the original Visual Studio project file. After finding the difference, I decided I was gonna learn what those flags meant, so I googled for “visual c++ compiler flags” and guess what? Nothing useful. The right string to google would be “visual c++ compiler options”. But before getting to it, I had to unsuccessfully go thru “visual studio compiler options”. You’d think that would cut it, right? Since “visual c++ compiler options” did it. But, surpringly, “visual studio compiler flags” did actually find what I wanted. Interesting combination.

I don’t really feel like blaming Google on this. Reproducing the same search pattern in the internal Help function of Microsoft Visual Studio gave me the same success/no-success scheme. Besides, the whole point-and-click procedure is a terribly uncomfortable experience. Not only I have to get my hands off my keyboard (inherently a waste of time), but also do I have to (mind: have to) wander my mouse around for a while to get to the information.

So, I wondered, is there an alternative? I went to my rxvt terminal emulator (which I run through Cygwin, can’t really be bothered with using the native Windows Terminal), and tried to get some help from cl.exe. No luck. After some try-and-fail recursion, the least useless thing I would find was cl.exe -help which would give me 106 (one hundred and six!) lines of documentation. Wow, impressive, isn’t it? Comparing, gcc‘s manual page is 7820 lines, as for the latest stable.

Leaving closed protocols behind

Tuesday, October 23rd, 2007

In order to fulfill what has been a proposition of mine for quite a long time, as of December the 1st 2007, I will no longer use any Instant Messaging services based on a closed protocol, e.g. MSN, ICQ, AIM or Yahoo. The only way you will be able to contact me (besides conventional methods such as phone and email) will be through my Jabber ID: salvatore.iovene at googlemail.com (replace “at” with “@”). This also works from GMail.

Reason

Proprietary IM systems have a terrible flaw: MSN users can’t chat with Yahoo users, AIM can’t chat with ICQ, and so on. So if I have friends who only use MSN and other friends who only use ICQ, I will have to use both to keep in touch with everybody. The reason for this is the corporate greed taking advantage of the network effect. Wikipedia says:

The network effect is a characteristic that causes a good or service to have a value to a potential customer dependent on the number of customers already owning that good or using that service.

This also reflects the fact that corporates are valuing their own profit better than the final user’s satisfaction. Moreover, I don’t like the idea of using a closed protocol. “Closed protocol” means that the data (e.g. chat messages) exchanged by two computers involved in a transaction, is represented with a secret format, that the user is not allowed to study. Jabber, on the other hand, uses an open protocol, based on XML. Everybody is allowed to study the protocol, and write clients or servers that support it. This allow collaboration and cooperation. Greedy corporates, instead, keep the protocol secret in order to be the only ones able to write a client and a server for it, so they impose you the use of their clients (such MSN) which might be bloated with spyware and advertisements.

Since I’ve decided that I don’t want to support this kind of behaviour, I will unsubscribe from the closed protocol services that I use. You don’t have to do the same, but just get yourself a Jabber account in order to keep in touch with me, and, preferrably, convince your friends to do the same.

What is Jabber?

When you hear someone (probably me) talking about Jabber, they are usually referring to one of the following:

  • The XMPP (Jabber) Protocol
  • The Public Federated Jabber Network (PFJN)
  • The Jabber Platform (which includes the previous items, as well as jabber chat clients, devices, transports, etc.)

Jabber is, strictly speaking, the informal name of an open-standard decentralized instant messaging protocol officially called XMPP.

NOTE: It is also the name of a company called Jabber Inc., which sells Jabber-based products. However, the Jabber platform is much larger than this single company. Don’t let this confuse you! If you want to go to the authoritative website about jabber, that would be jabber.org, not jabber.com!

The network of independent Jabber servers on the internet make up the Public Federated Jabber Network. If you have an account on a server on the PFJN, then you can communicate with anyone else who has an account on a PFJN server. This means that Google Talk users can communicate seamlessly with Gizmo-Project users (and vice-versa), as both of these services are on the Public Federated Jabber Network.

How can I use Jabber?

To use Jabber you need a Jabber client and an account on a server. Here’s a list of popular clients:

MS Windows

MacOS X

GNU/Linux

Then you will need an account. Most of the listed clients will allow you to create a Jabber account choosing from a list of servers, or, if you want, you can run your own server.

Google Talk

If you have a gMail account, then you have a jabber id via Google Talk! Your jabber id is the same as your email address. You can use either the native google talk client or any other jabber client.

Gizmo Project

Also, if you use the Gizmo Project, you too have a jabber account. Your jabber ID is login-name@chat.gizmoproject.com.

jabber.org

The Jabber Software Foundation is probably the best known Jabber server out there. They just recently switched over to ejabberd for their software, so they should be quite solid now.

Fujitsu-Siemens shame on you

Wednesday, October 17th, 2007

I found myself in the process of realizing a dual-boot system on a laptop, with Windows XP and Ubuntu 7.10. After wiping out the content of the disk and partitioning it appropriately, I proceed to the installation of Windows XP (knowing that I needed to install it first, since it would overwrite the MBR and completely disregard and disrespect user’s freedom), so I put in the so-called Recovery Disk provided with that particularly Fujitsu-Siemens laptop. After a little while, the Recovery Disk was proposing me to install Windows XP either using the full disk, or in two partitions, with a 10 GB “data” partition. I was astonished and outraged. It seems that the Fujitsu-Siemens people were thinking that the user wasn’t smart enough to be able to choose what partition use for his or her Windows install. They would rather limit the user’s freedom, and not give him or her some choice. I suspect this was the result of some pressure from the Microsoft end: this “trick” basically stops the user from installing other Operating Systems along Windows, unless he or she buys a new non-branded copy.

Fujitsu-Siemens and Microsoft: shame on you!