convert png to windows icon .ico file for favicon in ubuntu Dec
21
1
0

I've never had a great way of making windows icon files (.ico). I used to use the icon editor in Visual Studio in the past, but I haven't programmed in Windows for years and I don't have access to VS anymore. I've always felt there had to be a way to convert a png to ico file. Even Photoshop doesn't have this built in: for that you need a plugin.

It took me a while, but there's a way to do it using some of the packages from netpbm. If you're using Ubuntu you're in luck, as with most things it's just an apt-get away.

sudo apt-get install netpbm

Next, I'll start with a 16x16, 32x32 or 48x48 square pixel PNG. I tend to use the 32x32 size.

For this example I start with a 32x32 favicon.png, convert it to an intermediary pnm file, force the scaling to a ppm file, convert to 256 color space, and compile it into an ico file with the following set of commands.

pngtopnm -mix favicon.png > tmp_favicon.pnm

pnmscale -xsize=32 -ysize=32 tmp_favicon.pnm > tmp_favicon32.ppm
pnmscale -xsize=16 -ysize=16 tmp_favicon.pnm > tmp_favicon16.ppm

pnmquant 256 tmp_favicon32.ppm > tmp_favicon32x32.ppm
pnmquant 256 tmp_favicon16.ppm > tmp_favicon16x16.ppm

ppmtowinicon -output favicon.ico tmp_favicon16x16.ppm tmp_favicon32x32.ppm
rm -f tmp_favicon*

This method gave me what I needed: an ico file that I could use for a favicon and include as a windows icon for a binary executable.

comments

getting parent path of current directory in python Dec
10
1
0

The following code extracts the parent path of your current working directory, or any path value, in Python. I'm not sure if there's a way to automatically walk up and down through the directories, but this worked for me and was nice and small.

It works by splitting the path on "/", removes the last element in the array, then joins everything back together.

import os

path = os.getcwd()
parent_path = os.sep.join(path.split(os.sep)[:-1])

comments

custom user profile and extending the user admin in django Dec
08
1
0

In almost every project I do these days I need to extend and add fields to the default Django User model to store things like profiles, preferences, history etc.... One way to do this is to create a new model that inherits off of the django User class and use that class for authentication. This is usually not the best idea. In my case it got complicated integrating this change back into third party applications even when setting the AUTH_PROFILE_MODULE and writing a custom authentication backend.

The method I have been using lately works off a custom Model that links back to the User through a OneToOneField: based off the docs this is the recommended way to extend the django user. I find this method much cleaner to work with, and ultimately more compatible and maintainable. For instance I can work in my additions to the User in parallel with other applications. This is not possible if we are all inheriting off the User.

One of the main arguments that I hear against using a OneToOneField over Inheritance is that it creates extra database calls. This is not true. Perhaps a little known fact is that django implements model inheritance through a one-to-one relation: accessing fields from the subclass will do a query and accessing fields from the parent will do another query, so you're doing the same amount of queries either way. It's been mentioned that sub-classing models is not the right solution in most cases.

The following technique is not specific to extending just the User. This is a way to add additional attributes to an existing model written anywhere else in the project without having to modify the original source code. You can then make the additions show up in the admin by registering a custom extended ModelAdmin. This is essentially the same way I add additional properties to Satchmo products for e-commerce shops, although there are additional steps I need to take that are specific to Satchmo.

For this example lets do something simple, lets say something like adding a user profile for a blog that gives me the ability to create an avatar and a biography description for each user.

I'll first start out by defining a custom profile model class that'll attach the desired fields to the django user model.

I want to create this model whenever a user is created so I'll also add a profile creation method to the post_save signal for the User model.

# models.py
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User


class UserProfile(models.Model):
    user = models.OneToOneField(User)
    avatar = models.ImageField(upload_to='uploads/avatars', default='', blank=True)
    biography = models.TextField(default='', blank=True)

    def __unicode__(self):
        return self.user.username


def create_user_profile(sender, instance, created, **kwargs):
    """Create the UserProfile when a new User is saved"""
    if created:
        profile = UserProfile()
        profile.user = instance
        profile.save()

post_save.connect(create_user_profile, sender=User)

This is a great start. The above code will provide me the ability to add additional fields to the django user with minimal intervention. This might be all I actually need, but I like to push things further; and in this case it's a good idea to make the user profile available in the admin.

Although I could have the admin autodiscover the model like usual, I find it much more efficient to inline the UserProfile into the existing User admin view. To do this I create an inline for the new profile and add it to a custom UserAdmin class that inherits off of the django UserAdmin class.

The process of replacing an existing registered model admin is easy, you just need to remember to unregister the model first. This gives me the ability to adjust the default django user admin view without having to modify any core code.

# admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

from django.contrib.auth.models import User
from models import UserProfile


class ProfileInline(admin.StackedInline):
    model = UserProfile
    fk_name = 'user'
    max_num = 1


class CustomUserAdmin(UserAdmin):
    inlines = [ProfileInline,]


admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

An optional step is to can add AUTH_PROFILE_MODULE in settings.py. I tend NOT to do this because other applications that I integrate, like Satchmo, already have this field set and I don't want step on anyone's toes.

