Python — Script to Rename Files and Crop Images in Directory

I’m often using python to rename files for me or process them in batches when I need to save some time / immense boredom, and I do it so infrequently I generally have to look at reference material.

Here some code for future reference.

"""
Python Rename Script
=========

This is just some one off code I wrote to save myself from doing repetative tasks. 

It probably took as long as manually renaming them and cropping the files.

The source files were in this format:
- name fun.jpg
- name work.jpg

I needed them in the following format:
- team_name.jpg
- team_name2.jpg 

and at specific dimensions.

I at first just wanted to rename, but found out some images were odd sizes.
"""

import re
import os
import shutil
from PIL import Image, ImageOps

dirname = os.path.abspath('.')
file_paths = os.listdir(dirname)

for _file in file_paths:
    try:
        matches = re.findall('(.*) (fun|work)\.jpg', _file)[0] # find name & if fun or work.
        name = matches[0]
        _type = matches[1]
        prefix = 'team_'
        suffix = ''
        if _type == 'fun':
            suffix = '2'
        
        new_name = prefix + name  + suffix + '.jpg'
        
        image = Image.open(_file)
        
        imagefit = ImageOps.fit(image, (150, 170), Image.ANTIALIAS, 0, (0.5, 0))
        imagefit.save('tmp/'+ new_name, 'JPEG', quality=90)
        
    except Exception, e:
        print e, _file
        
        # I don't really care about when this fails..
        # it would fail on any regex match failure like .DS_STORE (OSX file)
        # or my tmp directory

Mac OSX – Python Imaging Library PIL on Mac 10.6

Installing PIL was no problem, but I couldn’t import it.

I used homebrew, PIP, easy_install, they all say it’s correctly installed in the various directories.

I just decided to fix it by going to /Library/Python/2.6/site-packages and making a symlink from the egg file to to PIL

cd /Library/Python/2.6/site-packages
ln -s PIL-1.1.7-py2.6-macosx-10.6-universal.egg/ PIL

I suggest you not dwell on it and do this instead.

TextMate — CSS File Type for .css.liquid extensions

The default Liquid bundle will conflict with CSS Liquid files meaning syntax highlighting will off for CSS Liquid.

I had to switch between CSS and HTML Liquid since both files have .liquid endings.

To add css.liquid to the CSS language, push cmd+option+control+L, click on CSS, click on CSS again, and add ‘css.liquid’ to the ‘fileTypes’ line.

Django — Automatically importing modules for python manage.py shell

Ever wonder how many hours of time you’ve wasted importing the same things over and over at the start of a python manage.py shell?

Imagine the number of times you forgot to import datetime or decimal, or your model even.

I’ve finally had enough and looked up ways around this problem.

Luckily, this iPython solution is amazingly easy. Cut and paste code into iPython’s config files (which are python as well) and you’re done!

http://djangosnippets.org/snippets/549/

It will take 2 minutes max.

Django / Postfix — Connection Refused on send_mail on OSX

I was having trouble sending email from my local development environment (OS X) via django’s send_mail, and thus smtplib.

I figured out I need to enable postfix for OSX following the directions here:
http://www.agileapproach.com/blog-entry/how-enable-local-smtp-postfix-os-x-leopard-0

Except I had to do as a comment mentioned in the post, write each key/value as its own line, like so:

	<key>RunAtLoad</key> 
	<true/> 
	<key>KeepAlive</key> 
	<true/>

Check if postfix is running by typing sudo postfix status

If it’s not running, just start it: sudo postfix start

Now try connecting to it via localhost port 25

s = smtplib.SMTP('localhost')
# or send_mail
django.core.mail.send_mail(...)

Django — How to Order Inline ForeignKey

To apply ordering to a foreign key in the admin, you simply define an “ordering” attribute in your ModelAdmin.

But what about Inlines?

To apply ordering to an Inline Model’s foreign key, override the default form of the admin.StackedInline or admin.TabularInline subclass by specifying a ModelForm.

class OrderedInlineForm(forms.ModelForm):
    product = forms.ModelChoiceField(queryset=Product.objects.order_by('name'))
    class Meta:
        model = MyInlineModel

class MyInlineModelAdmin(admin.StackedInline):
    model = MyInlineModel
    form = OrderedInlineForm

Git Merge — Ignore Merge Conflicts for Specific Directory

How do you have Git ignore merge conflicts for a directory?
How do you force git to always accept files from a specific branch?

Look no further.

I have all of my project files in a git repo, including my libraries. Some libraries must compile and build binaries dependent on the OS, in my example pyCrypto.

That means I have a development branch for local development on my Mac, and a production branch that has the correct pyCrypto binaries for the production server.

However, every time I try to merge changes from my development branch, I’d get conflicts (naturally) since the binaries are different between the two packages.

I’ve solved my problem by forcing git to NOT merge the Crypto folder at all

I set up a git merge driver that does nothing at all, and set all files in the Crypto folder to use this driver.

All of this info comes from a stack question here http://stackoverflow.com/questions/928646/how-do-i-tell-git-to-always-select-my-local-version-for-conflicted-merges-on-a-sp/930495#930495

Step 1: create a special merge rule in your repositories .git/config file

[merge "keepmine"]
        name = dont_merge_selected_files
        driver = echo %O %A %B

Step 2: navigate to the folder you want never merged from outside branches, and create a .gitattributes file where you specify all files to use the merge driver “keepmine” defined in step 1

* merge=keepmine

commit your changes, and try merging! The conflicts in the folder with .gitattributes will not register and leave the original files intact. If you want the other way around, where your branch is always overwritten by a merge, take a look at the stack post above.

It says to set up a merge driver as

keepMine.sh %O %A %B

and in your keepMine.sh

cp -f $3 $2.
return 0

where 0 is the exit code of “resolved”.

This saves my world.

GitHub — fatal: ‘/data/repositories…’ does not appear to be a git repository

I just found out that my specific problem with GitHub doesn’t have to do with MY settings at all — I need to ask GitHub to fix an error in their systems.

http://support.github.com/discussions/repos/3426-fatal-datarepositories-does-not-appear-to-be-a-git-repository

Hopefully this helps somebody else getting the same problem.

Make sure you can ssh git@github.com

ssh git@github.com
ERROR: Hi yuchant! You've successfully authenticated, but GitHub does not provide shell access
Connection to github.com closed.

If you are having issues with permissions, read the answer to this stack question: http://stackoverflow.com/questions/922210/unable-to-git-push-master-to-github for tons of debugging ideas.

For me, it turns out it wasn’t my fault : )