New Programming / Shell / Vim Font

Thanks to Chris Weisel for pointing out a great new font for shells and Vim. I usually check out “great new programming fonts” and am consistently disappointed. This one is different. It is similar to Bitstream Mono, but not as heavy. That makes it more readable for me.

Font on github:
https://github.com/adobe/Source-Code-Pro

in .gvimrc (_gvimrc):
set guifont=Source_Code_Pro_Semibold:h12:cANSI

Posted in programming | Leave a comment

Easy Erg – C++ Library for the Concept 2 Rowing Machine Released

I recently open-sourced some of my code. It’s a C++ library that wraps the API and provides an ‘Erg’ class.

It currently it builds against an older version of the SDK – version 1.24 – and the current build system requires cygwin.
(There’s nothing in the wrapper code itself that requires g++, I just don’t have Visual C++ installed to create a build script or project.)
On my list is updating it to the most recent SDK.

Source is available from GitHub at:
https://github.com/kdahlhaus/easy-erg

Usage is something like this:


 ErgNet *net = ErgNet::getInstance();
        cout << "net.discoverErgs() = " << net->discoverErgs() << "\n";

        Pm3Erg erg = Pm3Erg(0);

        erg.reset();
        erg.goFinished();
        erg.goIdle();
        erg.goReady();
        erg.goInUse();

        while (1)
        {
            cout << erg.hasStartedRowing() << "  " << erg.getPaceInSecondsPer500() << " " << erg.getStrokeStateText() <<  "\n";
        } 

Posted in indoor-rowing, programming, rowing | Leave a comment

New Rowing Series on Row-2K

Row2K has posted the first video of a new web series. This one is called ‘Gut Checks.’ It is a series of short interviews with national-caliber rowers interspersed with some great rowing video.

“The one that sticks out to me is when we got 4th in the olympics by three tenths of a second. (Holds up hands) It’s about that far.”

It’s a very well done video.

http://www.row2k.com/features/784/The-Training-Center—Episode-1–Gut-Checks/#.UsxB47Sbt30

Posted in rowing | Tagged | Leave a comment

VI Joke

I have no idea where I found this. People don’t argue about editors as much as they used to. This joke was more relevant then.

Two guys are sitting in a bar, and get talking.
"What's you IQ?" one asks.
"169" is the reply.
"Wow, amazing --- my IQ's 172. What're your ideas on Hawkings latest work on
superstring theory?"
And the two get chatting and become lifelong friends.

Further down the bar, two other guys are comparing IQs.
"Mine's 104"
"Gosh, mine's 102. What do you think about the latest Cub's game?"
And the two become lifelong friends.

Even further down the bar, two other guys are also comparing IQs.
"Mine's 53."
"Wow! Mine's 54. Do you use emacs or vi?" 

Posted in programming | Tagged , | Leave a comment

RESTful API Design

I just stumbled on Geert Jansen’s book ‘Thoughts on RESTful API Design.’ Here he has documented things he learned while designing the Red Hat Enterprise Virtualization API.

The nice thing is that the source to the book is on github and you can read it on ReadTheDocs.org.

It outlines some good design decisions when creating an API and is well worth taking a look. It’s not too long of a read.

Posted in programming | Tagged , | Leave a comment

Repeating Sections in a Django Template

I have a need to have multiple sections of name/value pairs with a header on some pages. Something like:

<div class="row">
    <div class="span6">
        <div class="row"><div class="span3"><h2>History:</h2></div></div>
        <div class="row"><div class="span2">Date added to fleet:</div><div class="span2">{{plane.dateAddedToFleet}}</div></div>
        <div class="row"><div class="span2">Total Flight Time:</div><div class="span2">{{plane.totalFlightTime|asTime}}</div></div>
        <div class="row"><div class="span2">Total Number of Flights:</div><div class="span2">{{plane.totalNumberOfFlights}}</div></div>
    </div>
</div>

So that’s wrong. I first tried creating a custom tag to render the entire section that would be used like this within the django template:


{% specgroup "History" "Date added to fleet" plane.dateAddedToFleet "Total Flight Time:" plane.totalFlightTime|asTime "Total Number of Flights" plane.totalNumberOfFlights %}

The custom tag code for the above is:


# tags for groups of fields (such as on plane detail page)
@register.simple_tag
def specgroup(*args):
    """group header label1 value1 label2 value2 ...."""
    header= args[0]
    logging.getLogger().error(header)
    html = """
<div class="row">
    <div class="span6">
        <div class="row"><div class="span3"><h2>%s:</h2></div></div>
"""%header
    # parse remainder of args as  label1 value1 label2 value2 etc....
    data = args[1:]
    diter = iter(data)
    for d in diter:
        data = {}
        data["label"] = d
        data["value"] = diter.next()
        html += """  <div class="row"><div class="span2">%(label)s:</div><div class="span2">%(value)s</div></div>"""%data
    html += """
    </div>
</div>"""
    return html 

