Tuesday, December 27, 2011

Autoselection of checkboxes in a table

The code doing selection
$(function () {
    "use strict";
    var toggleSelect = $("#all"),
        checkboxes = $("#table").find("tbody input[type=checkbox]");
    toggleSelect.click(function () {
        checkboxes.attr('checked', $(this).is(":checked"));
    });
    checkboxes.click(function () {
        toggleSelect.attr('checked', checkboxes.length === checkboxes.filter(':checked').length);
    });
});
A sample table
Username Phone Number
User 1 0123456789
User 2 0133456789

Tuesday, December 6, 2011

Activate VE from Django's manage.py

To transparently activate virtual environment from project's manage.py insert the code below right after #!/usr/bin/env python
activate_this = '/ABSOLUTE/PATH/TO/ENVIRONMENT/FILES/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))

Thursday, October 20, 2011

Madly follow PEP8 with git help

If you intended or are obliged to strictly comply to PEP8 it may be useful to have a git hook that takes care of checking your code before you have committed and prevents you from amending previous commit again and again.

So, in .git/hooks/ directory of your repository create a file with name pre-commit and put

#!/bin/sh

# comma-separated list of files and directories which are not for checking
SKIP=migrations,bootstrap.py,dodo.py,manage.py

pep8 -r --exclude=$SKIP .

UPDATE: The code above checks all the project Python files. To limit checking only for files going to be committed

#!/bin/sh

FILES=$(git diff --cached --name-status | awk '$1 $2 { print $2}' | grep -e \.py$)
if [ -n "$FILES" ]; then
    pep8 -r $FILES
fi

The command shows all staged files, next only the filenames are left and filters Python files. If any they are to be checked with PEP8 utility.

Saturday, October 15, 2011

Word and text translation bookmarklet

Sometimes (I hope rarer and rarer :)) I need to translate an unknown foreign word on the page. I used to select it, open Google Dictionary Translate, paste it, set source and destination languages if needs and only then press the button to translate it.

Some time later I discovered bookmarklets. I liked the approach and made one for myself.

Drag this link En<>Ru the bookmark panel to be able translate words or text.

To change default source and destination languages put their codes in place of en and ru.

Source code.
(function() {
    var t;
    try {
        t= ((window.getSelection && window.getSelection()) ||
            (document.getSelection && document.getSelection()) ||
            (document.selection &&
            document.selection.createRange &&
            document.selection.createRange().text));
    }
    catch(e){
        t = "";
    }

    if(t && (t=t.toString()) && t.length){
window.open("http://translate.google.com/?sl=en&tl=ru&hl=en&text="+t+"#en|ru|"+t);
    }
})()

I used Javascript Compressor to get compressed version to use it in the bookmarklet.

Friday, October 14, 2011

Uninstall XCode

To uninstall XCode from Mac OS X run in terminal:
sudo /Developer/Library/uninstall-devtools –mode=all

Tuesday, October 11, 2011

Upgrading Mac OS X to Lion and dealing with virtualenv

I happened to have successfully upgraded my Snow Leopard to Lion. It looks nicer, softer and so forth. But I depend on my MacBook Pro in my work and have to have everything working.

Actually after upgrade everything were broken: python did not work properly, system paths were set in their defaults. So it was absolute mess.

First, as I learned it from Snow Leopard, I have downloaded new XCode from Mac App Store. It quote big and it took all night (while I was sleeping) for downloading. In the morning I installed and all became better but one. Virtual environments were still spoiled and did not work.

After a few tries and researches I came up with the following:

sudo easy_install pip # it installs new (or even) pip version
sudo pip install virtualenvwrapper

After those commands all get working.

Thursday, October 6, 2011

CKEditor autosave plugin

If you need autosave function for the CKEditor I made a plugin. It allows to save automatically the work as you've stopped typing.

UPD  Oct 6, 2011: Plugin has moved to GitHub.

Monday, August 15, 2011

Avoid command repeating in Bash

If you are already done with mess of the same commands in bash history, just put that in your ~/.bashrc
export HISTCONTROL=ignoredups:erasedups
ignoredups prevents the history from duplicates
erasedups if a command is already in the list it will be removed at the old position and put in the beginning of the history list

Wednesday, August 3, 2011

Clients of the webservice

Some time ago my iPhone happened to get lost. There were many clients of well known services installed and all of them had been logged in and most part of them had their passwords saved. To prevent access from my lost phone I had to change password for almost all services I used.

Clients should avoid using re-authentication with login and password. It implies saving them on the client side. Conversely, the application should either ask for OAuth authentication or for login and password only once. Latter requires the server to provide the key to login next time with.

Those techniques allow the web server to control all the clients without changing the password if something has happened to one of the clients.

Thursday, June 30, 2011

Yesterday date

$yesterday = date('Y-m-d', mktime(0, 0, 0, date("m") , date("d") - 1, date("Y")))

UPD: (thanks to stamm)
$yesterday = date('Y-m-d', strtotime('- 1 day')); 

Tuesday, June 28, 2011

Kwargs in Python

Recently I noticed that function cannot accept unicode strings as parameter names given in kwargs. They must be converted to strings.

I made a sample script
import sys

print "Version: %d.%d.%d\n" % sys.version_info[:3]

string_params = {'a':1, 'b': 2}
unicode_params = {u'a':1, u'b': 2}

def f(a,b):
 print "params: ", a, b

print "Run with string params:"
f(**string_params)

print "\nRun with unicode params:"
f(**unicode_params)

As output I got
Version: 2.5.1

Run with string params:
params:  1 2

Run with unicode params:
Traceback (most recent call last):
  Line 15, in 
    f(**unicode_params)
TypeError: f() keywords must be strings

To check out it online.

Disable Firefox cache for developing

To disable caches while you're developing and testing in Firefox:
  1. Type about:config in FF address bar;
  2. Set to false the following params:
    • network.http.use-cache
    • browser.cache.offline.enable
    • browser.cache.disk.enable
    • browser.cache.disk_cache_ssl
    • browser.cache.memory.enable
Beware, it totally disables cache in FF!

Monday, June 27, 2011

Make string html-safe

To make a string HTML-safe (convert & to &amp;, > to &gt; and so forth):

>>> import cgi
>>>
>>> test_string = "This is <unsafe> string & it contains wrong symbols"
>>>
>>> print cgi.escape(test_string)
This is &lt;unsafe&gt; string &amp; it contains wrong symbols