Postgresql — access from remote location / OBDC

Edit pg_hba.conf

add a line to allow a connection from your IP address:

host    all         all          71.56.137.10/24      md5

Edit postgresql.conf

Uncomment listen_addresses line and set to ‘*’

Download Postgresql ODBC driver

http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CHEQFjAA&url=http%3A%2F%2Fwww.postgresql.org%2Fftp%2Fodbc%2Fversions%2F&ei=7x3ZT8eVB6qm6gGm19WGAw&usg=AFQjCNFnVfQTQ1A6VfcYuSkBfQ14cdCKyw

Set up ODBC connection

This is the confusing part. If you downloaded a 64 bit driver, you need to launch the ODBC panel that lives in C:/windows/sysWOW64/odbcad32.exe

It looks identical to the other admin panel, and connections will even succeed, but in my case Endicia would only be able to connect if the connection was set up through sysWOW64/

Details here:
http://stackoverflow.com/questions/1954128/how-do-i-connect-to-my-64-bit-sql-server-with-odbc

Django prevent cascading delete

I accidentally deleted tons of data with a quick `Contact.objects.all().delete()`

Remember that any model that references the instance in question, even if the `ForeignKey` is nullable, will be deleted by django.

Use the on_delete argument on ForeignKey definition to prevent this behavior.
https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.on_delete

In my case, I had a large core model referencing a not-so-important stand alone model which was deleted. Important things shouldn’t be deleted just because they happen to reference an unimportant thing 🙂

Shopify API Orders ordering changed on May 17th 2012?

Shopify API’s orders call seems to be reversed suddenly – I am getting responses from MAX_DATE first, not the other way around.

My sync functions were expecting the latest 250 orders. I don’t see a way to specify ordering, so I have switched to using the since_id field.

Django — ‘NoneType’ object has no attribute ‘status_code’

My cache middleware was complaining about this – I thought I had a bug in another middleware that was not returning a response due to exceptions, but it was more simple: look for recent changes in your code that have altered view responses.

In my case I had added a method_decorator(cache_page) decorator to a class based view, which required I subclass the dispatch() line. Apparently, I forgot to return the super() call.

Make sure your views are returning responses!

PostgreSQL — Drop Column Not Null Constraint

The docs kept suggesting DROP CONSTRAINT constraint_name [ RESTRICT | CASCADE ] but it doesn’t appear to like that — you must pass the constraint_name without the CONSTRAINT keyword. At least on my 8.4.

Don’t do this as the docs might suggest..

ALTER TABLE <table> ALTER COLUMN <column> DROP CONSTRAINT not null;

Do this:

ALTER TABLE <table> ALTER COLUMN <column> DROP not null;
ALTER TABLE my_table ALTER COLUMN my_column DROP not null;

Django — Override One Specific Field Widget in Admin

formfield_overrides is just too global and redefining form fields has many drawbacks (loss of original field arguments for example and ModelForm magic). What do we do? I keep forgetting about the ModelForm meta class widget attribute.

The ModelForm meta class takes a widget attribute which is a map of fieldnames to widgets:

class OrderForm(forms.ModelForm):
    class Meta:
        model = Order
        widgets = {
            'activity': forms.Textarea(attrs={'disabled': True}),
            'log': forms.Textarea(attrs={'disabled': True}),
        }

class MyAdmin(admin.ModelAdmin):
    form = OrderForm

Photoshop OSX Sluggish Text and No Drag and Drop

I’ve been living with this for a while… typing 20 characters of text would take a minute, and more importantly, I could NOT drag and drop layers from one document to another.

I figured I’d fix the text problem first which happens to cure the drag and drop issue too!

I found a help article that told me to run OSX Font Book’s font validation tool.

It analyzed all of my fonts, found 10 that were troublesome, and provided an easy way to remove them all from my system after which my photoshop types text like a champ!

http://helpx.adobe.com/photoshop/kb/troubleshoot-fonts-photoshop-cs5.html

Python xlwt: writing excel files

To write excel files with Python, first download / install xlwt.

pip install xlwt

A demo with common operations should help more than a write up:

Create workbook and sheet

import xlwt
workbook = xlwt.Workbook() 
sheet = workbook.add_sheet("Sheet Name") 

Write a cell

sheet.write(0, 0, 'foobar') # row, column, value

Apply styles to a cell (bold)

style = xlwt.easyxf('font: bold 1')
sheet.write(0, 0, 'foobar', style)

Set width of column

To set the widths, you must set the width attribute to 256*NUM_CHARS where 256 is equal to the width of the zero character.

sheet.col(0).width = 256 * (len(key) + 1) 
# set width.. 256 = 1 width of 0 character

Apply multiple styles to a cell

Note that you are limited to 4k styles per document, meaning you should not initialize a style for every cell but re-use them (read below for simple cache solution).

style = xlwt.easyxf('font: bold 1, color red;'))
sheet.write(0, 0, 'foobar', style)

Apply currency style

To set currency, add the keyword argument num_format_str to the easyxf function or set the attribute on the returned style object.

style = easyxf(num_format_str='$#,##0.00')
# or set it directly on the style object
style = easyxf('font: bold 1')
style.num_format_str = '$#,##0.00'
sheet.write(0, 0, '100.00', style)

Write excel formulas

Writing formulas is trivial with xlwt.Formula

sheet.write(0, 0, xlwt.Formula('HYPERLINK("http://yujitomita.com"; "click me")'))

Save

workbook.save("foobar.xls") 
# done!

Gotchas

Here are some things that “got” me good (took some troubleshooting).

Can’t override cells

I actually like this feature – it prevents cells from being overridden, so I’ve figured out on more than one occasion my script was failing. Why would you be overwriting a cell anyways?

# to overwrite cells, create the sheet with kwarg cell_overwrite_ok
workbook.add_sheet('foobar', cell_overwrite_ok=True) 

Valid sheet name

  • Sheets are only valid if under 31 characters
  • They can’t contain characters such as ‘:’, ‘/’. More to come I’m sure…

Style 4k limit per document

Applying styles has been made trivial, if you know the rules.

There’s a 4k limit on styles defined in a document, so I created a cached easyxf function which at least tries to pull a definition from cache before creating a new style.

class MyClass(object):
	kwd_mark = object()
	def cached_easyxf(self, string='', **kwargs):
		if not hasattr(self, '_cached_easyxf'):
			self._cached_easyxf = {}
		key = (string,) + (self.kwd_mark,) + tuple(sorted(kwargs.items()))
		return self._cached_easyxf.setdefault(key, xlwt.easyxf(string, **kwargs))

Easyxf string format

I just did a bit of experimentation to figure out the common formats.

For example, the string format appears to accept an array of key value pairs separated by a space.

‘KEY: KEY-VALUE VALUE, KEY-VALUE VALUE; KEY2: KEY-VALUE2 VALUE2’

sheet.write(0, 0, xlwt.easyxf('font: bold 1')) # bold
sheet.write(0, 0, xlwt.easyxf('font: bold 1, color: blue, underline single'))