You cannot split the arguments across multiple lines to clean up the mess that is the call to the custom tag. So back to the drawing board.

I compromised with this:


{% specheader "History" %}
{% specdata "Date added to fleet" plane.dateAddedToFleet %}
{% specdata "Total Flight Time" plane.totalFlightTime|asTime %}
{% specdata "Total Number of Flights" plane.totalNumberOfFlights %}
{% specend %} 

It’s my favorite compromise between brevity and maintainability.

The custom tags to implement this are:


@register.simple_tag
def specheader(header):
    return """
<div class="row">
    <div class="span6">
        <div class="row"><div class="span3"><h2>%s:</h2></div></div>"""%header

@register.simple_tag
def specdata(label,value):
    return '<div class="row"><div class="span2">%s:</div><div class="span2">%s</div></div>'%(label, value)

@register.simple_tag
def specend():
    return "</div></div>"

Which is also cleaner than the all-in-one tag.

It’s not for me, but Skylar Savland on github created a Django Template macros with args and kwargs gist that is another solution to this problem.

I’d love to hear ideas that solve this problem in a better way.

Posted in Django, Python | 8 Comments

Rate limiting with django-ratelimit

I was playing around with James Socol’s django-ratelimit tonight. It provides a decorator to rate-limit view functions. Very nice! I wanted to use it for login blocking, and some minor changes helped this out. My forked version of django-ratelimit is a available on GitHub It adds a message when a call is blocked and the ability to clear the count for given user.

Adding it to django-userena sign-in was as simple as:

in userena/views.py:


from ratelimit.decorators import ratelimit, clear
@ratelimit(field='identification',rate="5/m", method="POST", block=True, error_message="You have too many invalid login attempts.  Please try again later")
@secure_required
def signin(request, auth_form=AuthenticationForm,.....
.
.
.
     #after successful login
     clear(request, field='identification') ### clear rate limiting 

Posted in Django, Python | Leave a comment

Custom Tag to Render Avatar in Django Userena

Here is a simple custom tag to render a users avatar (‘mugshot’) when using Django Userena. It optionally takes width and or height in pixels.

Place the following code in /templatetags/my_app_tags.py:

your_app/
    models.py
    templatetags/
        __init__.py
        my_app_tags.py


from django import template
register = template.Library()

from django import template
register = template.Library()

@register.simple_tag(takes_context=True)
def avatar(context, height=None, width=None):
    """ returns html for avatar, optional height/width supplied """
    user = context['user']
    widthAttr = 'width="%s"'%width if width is not None else ""
    heightAttr = 'height="%s"'%height if height is not None else ""
    return """<img %s %s class="avatar" src="%s"" alt="avatar image"  />"""%(heightAttr, widthAttr, user.get_profile().get_mugshot_url())

The following template shows how this could be used


{% load myapp_tags %}

{% avatar %}
{% avatar height=5 %}
{% avatar width=150 %}
{% avatar width=100 height=100 %} 
 

Posted in Django, Python | Leave a comment

Mothballed Software

We all probably have mothballed software – projects that didn’t go very far. This was one of mine, a rowing game!

Posted in programming, rowing | Leave a comment

Django Image Field Overwrite with ImageKit

I’m using django-imagekit on a new site. I was having a problem that when a user uploaded a new image for the object, the system would not overwrite the existing image file, but instead would create a new file with a sequence number on the end. This was not the behavior I was looking for. Lockjaw’s answer on StackExchange handled the not-overwriting the existing file problem. ImageKit was still caching the previous image for any specfields. The solution is to call ‘.clear()’ after saving the new image to purge the ImageKit cache for that specfield/image.

So, the total solution is:


#Lockjaw's code on StackExchange
class OverwriteStorage(FileSystemStorage):   
    def get_available_name(self, name):
        if self.exists(name):
            os.remove(os.path.join(settings.MEDIA_ROOT, name))
        return name

def issue_plane_image_path(plane, filename):
    "return the canonical file name for an image on this plane instance"
    extension = os.path.splitext(filename)[1]
    return os.path.join('photos/planes', plane.slug+extension) 

class Plane(models.Model):
    image = models.ImageField(upload_to=issue_plane_image_path, storage=OverwriteFileStorage(), null=True, blank=True)
    gallery = ImageSpecField(...)
    thumbnail = ImageSpecField(...) 

    def clearImageCache(self):
       "invalidate all ImageKit spec caches"
       self.gallery.clear()
       self.thumbnail.clear()

and in the edit view:


.
.
if form.is_valid():
   form.save()
   plane.clearImageCache()

And now each instance has very few images (usually only one, but if a person uploads different filetypes such as a PNG then a JPG, they will both exist. I am OK with that.)

Posted in Django, Python | Leave a comment