Showing posts with label workflow. Show all posts
Showing posts with label workflow. Show all posts

Sunday, July 12, 2009

xorg options for Jaunty

Since Jaunty the Ubuntu people thought it would be a good idea to cripple the xorg settings (they disabled middle mouse button emulation and ctrl+alt+backspace xorg reset hotkey).

Luckily this can be fixed by editing the /etc/X11/xorg.conf file by adding the following:
# Enable middle mouse button emulation (left+right click at the same time):
Section "InputDevice"
Identifier "Configured Mouse"
Driver "mouse"
Option "CorePointer"
Option "Device" "/dev/input/mice"
Option "Protocol" "ExplorerPS/2"
Option "ZAxisMapping" "4 5"
Option "Emulate3Buttons" "true"
EndSection

# Enable crl+alt+backspace xorg reset
Section "ServerFlags"
Option "DontZap" "false"
EndSection

Friday, July 10, 2009

My vimrc file

Got to save my .vimrc (vim configuration file) once in a while and now is a good time as I just cleaned it up a bit. Did not tweak it too much, but it has a few handy shortcuts, some for python some just general purpose. The file can be found as gist (revisioned pastebin) here.

And here is a raw paste:
" set tabstop settings
set ts=8
set sw=8

" wrap long lines
set textwidth=80
set linebreak
set smartindent

syntax on
set nocompatible
set novisualbell

" check for external modification
set autoread

" incremental search
set incsearch

" set spelling highlight options
highlight clear SpellBad
highlight SpellBad term=standout ctermfg=1 term=underline cterm=underline
highlight clear SpellCap
highlight SpellCap term=underline cterm=underline
highlight clear SpellRare
highlight SpellRare term=underline cterm=underline
highlight clear SpellLocal
highlight SpellLocal term=underline cterm=underline

" ---------- START OF SHORTCUTS DEFINITIONS (KEY BINDINGS) ----------
"
" INDEX
"
" ,s enable spellcheck highlight
" ,S dissable spellcheck highlight
" ,c-d save all and exit
" ,c trim spaces at end of lines
" ,C trim spaces at the beginning of lines
" ,d insert date in YY-MM-DD format
" ,u insert unix timestamp
" <F2><F3><F4> execute file with python interpreter 2/3 and with argument
" <F5><F6> enable/dissable paste mode
" <F9><F10> exchange spaces with tabs and tabs with spaces
" <F12> general search and replace template

" spell checking shortcuts (ctrl+[sS] to switch it on/off)
map ,s :set spell<CR> :setlocal spell spelllang=en_us<CR> :set spellfile=~/.vim/spellfile.{encoding}.add<CR>
map ,S :set nospell<CR>

" add python 2, 3 and 3 with arguments execution to F2-F4
au filetype python nmap <F2> <esc>:w<CR>:tabfirst<CR>:! python %<CR>
au filetype python nmap <F3> <esc>:w<CR>:tabfirst<CR>:! python3 %<CR>
au filetype python nmap <F4> <esc>:w<CR>:! python3 %

" add save all and exit shortcut to ctrl+d
nmap <c-d> <esc>:xa<CR>

" add shortcut for switching paste mode on/off (F5-F6)
nmap <F5> :set paste<CR>i
nmap <F6> :set nopaste<CR>

" shortuct for swapping spaces with tabs (F9-F10)
nmap <F9> :%s/ /\t/g<CR>
nmap <F10> :%s/\t/ /g<CR>

" general search and replace template
nmap <F12> :%s///g

" suppress all spaces at end/beginning of lines
nmap ,c :%s/\s\+$//<CR>
nmap ,C :%s/^\s\+//<CR>

" insert current date in YY-MM-DD or UNIX time format
map ,d :r!date +\%Y-\%m-\%d<CR>hJi
map ,u :r!date +\%s<CR>

""" --------- END OF KEYBINDINGS --------------

" set execution bit for scripts
au bufwritepost *.sh silent !chmod +x %
au bufwritepost *.x.py silent !chmod +x %

" if we edit makefiles, make sure that tabs are not replaced with spaces
au filetype make setlocal noexpandtab

" set plaintext documents to a text with of 72 chars
autocmd BufRead *.txt set tw=72

Saturday, July 4, 2009

Terminal command shortcut scirpt

You know those terminal commands that you execute all the time but are too lazy to put in a shell alias or those special commands you need a lot of time to figure out and then mostly forget about it and then the next time you need it you cruse yourself you did not save it somewhere? This script aims to address this problems.

It stores commands terminated with newline in a data file (~/.scdata). When you invoke it with the number argument, it executes that line number (beginning with 0). Without argument it list the available commands with id's and prompts for id to execute.

Now, when you figured out some complicated command with a lot of options, like 'rsync -av /myhome /backup_drive' you can simply echo it to the data file (echo 'rsync -av /myhome /backup_drive' >> ~/.scdata) and recall it anytime with the prompt utility.

Your ~/.scdata with 4 commands (0-3) could look like this:

echo hello
cp foo bar
rsync -av /myhome /backup_drive
echo 'and so forth'

Now running the script with argument '2' ($ sc.py 2) for instance would run the rsync command.

Syntax highlighted version here.

#! /usr/bin/env python3

"""
Terminal command shortcut scirpt.

