Working Ninja

Here's a simple shell wrapper that prints all sockets opened by Firefox.

1. Add the following function to your ~/.bashrc:

function ffsocks() {
    netstat -anp --inet | awk '/firefox/ { print $5 }'

2. Reload your shell (or run source ~/.bashrc) to make ffsocks callable from your shell environment.

3. Finally, execute ffsocks!

$ ffsocks

The power of shell wrappers comes from their ability to "codify" a more complex command (or series of commands, what flags are used, etc) and also in their reusable nature (we can call ffsocks any time we want!). Thus, shell wrappers are a good option for complex commands that are called often (or for those hard to remember ones that you don't call too often--I guess they're just all around good to use whenever!).


By default, a ModelForm is populated with all its objects from the database. Sometimes it's desirable to limit these results as they are returned to the view. After setting up our ModelForm ( there is only one thing we need to do to make this happen. Within our view (, we update the queryset as follows:

class PollForm(ModelForm):
    class Meta:
        model = Poll
        fields = ('question',)

form = PollForm()
form.fields['question'].queryset = Poll.objects.filter(question__startswith="How")

This will filter Polls that start with "How".



The following example looks for the "idle" time before backlight brightness is reduced.

Find what you're looking for:

gsettings list-recursively | grep idle

Get the value:

gsettings get org.gnome.settings-daemon.plugins.power idle-brightness

Set the value:

gsettings set org.gnome.settings-daemon.plugins.power idle-brightness 120



Create unicode string "a".

>>> a = u'\u2019'
>>> a

Convert to ASCII string (ASCII is default for Python 2 str()).

>>> str(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 0: ordinal not in range(128)

Encode the unicode string to UTF-8 (overriding the default of ASCII).

>>> str(a.encode('utf-8'))
>>> print str(a.encode('utf-8'))

For a greater understanding, see Ned Batchelder's great "Pragmatic Unicode, or, How do I stop the pain?" (2012) video.


Let's say we want to query our Polls app for all Questions that have popular (more than 5 votes) choices that contain Python in the choice_text.

We could query our database as follows:

SELECT * FROM question JOIN (SELECT * FROM choice WHERE vote_count > 5 AND choice_text LIKE '%Python%') choice ON = choice.question_id;

Or, it can be codified in a potentially more comprehendable, OOP/ORM format with SQLAlchemy.

First, we set up our schema by declaring the relationship and the parameters of the join:

class Question(Base):
    __tablename__ = 'question'

    id = Column(Integer, primary_key=True)

    popular_choices = relationship('Choice', primaryjoin='and_( == Choice.question_id, Choice.vote_count > 5')

Next, we query with SQLAlchemy's ORM:

popular_python_choices = session.query(Question) \
    .filter(Question.popular_choices.contains('Python') \

Not quite as terse as straight SQL but hopefully it is clear how, after the schema is set up, calling Question.popular_choices.contains('Python') provides increased readability (reads like English) and reusability (replace our filter Python with whatever you wish!).

SQLAlchemy provides another good example.


Here's the most straightforward and succinct way I've found to mock patch a function that returns different (but specific) results with each call, shamelessly copied from Python Docs:

>>> values = {'a': 1, 'b': 2, 'c': 3}
>>> def side_effect(arg):
...     return values[arg]
>>> mock.side_effect = side_effect
>>> mock('a'), mock('b'), mock('c')
(1, 2, 3)

And, now that we have our side_effect function defined, we can pass new values to return:

>>> mock.side_effect = [5, 4, 3, 2, 1]
>>> mock(), mock(), mock()
(5, 4, 3)



After updating mysql-connector-python to 8.0.11 (released April 19, 2018), I received an "OperationalError: 1043 (08S01): Bad handshake" error when querying a MySQL database. I found that I needed to set 'use_pure: True' in the connection string.

From the MySQL folks:

The C extension was added in version 2.1.1 and is enabled by default as of 8.0.11. The use_pure option determines whether the Python or C version of this connector is enabled and used.1

For example2:

import mysql.connector

config = {
  'user': 'scott',
  'password': 'password',
  'host': '',
  'database': 'employees',
  'use_pure': True,

cnx = mysql.connector.connect(**config)

Since I don't have the C extension installed on my server, I reverted back to the Python implementation. Though it is good to know that the C extension can improve performance for large queries--something to tuck away for future use.



Toggle all <option>'s as checked/unchecked with the click of a <button>.


    jQuery("select :checkbox").each(function(){
        this.checked = !this.checked;



If you've ever touched a date or time related field via the Django API, you'll have noticed the big warning that the date and/or time is not localized. While the warning is nice there isn't much more in the way of how to localize the time. Here are two ways that I usually go about it:

>>> timezone.make_aware() 
>>> timezone.localtime()

Both are found in django.utils's timezone module. If you're using Django Extensions, timezone is already loaded when you run ./ shell_plus. If you're not, simply run from django.utils import timezone.

For usage:

>>> help(timezone.make_aware)
>>> help(timezone.localtime)

Give your hand some relief from reaching for Ctrl and take advantage of the close proximity of Caps Lock.

# Note any previous values for xdb-options (most likely none)
gsettings get org.gnome.desktop.input-sources xkb-options

# Set our xkb-options (plus anything from our get, if needed)
gsettings set org.gnome.desktop.input-sources xkb-options "['ctrl:nocaps']"

Now to retrain your brain ;)