Lets say I put models.py and admin.py in an application named 'custom'.

# settings.py
AUTH_PROFILE_MODULE = 'custom.UserProfile'

This setting allows me to pull the profile off of the django user with the get_profile() method.

profile = user.get_profile()

It's handy but not necessary. You can always get the profile the old-fashioned way:

profile = user.userprofile

I hope this explanation helps. I'm jotting it down mainly so I can refer back to it later as I tend to forget where things are located and what I need to include. There could be a better way to do things, but this has worked for me and hopefully it'll be helpful for someone else. As always feedback and comments are welcome.

Happy coding!

comments

stupid simple web server with python Dec
08
1
0

If you need to set up a basic web server really fast and you don't want to go through the hassle of setting up nginx, apache or another production-level web server you can just use Python. If you're lucky like me you're already developing in it anyway.

Python comes with a simple web server built in: SimpleHTTPServer

All you need to do is to change to the directory you want to host and call it:

cd /path/to/directory
python -m SimpleHTTPServer

That's all there is to it. You'll then be serving rooted to that directory. You can access it through localhost, 127.0.0.1, or your inet IP.

It will look for and automatically host index.html. If index.html isn't found then it will list the contents of the directory specified.

http://localhost:8000
http://192.168.1.###:8000

The default port is 8000, but you can easily change it. One things I use this for is when I need to initiate more than one simple server at once.

python -m SimpleHTTPServer 8080

Keep in mind that this is a single threaded server and it breaks easily. This most definitely should NOT be used in production.

Among other things this an easy way to transfer files between computers through your local network using only Python.

reference: http://www.linuxjournal.com/content/tech-tip-really-simple-http-server-python

comments

git-aware ps1 Nov
19
1
0

http://blog.bitfluent.com/post/27983389/git-utilities-you-cant-live-without

You'll need git-completion.bash working, but put the following line into your .bashrc or .bash_profile to display the current branch in your terminal.

PS1='$(__git_ps1 "(%s)")$ '

Which you can combine with whatever you already have setup. It can be something similar to one of the following:

PS1='\h:\W$(__git_ps1 "(%s)") \u\$ '
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\ $(__git_ps1 "(%s)")$ '
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] $(__git_ps1 "(%s)")$ '

comments

installing a lamp stack on ubuntu Nov
17
1
0

If you're ever in the unfortunate position where you need to install a LAMP stack (Linux, Apache, MySQL, PHP) on an Ubuntu server, you can install the following modules to quickly get yourself up and running.

apache2 php5-mysql libapache2-mod-php5 mysql-server

sudo apt-get install apache2
sudo apt-get install php5-mysql
sudo apt-get install libapache2-mod-php5
sudo apt-get install mysql-server

Or, for the super lazy use tasksel:

sudo tasksel install lamp-server

Good luck and godspeed.

comments

random string and digit generation in python Nov
17
1
0

This snippet generates a random string with digits with a defined LENGTH in Python. Useful for things like generating random passwords.

import os
import string


LENGTH = 6

password = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(LENGTH))

comments

using the for loop counter in python Nov
17
1
0

Even with all the powerful tools Python loops do for you, sometimes you need to grab the good ol' loop counter.

There are a couple of different ways you can do this. The cleanest method that I found so far is to use the enumerate function. You can do something like this:

test = ['a', 'b', 'c']

for counter, value in enumerate(test):
    print counter, value

comments

detect and change html named anchor tags in the url through javascript and jquery Oct
06
1
0

You may already be familiar with using html named anchor tags to auto-scroll the page to a certain section in an html page, which would look something like this:

<a id="button" href="#tag">link</a>

...

<a name="tag">anchor</a>

An alternative use for anchor tags is to change and detect the tag value in the url on the fly in order to initialize certain states with javascript-driven content. This is handy as it lets people bookmark the location and the page will initialize properly even in heavy ajax environments. It's surprisingly easy to interact dynamically with the url anchor tag object.

You can detect the current anchor value of the url in javascript through "location.hash" like this:

if(location.hash == '#tag') {
    // initialize content
    ...
}

You can also dynamically change the anchor tag in the url just by setting "location.hash" like so:

// location.hash = 'value';

$('a#button').click(function(event) {
    event.preventDefault();

    // set the anchor value
    // I like to strip the hash out of the href value; you can use your own method of choice to determine the anchor.
    location.hash = $(this).attr('href').replace('#', '');

    // do something important
    ...
});

These examples use JQuery to simplify the code.

comments

restricting views to staff users in django Sep
02
1
0

Hopefully you've already found the login_required decorator for Django views, which make it incredibly simple to integrate authentication into the site.

One thing that's not documented well is there's another decorator @staff_member_required. This works the same way @login_required does except it restricts access to users who are both authenticated and has staff status set in their settings.

This comes in handy when extending the admin or writing custom moderation applications.

You can do something similar to:

from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.contrib.admin.views.decorators import staff_member_required


@staff_member_required
def view(request):

    ...

    return render_to_response('template.html', context_instance=RequestContext(request))

comments