Thursday, April 17, 2014

Insertion sort in Python

Implementation of Insertion sort in Python:
def sort(array):

  for i, item in enumerate(array):
    j = i
    while j > 0 and array[j - 1] > item:
      array[j - 1], array[j] = item, array[j - 1]
      j -= 1

  return array
      

import random


for i in xrange(10000):
  n = random.randint(10, 1000)
  array = [random.randint(0, n) for j in xrange(n)]
  print "%s (%s)," % (i, n),
  assert sorted(array) == sort(array)


Wednesday, April 9, 2014

Get current exception details in ipdb

So, I am debugging a program and want to see what is  currently active exception.

ipdb does not have a buitl-in command for this, so let's try using sys.exc_info():

> /home/vic/projects/test.py(4)<module>()
      2     1/0
      3 except:
----> 4     import ipdb; ipdb.set_trace()

ipdb> import sys; sys.exc_info()
(<type 'exceptions.AttributeError'>, AttributeError("Pdb instance has no attribute 'do_import'",), <traceback object at 0x2341bd8>)
ipdb> 

Hmm...

Ok, let's ask on Stackoverflow. And here is the solution: put

     alias exc_info !import sys; sys.exc_info() %1

into ~/.pdbrc

Now:
> /home/vic/projects/test.py(4)<module>()
      2     1/0
      3 except:
----> 4     import ipdb; ipdb.set_trace()

ipdb> exc_info
(<type 'exceptions.ZeroDivisionError'>, ZeroDivisionError('integer division or modulo by zero',), <traceback object at 0x7fe8dc7909e0>)
ipdb> 

Tuesday, April 8, 2014

Setup IntelliJ IDEA with GoLang on Ubuntu

  1. Install golang package
  2. Put this into ~/.profile:
    export GOROOT=$(go env GOROOT)
    export GOPATH="$HOME/projects/go"
  3. Download and unpack IntelliJ IDEA Community Edition from here. Launch idea-IC-135.480/bin/idea.sh
  4. Install GoLang plugin for IDEA. Open the Plugins installation page: File -> Settings -> Plugins -> Browse Repositories... Search for "golang". Right click on the proper plugin and install.
More info here.

Sunday, February 23, 2014

Batch convert all titles from a DVD source using HandBrake

HandBrake is a very nice tool to convert (rip) a DVD to another video formats. I was manually converting each title (the Linux version is not very discoverable) until I searched the Web how to convert all titles at once.

Here it is:


Tuesday, February 18, 2014

Delete merged branches in Git

Here is a script I made to delete local and remote branches merged into the current HEAD:
#!/usr/bin/env python3
import subprocess


print('Fetching remote branches...')
subprocess.call('git fetch -p --all', shell=True)

print('Processing remote branches...')

remote_branches = subprocess.check_output(
    'git branch -r origin/* --merged', shell=True).decode().split('\n')

answer = ''
remote_head = ''
for branch in remote_branches:
    branch = branch.strip()
    if branch == remote_head:
        print('Skipping remote branch %r which is the remote head.' % branch)
        continue
    if not branch:
        continue
    remote, branch = branch.split('/', maxsplit=1)
    if not remote_head:
        remote_head = branch.partition('HEAD -> ')[2]
        continue
    if answer != 'A':
        answer = input('Delete remote branch %r? (y/a or Enter) ' % branch).upper()
    if answer in 'YA':
        subprocess.call('git push %s :%s' % (remote, branch), shell=True)

print('Processing local branches...')

local_branches = [branch.strip() for branch in subprocess.check_output(
    'git branch --merged', shell=True).decode().split('\n')]

for branch in local_branches:
    branch = branch.strip()
    if not branch:
        continue
    if branch.startswith('* '):
        print('Skipping current branch')
        continue

    if answer != 'A':
        answer = input('Delete local branch %r? (y/a or Enter) ' % branch).upper()
    if answer in 'YA':
        subprocess.call('git branch -d %s' % branch, shell=True)

Tuesday, February 11, 2014

Tweaking IPython

I like IPython, but I don't like numbered prompts. Also I would like to not confirm exiting IPython when I press Ctrl+D.

Regular Python session:


Configured IPython session:


How I tweaked the configuration:

1. Created the configuration file:

ipython profile create

2. Edited the configuration file ~/.config/ipython/profile_default/ipython_config.py setting some lines like this:

# Set to confirm when you try to exit IPython with an EOF (Control-D in Unix,
# Control-Z/Enter in Windows). By typing 'exit' or 'quit', you can force a
# direct exit without any confirmation.
c.TerminalInteractiveShell.confirm_exit = False

# Output prompt. '\#' will be transformed to the prompt number
c.PromptManager.out_template = '>>> '

# Continuation prompt.
c.PromptManager.in2_template = '... '

# If True (default), each prompt will be right-aligned with the preceding one.
# c.PromptManager.justify = True

# Input prompt.  '\#' will be transformed to the prompt number
c.PromptManager.in_template = '>>> '

Sunday, January 5, 2014

A practical introduction to unit testing of Python applications using Mock library

Fake it till you make it
A talk by Ravi Chandra:

A practical introduction to unit testing decoupled, service-oriented, Python applications using with Mock library. A three-tiered (server, client, and view) Flask web application is used as a motivating example across the talk. Mock helps to isolate functionality specific to a layer to facilitate fast, compact, unit testing while avoiding writing specific mock classes or using fixtures.