This script reads a command data file (~/.scdata) and executes commands from it.

There are two command execution models:
1. by argement, if you invoke it with a number, it executes this command
and exits. If you invoke it with -e opion, it opens the command file
for editing and then enters the main loop.
2. by loop, if you invoke it withouth an argument, it prints the
availible commands and promts for command number (id) to execute.

There are also 2 special non-numeric loop commands:
e: edit command file and return to main loop
q: quit program
"""

import os, sys, time

def get_editor():
try:
editor = os.environ['EDITOR']
except:
editor = 'vim'
return editor

def read_data(editor, data_file):
try:
with open(data_file, 'r') as f:
data = f.readlines()
data = [item.strip() for item in data]
data = dict(enumerate(data))
return data
except:
print('Data file not found, first start?.. Creating data file')
print('Please add some command to it..')
time.sleep(3)
with open(data_file, 'w') as f:
pass
os.system(editor + ' ' + data_file)
return read_data()

if __name__ == '__main__':

editor = get_editor()
data_file = os.path.join(os.path.expanduser('~'), '.scdata')

data = read_data(editor, data_file)

if len(sys.argv) > 1:
if sys.argv[1] == '-e':
print('Opening data file for editing..')
time.sleep(1)
os.system(editor + ' ' + data_file)
try:
cmd_task = int(sys.argv[1])
os.system('clear')
print('executing ', data[cmd_task], '\n')
os.system(data[cmd_task])
print('\nexecution done, exiting..')
sys.exit()
except (IndexError, ValueError):
pass

while True:
os.system('clear')
print('Shell command shortcut utility\n' +
'==============================\n\n' +
'Currently availible commands are:\n')
for cmd_task, cmd in data.items():
print(cmd_task, '\t', cmd)
print('\nPlease enter a command (e, q, or number)\n')
try:
cmd_task = input('% ')
if cmd_task == 'e':
os.system(editor + ' ' + data_file)
data = read_data(editor, data_file)
continue
elif cmd_task == 'q':
print('Quit.. bye!')
sys.exit()
else:
cmd_task = int(cmd_task)
assert(cmd_task <= len(data))
except (AssertionError, ValueError, KeyError):
print('Please enter a valid input ' +
'(h, e, q or number)')
time.sleep(1)
else:
os.system('clear')
print('executing \'{1}\' ..\n'.format(data[cmd_task]))
time.sleep(1)
os.system(data[cmd_task])
print('\nexecution done, hit a key to return..')
input()

Monday, June 29, 2009

Work session start/end script

There is a set of repetitive tasks I do when I develop something, like check-in, off-site backup, archive integrity checking, etc. To automate this, I wrote a little script that I invoke when I start and stop to work on something for this purpose. The start and end functions should be adapted to personal needs, this one is a bit bare-bone.

Here is what it looks like (syntax highlighted version here):

#! /usr/bin/env python3

"""
Work session start/end script.

This script contains the routines that should be performed before and after a
work session and log it. Currently these are git repository integrity checking
for start up. Change commiting and backup for end of session.

Uses 'rsync' for backup and 'git' for revision control, make sure they are in
place.

The BACKUP_PATH has to be adapted to the syncronization target.

This script is quite safe to use.
"""

import os, sys, subprocess, time, datetime

BACKUP_PATH = '/media/disk'
LOGFILE = 'session.log'

def log(message, logfile=LOGFILE):
timestamp = str(int(time.mktime(datetime.datetime.now().timetuple())))
name = os.path.basename(__file__)
with open(logfile, 'a') as f:
f.write('[' + timestamp + '] ' + name + ': ' + message + '\n')

def start():
status = subprocess.call(['git', 'gc'])
if status != 0:
print ('!! something went wrong with the repository checking!')
print ('(recheck manually with git fsck and restore integrity)')
sys.exit(1)

log('session started')

def end():
os.system('git add .')
os.system('git gui')

if os.path.isdir(BACKUP_PATH):
os.system('rsync -a . ' + BACKUP_PATH)
else:
print('backup path not existent, backup aborted..')

log('session ended')

if __name__ == '__main__':
usage = ('Usage: session.py start|end\n' +
' start: start session\n' +
' end: end session\n')

os.chdir(os.path.abspath(os.path.dirname(__file__)))

if len(sys.argv) == 1 or (
sys.argv[1] != 'start' and sys.argv[1] != 'end'):
print(usage)
sys.exit()

if sys.argv[1] == 'start':
start()
elif sys.argv[1] == 'end':
end()