Prevent committing to master with git hooks

Currently, my git workflow consists of two branches: master and dev. The master branch is the last state of my code that was verified to work 100%. The dev branch is what I branch off of to fix bugs, add features, etc… (for very small changes I will work directly on dev). Sometimes I forget where I am, and I start coding on the master branch. In order to prevent myself from actually making commits to master I’ve added this code to my pre-commit hooks.

#!/bin/bash
 
if [[ `git symbolic-ref HEAD` == "refs/heads/master" ]]
then
    echo "You cannot commit to master!"
    echo "Stash your changes and apply them to another branch"
    echo "git stash"
    echo "git checkout branch"
    echo "git stash apply"
    exit 1
fi

This code runs right before each commit and prevents the commit if you are on the master branch. The error includes instructions on how to fix the issue by stashing your changes and applying them to a branch.

There are three ways to accomplish this:

  1. Edit an existing repo’s pre-commit hook
    Add the code to your pre-commit hook located in /.git/hooks/pre-commit.

  2. Supply a template with the --template=<template_directory> switch
    This allows you to use a different template for creating the repo, instead of the default template. This also work when performing a git clone

  3. Edit your global template
    The default global templates are located at /usr/share/git-core/templates. Add the code to the hooks/pre-commit file located in that templates folder.

Personally, I’ve edited my global pre-commit hook. I don’t see a reason why I will ever need to commit to master.

This hook will prevent you from running a first commit on a newly created repo. Use the --no-verify option on a repo’s first commit to skip the pre-commit hook.

Serving fonts with @font-face

@font-face allows you to use any font on your web page. It is supported by all major browsers, and has actually been supported by Internet Explorer for a long time.

To use @font-face, first you have to make sure that your server is returning the correct mime types for fonts. Here are the correct mime types:

  • WOFF – application/x-font-woff
  • TTF – font/ttf
  • OTF – font/otf
  • EOT – application/vnd.ms-fontobject
  • SVG – image/svg+xml

To do this in apache, add this to your .htaccess file:

1
2
3
4
5
AddType font/ttf .ttf
AddType application/vnd.ms-fontobject .eot
AddType font/otf .otf
AddType application/x-font-woff .woff
AddType application/vnd.ms-fontobject .svg

In IIS:

  1. Open IIS manager
  2. Right click your server and click properties
  3. Click Mime Types
  4. Add the above mime types

Now in your css file add the font with @font-face.

1
2
3
4
5
6
7
8
9
10
11
12
13
@font-face {
    /* Name of the font */
    font-family: 'font name'; 
 
    /* This is for IE */
    src: url(/css/fonts/font.eot);
 
    /* This is for all other browsers */
    src: local('font name'),
    url(/css/fonts/font.woff) format('woff'),
    url(/css/fonts/font.ttf) format('truetype'), 
    url(/css/fonts/font.svg) format('svg');
}

The browser will go through the fonts in the src descriptor until it successfully loads one.

You are all set to use your font now. Use your new font just like you would any other font.

1
2
3
h1 {
    font-family: 'font name', verdana, sans-serif;
}

More Info

How to make a custom ringtone or text message sound for iPhone IOS 5

  1. Add the audio file to your iTunes library
  2. Right click the file in your library and click “Create AAC Version”
  3. Drag the newly create file from your library onto your desktop
  4. Change the extension of the file from .m4a to .m4r
  5. Finally, drag the .m4r file into your device in iTunes

The file will be available in the ringtones portion of the Ringtone and Text Tone sound setting.

AJAX Requests and PHP

Recently I’ve seen a lot of questions on stackoverflow about how to detect/respond to AJAX requests. It’s actually quite simple. Most of the major players in the javascript framework will send a specific header(X-REQUESTED-WITH) to the requested page. You can check this header to detect AJAX requests.

1
2
3
4
5
6
7
8
9
if (
    isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) &&
    strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest'
) {
    // AJAX request
}
else {
    // Normal request
}

You can add this to your request object or define a constant

1
2
3
4
define(
    'IS_AJAX_REQUEST',
    (bool)isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest';
);

Example usage

1
2
3
4
5
6
7
8
9
10
// Get an array of contacts for a user
$contacts = Contacts::getForUser( $user_id );
 
// If the page was requested via ajax, json encode the array and exit the script
if ( IS_AJAX_REQUEST ) {
    die( json_encode( $contacts ) );
}
 
// Normal request, require the view
require( 'views/contacts.php' );

Frameworks verified to use the X-REQUESTED_WITH header: Prototype, Jquery, Dojo, Mootools, YUI

Managing sensitive data in git projects

Many of my projects have files that contain usernames/passwords for various services (e.g. MySQL). For a public project on Github, this is unacceptable. Here is a solution:

  1. Make a duplicate of the file named <filename>_sample and remove the sensitive data from it.
  2. Add a line to your .gitignore file to untrack/ignore the file.
  3. If the file was previously tracked you must untrack it with
    1
    
    git rm --cached <filename>

The sensitive file will not be added to your future commits.

Linking GitHub commit messages to issues

When performing a GitHub commit you can link the commit message to an issue:

1
git commit -m "fixed bug, closes #1"

Adding this closes will close the issue and link the commit message to the newly closed issue.

Alternate syntaxes:

1
2
Closes GH-1.
Closes gh-1.

Here’s an example

Changing the marker icon in a Google Fusion Table

By default, when displaying a Fusion Table, the marker icon is a small red dot. To get a normal marker icon follow these steps:

  1. Go into the admin of your Fusion Table
  2. In the menu go to Visualize > Map
  3. Above the map click the link “Configure styles”
  4. In the left menu of the window that pops up click the “Marker icon” link
  5. There are a bunch of options, but if you just want to change all of the marker icons, under the “Fixed” tab select the marker you want to use
  6. Click “Save”

Making wordpress parent navigation items unclickable with jquery

I’m developing a new site that has a navigation that is built dynamically via wordpress’ wp_list_pages function

1
<?php  wp_list_pages('sort_column=menu_order&title_li=&exclude=6'); ?>

Navigation items that have submenus (css dropdowns) are still clickable, but for this website they have no content. I wanted a way to make those items unclickable. I was unable to find any way with wordpress’ api, but I did find a way with jquery.

1
2
3
4
5
6
$('#navigation_ul > li > a').filter(
    function() {
        return $(this).siblings().length > 0
    }
).attr( 'href', '#' )
 .attr( 'onClick', 'return false' );

All navigation links that have submenus will have their href to ‘#’, and onClick set to ‘return false’.

Accessing dictionaries inside lists with Django templates

Today while working on the new SVO I ran into an issue with the coding of breadcrumbs. I wanted to pull the breadcrumb code out of each page template and put it into the header template.

This is what I had originally in each template:

1
2
3
4
5
6
<p id="breadcrumbs">
    <a href="/">Home</a><span class="bc_sep">></span>
    <a href="{% url videos %}">Videos</a><span class="bc_sep">></span>
    <a href="{% url company video.company.id video.company.name|slugify %}">{{ video.company.name }}</a><span class="bc_sep">></span>
    <strong>{{ video.name }}</strong>
</p>

This quickly became annoying, repeating this code in every page’s template. I decided to create a list of dictionaries inside each view to represent the breadcrumbs:

1
2
3
4
5
breadcrumbs = []
breadcrumbs.append( { 'home':reverse( 'home' ) } )
breadcrumbs.append( { 'skaters':reverse( 'skaters' ) } )
breadcrumbs.append( { index:'' } )
return render_to_response('index.html', {...'breadcrumbs':breadcrumbs})

Then in my template I loop the list and dictionary:

1
2
3
4
5
6
7
8
9
10
11
<p id="breadcrumbs">
{% for breadcrumb in breadcrumbs %} #this loops the list
	{% for text, link in breadcrumb.items %} #this extracts the dictionary inside each list
		{% if link %}
			<a href="{{ link }}">{{ text|capfirst }}</a><span class="bc_sep">></span>
		{% else %}
			<strong>{{ text|capfirst }}</strong>
		{% endif %}
	{% endfor %}
{% endfor %}
</p>

CSS & Javascript image preloader

While building a photo gallery for a client I ran into an issue where the photos took too long to load and clicking thumbnails before all the photos loaded resulted in ugly transitions.

My solution was to put a semi-transparent “shield” (containing a loading animation) over the gallery. The user will be able to see the images loading, but will be unable to click anything until all images are loaded and the shield is hidden.

Explanation follows the code.

Here’s the html. This goes inside the div that contains your gallery.

1
2
3
4
<div id="gallery_loader"> <!-- wrapper for shield -->
    <div></div> <!-- this is the actual shield -->
    <img src="animated_loader.gif"><!-- image preloader -->
</div>

…and the CSS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#gallery_loader {
    position:absolute; /* Position the wrapper at the top left corner */
    top:0;
    left: 0;
    width:100%; /* cover the entire width of your gallery */
    height:100%; /* cover the entire height of your gallery */
    overflow:hidden; /* hide anything that might overflow */
    z-index:999; /* make sure the shield is on top over everything */
}
#gallery_loader div { /* the actual shield */
    position:absolute; /* Position the shield at the top left corner of the wrapper */
    top:0;
    left:0;
    width:100%; /* Take up the entire wrapper */
    height:100%; /* Take up the entire wrapper */
    background: #fff;
    opacity: .8; /* .8 = 80% opacity for all non-ie browsers*/
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=80)"; /* This and the next style are for IE */
    filter: alpha(opacity=80);
}
#gallery_loader img {
    position:relative;
    display:block; /* Need this so we can center the image */
    margin: 150px auto 0 auto; /* Set this to whatever looks good */
    padding: 30px; /* Adjust to your needs */
    background: #fff;
    border: 1px solid #333;
    -moz-border-radius:5px; /* Round corners in mozilla browsers */
    -webkit-border-radius: 5px; /* Round corners for webkit browsers */
}

Put this inside an included javascript file. This will wait until the page is loaded entirely (images and all) and then fade the loader out. Requires jquery.

$(window).bind("load", function() {
	$('#gallery_loader').fadeOut();
});

#gallery_loader is positioned absolutely and placed on top of everything else (z-index:999). It’s set to take up the entire width/height of its parent. Next comes the shield that will actually do the “blocking” of everything in the gallery. The shield is opacited and set to take up the entire width/height of the wrapper. Finally the animated loading image is loaded and centered.

As you can tell from the HTML, the actual shield is not the container of the loading animation gif. This is because the children of transparent elements can’t be more opaque than their parents. In other words if we put the loading image inside the transparent “shield” (which has an opacity of 80%) it would have a max opacity of 80%. To fix this we put the “shield” underneath the loading image and opacitate it. Here’s a good page on opacity.

Note: If you’re having issues where the loading gif isn’t loading immediately add this right after the opening of your body element

1
2
3
<body>
<img src="animated_loader.gif" style="display:none">
...

This will cause the loading gif to load first.

Here is where I obtained my loading gif