<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><atom:link rel="hub" href="http://tumblr.superfeedr.com/" xmlns:atom="http://www.w3.org/2005/Atom"/><description>I am a freelance developer and iPhone hacker. I love making things, but I also love breaking them.</description><title>Conrad Kramer</title><generator>Tumblr (3.0; @conradev)</generator><link>http://blog.kramerapps.com/</link><item><title>Enhancing Git on OS X</title><description>&lt;p&gt;Git is a distributed version control system that has grown to be wildly popular among developers. It was created for use in managing the Linux kernel, and has since expanded to all walks of software development. It has become standard in iOS and OS X development, for use as dependency management, if nothing else. Git is extremely popular in other places, as well. Regardless of what git is used for, there are a number of enhancements that can be made to improve its usability. I outlined a few of them, tailored for OS X, in this article.&lt;/p&gt;

&lt;h2&gt;Installing Git&lt;/h2&gt;

&lt;p&gt;There are many ways to install git on OS X, but I am only going to discuss one of them in this blog post, using the &lt;a href="http://mxcl.github.com/homebrew/"&gt;Homebrew&lt;/a&gt; package manager for OS X. Installing git through Homebrew downloads the latest stable release of git, compiles it, and installs it to the ‘cellar’, usually located in &lt;code&gt;/usr/local/&lt;/code&gt;. The advantage in using a package manager like Homebrew or MacPorts to install git is that your machine is always running the latest version of it.&lt;/p&gt;

&lt;p&gt;Assuming you have Homebrew installed, git can be installed with one command:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;brew install git
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Color&lt;/h2&gt;

&lt;p&gt;Git can be configured to color its output so that it is easier to read and understand. For example, if colors are enabled, changes staged for commit are colored in green in the output of &lt;code&gt;git status&lt;/code&gt;, whereas those that are not are colored in red. This allows the user to easily and quickly distinguish between the two. Color is not enabled by default, but can be enabled with one command:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git config --global color.ui true
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Bash Completion&lt;/h2&gt;

&lt;p&gt;When using git in a shell, typing out long commands can often be a hassle. Installing bash completion for git will save you a lot of time, allowing you to tab complete all of your commands. It is very easy to set up, especially if you are using Homebrew. You only need to install the &lt;code&gt;bash-completion&lt;/code&gt; package:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;brew install bash-completion
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and then add the following to your &lt;code&gt;~/.bash_profile&lt;/code&gt; file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;if [ -f $(brew --prefix)/etc/bash_completion ]; then
  . $(brew --prefix)/etc/bash_completion
fi
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and voila! Git should now tab-complete all of your commands.&lt;/p&gt;

&lt;p&gt;In addition to bash completion, aliases can also be defined to shorten the time required to enter long commands. The only problem with aliases is that they can become embedded in muscle memory, and are only local to your own machine. This means that if you login into an arbitrary server, or use your friends computer, the aliases will not be there to help you. It may only cause frustration, but you also may forget the underlying command behind the alias. Regardless, adding aliases is as simple as one command. For example, to alias &lt;code&gt;checkout&lt;/code&gt; to &lt;code&gt;co&lt;/code&gt;, you can enter:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git config --global alias.co checkout
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Prompt&lt;/h2&gt;

&lt;p&gt;Git also comes with a handy utility to add information about the current repository to your bash prompt. Having git status in the prompt provides a heads up display of whether the current directory is under version control or not, and can also provide basic information, like which branch is currently checked out. This feature can be easily set up, assuming you installed git and bash-completion with Homebrew, by adding the following to your &lt;code&gt;~/.bash_profile&lt;/code&gt; file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;source $(brew --prefix)/etc/bash_completion.d/git-prompt.sh
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;__git_ps1&lt;/code&gt; function is now available in your shell. You can then use it in your prompt like the example below, which adds the current branch to the default prompt in OS X:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;PS1="\h:\W \u\$(__git_ps1 \" (%s) \")\$"
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Github Integration&lt;/h2&gt;

&lt;p&gt;It you happen to use Github for hosting your git repositories (and enhancing your git workflow), there is a convenient tool that can integrate some of Github’s functionality into your command line. The tool is called &lt;a href="https://github.com/defunkt/hub"&gt;Hub&lt;/a&gt;. One feature it adds is short-hand notation for repositories, assuming that the repository is hosted on github. For example, it can shorten&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git clone git://github.com/conradev/QuickQR.git
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;to&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git clone conradev/QuickQR
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In addition to short-hand, Hub also adds Github specific functionality to your command line, like the ability to open pull requests. If you are working on a topic branch, and want to open a pull request, you need only type&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git pull-request
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and you can type up a pull request in your text editor. Installing hub is also a breeze. To install it with Homebrew, you can type&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;brew install hub
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This installs the ‘hub’ command to your PATH. It acts as an intermediary layer on top of git, meaning it uses git to execute the commands you enter, after preprocessing them a bit. To integrate hub seamlessly (as seen in the examples above), you can alias git to hub, by adding the following to your &lt;code&gt;~/.bash_profile&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;eval "$(hub alias -s)"
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Graphical Components&lt;/h2&gt;

&lt;p&gt;When working with git, graphical components in one’s workflow can be of great aid in doing specific tasks. If you have had to conduct an extensive merge manually, for example, you know that it can become a nightmare. Git was created with this limitation in mind. Git allows for external diff and merge tools to act as front-ends to aid in those operations. The guys at &lt;a href="http://blackpixel.com"&gt;Black Pixel&lt;/a&gt; created an awesome OS X application for comparing and merging files, named &lt;a href="http://www.kaleidoscopeapp.com"&gt;Kaleidoscope&lt;/a&gt;. With a couple clicks, it will install a command line tool and add itself to your git configuration as a diff and merge tool. To conduct a complex merge, you can use &lt;code&gt;git mergetool&lt;/code&gt; as opposed to &lt;code&gt;git merge&lt;/code&gt;, and Kaleidoscope will be opened for resolving any conflicts. There are also tools out there that allow you to interact with a git repository graphically, one of the most popular on OS X being &lt;a href="http://www.git-tower.com"&gt;Git Tower&lt;/a&gt;. Graphical managers allow you to commit code, manage branches and do anything you want with the click of your mouse.&lt;/p&gt;

&lt;p&gt;I personally do not use Git Tower, as I prefer git on the command line. I prefer it because I like to know exactly what I am executing, when I execute it, and because shell is portable. This is why I like Kaleidoscope as a diff/merge tool, because it is invoked from the command line only when needed. Regardless, deciding whether or not to use a graphical manager is a matter of personal preference.&lt;/p&gt;

&lt;h2&gt;Get Coding!&lt;/h2&gt;

&lt;p&gt;The hope in making git more usable is that it transforms from a necesary and annoying task into one that is efficient and enjoyable. This way, you can spend more time coding, and less time dealing with version control. So, get coding!&lt;/p&gt;

&lt;p&gt;Feel free to &lt;a href="http://twitter.com/conradev"&gt;follow me&lt;/a&gt; on Twitter or check out &lt;a href="https://kramerapps.com"&gt;my&lt;/a&gt; &lt;a href="https://github.com/conradev"&gt;software&lt;/a&gt;. Additionally, if your company is hiring mobile dev interns this upcoming summer, and has no inhibitions hiring a high school student, be sure to &lt;a href="http://conrad@kramerapps.com"&gt;get in touch&lt;/a&gt;.&lt;/p&gt;</description><link>http://blog.kramerapps.com/post/40839091386</link><guid>http://blog.kramerapps.com/post/40839091386</guid><pubDate>Fri, 18 Jan 2013 08:23:31 -0500</pubDate></item><item><title>A Quicker QR Code Scanner </title><description>&lt;p&gt;&lt;a href="http://en.wikipedia.org/wiki/QR_code"&gt;QR codes&lt;/a&gt; have become very popular in the advertising industry. They are slapped onto flyers, business cards and many other marketing materials with the hope that consumers will scan them. QR codes sound like a great idea in writing, but they are faced with many problems being adopted in the real world. One of these problems is the neglect of QR codes by smartphone manufacturers. There are a plethora of applications available for each given smartphone to scan QR codes, but the fact that they are third party detracts from their value. They don’t come pre-installed, involve hassle to activate, and each one is different, causing fragmentation. Countless times have I seen a QR code only to be deterred by the fact that I must first unlock my iPhone, navigate to a page of rarely used applications, open a QR code scanner, and wait for the camera to initialize. If smartphone manufacturers adopted QR codes and integrated scanning functionality into their software, all of these problems would be solved. In Japan, for example, QR codes are immensely popular and almost all phones have QR code scanning functionality. I don’t know which one caused the other, but it does seem as if those two things go hand in hand. In the US, the only smartphone (that I know of) that has QR code scanning functionality built in is Windows Phone, with &lt;a href="http://www.windowsphone.com/en-us/how-to/wp7/web/scan-codes-tags-and-text"&gt;Bing Vision search&lt;/a&gt;. Google also has a visual search platform, &lt;a href="http://en.wikipedia.org/wiki/Google_Goggles"&gt;Google Goggles&lt;/a&gt;, with apps on iOS and Android, but the functionality has not yet been integrated into Android itself.&lt;/p&gt;

&lt;p&gt;Interestingly enough, Apple has adopted 2D barcodes (including QR codes) in its new Passbook service in iOS 6. By doing this, Apple is expressing confidence that 2D barcodes will continue to be relevant for a long time to come. It would only make sense for them to integrate QR code scanning into iOS. As some have &lt;a href="http://techcrunch.com/2012/09/01/how-apple-and-google-could-make-qr-codes-mainstream/"&gt;suggested&lt;/a&gt;, this could be done by making the camera application a bit smarter, to automatically look out for QR codes. That article does get one thing wrong, though, in saying that the idea is “probably not as simple to implement as it seems”. As it turns out, the idea &lt;em&gt;is&lt;/em&gt; simple to implement, at least on iOS.&lt;/p&gt;

&lt;h2&gt;Analyzing The Camera&lt;/h2&gt;

&lt;p&gt;In order to integrate QR code scanning functionality into the camera, I first needed to understand how the camera works. I did this by reverse engineering Apple’s software. I discussed popular tools that I use to reverse engineer software in my previous &lt;a href="http://kramerapps.com/blog/post/38090565883/integrate-cloud-print-ios"&gt;blog post&lt;/a&gt;. The framework that controls basic camera interactions on iOS is the private framework PhotoLibrary. The framework includes the view controllers that display the Camera Roll and also the controller that is responsible for taking photos, &lt;code&gt;PLCameraController&lt;/code&gt;. These controllers are not only used in the Camera application, but are also used to back the public &lt;code&gt;UIImagePickerController&lt;/code&gt; class. The PhotoLibrary framework is based on the public AVFoundation framework. Here is the interface for &lt;code&gt;PLCameraController&lt;/code&gt;, abridged to only show the parts we care about:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@interface PLCameraController : NSObject {
    AVCaptureDeviceInput *_avCaptureInputFront;
    AVCaptureDeviceInput *_avCaptureInputBack;
    AVCaptureDeviceInput *_avCaptureInputAudio;
    AVCaptureStillImageOutput *_avCaptureOutputPhoto;
    AVCaptureMovieFileOutput *_avCaptureOutputVideo;
    AVCaptureVideoDataOutput *_avCaptureOutputPanorama;
}

+ (instancetype)sharedInstance;

@property(weak, nonatomic) AVCaptureOutput *currentOutput;
@property(weak, nonatomic) AVCaptureDeviceInput *currentInput;
@property(readonly, strong, nonatomic) AVCaptureSession *currentSession;
@property(readonly, strong, nonatomic) AVCaptureVideoPreviewLayer *previewLayer;

@end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see, the basic structure of the camera controller is an &lt;code&gt;AVCaptureSession&lt;/code&gt; with a number of inputs and outputs. The microphone, front and back cameras function as inputs, and there are outputs for taking photos, videos, and panorama shots. When I first looked into the PhotoLibrary framework before iOS 6 was released, these observations led me to &lt;a href="http://www.wired.com/gadgetlab/2011/11/enable-secret-panorama-feature-in-ios5/"&gt;discover&lt;/a&gt; the then unreleased Panorama mode.&lt;/p&gt;

&lt;h2&gt;Adding QR Code Scanning&lt;/h2&gt;

&lt;p&gt;Once I knew the basic structure of the PhotoLibrary framework, I was able to work on integrating a QR code scanner into it. The library I used to read QR codes was &lt;a href="http://code.google.com/p/zxing/"&gt;ZXing&lt;/a&gt;, pronounced “zebra crossing”. It is a popular open source library for interpreting 2D barcodes, originally written in Java, and then ported to C++. There are also Objective-C wrappers available in the source distribution (two of them, in fact), but I found both heavy-handed for my purposes. In addition, both Objective-C wrappers process image data on the main thread, which I found to cause noticeable interface lag. I chose instead to write a small class (100 lines) that implements the functionality I need. The class I wrote takes data from a &lt;code&gt;AVCaptureVideoDataOutput&lt;/code&gt; and processes it with the ZXing C++ library on a private queue.&lt;/p&gt;

&lt;p&gt;Thanks to Apple’s straightforward &lt;a href="https://developer.apple.com/library/ios/#documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/04_MediaCapture.html"&gt;media capture API&lt;/a&gt; in AVFoundation, it is easy to add arbitrary outputs to a capture session. All I needed to do was create an instance of my class, and add the video data output to the session in the camera controller, and just like that, I was recognizing QR codes. The implementation was just as straightforward as the idea. I made something to read QR codes, and quite simply added it into the Camera. Don’t believe me? Check out the &lt;a href="https://github.com/conradev/QuickQR"&gt;source code&lt;/a&gt;! I also made a video, demonstrating the tweak in action:&lt;/p&gt;

&lt;iframe width="560" height="315" src="http://www.youtube.com/embed/HQNB9XZdPCk" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt;

&lt;p&gt;&lt;br/&gt;&lt;/p&gt;

&lt;p&gt;If you are interested in tweaking iOS, be sure to check out my previous &lt;a href="http://kramerapps.com/blog/post/38090565883/integrate-cloud-print-ios"&gt;blog post&lt;/a&gt; for a more in-depth discussion. Feel free to &lt;a href="http://twitter.com/conradev"&gt;follow me&lt;/a&gt; on Twitter or check out my &lt;a href="http://kramerapps.com"&gt;software&lt;/a&gt;. Additionally, if your company is hiring mobile dev interns this upcoming summer, and has no inhibitions hiring a high school student, be sure to &lt;a href="http://conrad@kramerapps.com"&gt;get in touch&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Discuss on Hacker News &lt;a href="http://news.ycombinator.com/item?id=5016497"&gt;here&lt;/a&gt;&lt;/p&gt;</description><link>http://blog.kramerapps.com/post/39821344121</link><guid>http://blog.kramerapps.com/post/39821344121</guid><pubDate>Sun, 06 Jan 2013 02:41:00 -0500</pubDate></item><item><title>Integrating Google Cloud Print into iOS</title><description>&lt;p&gt;Setting up my family&amp;#8217;s Chromebox was easy, until someone needed to print something. Google decided that in Chrome OS, the only method for printing should be through its &lt;a href="http://www.google.com/cloudprint/learn/"&gt;Cloud Print&lt;/a&gt; service. Google Cloud Print is a service that provides a API for printing, both to send print jobs and to receive them. This is an example of forward thinking by Google, and greatly simplifies the experience in Chrome OS. However, this adds complexity for the consumer. I ended up configuring the printer in my house using an open source &lt;a href="https://github.com/armooo/cloudprint"&gt;bridge&lt;/a&gt; running on a Linux server. Once I configured it properly, I began to really appreciate the advantages of Cloud Print. I enjoyed being able to print documents to my physical printer, and PDF files to my Google Drive, from anywhere in the world. Being able to print directly from Gmail is also awesome. However, I missed these luxuries on the device that I use the most, my iPhone.&lt;/p&gt;

&lt;p&gt;Beginning with iOS 4.2, Apple introduced AirPrint as a method to print over the local network. Since then, Apple’s core applications, and many others, have added print functionality. I wanted to be able to print natively on iOS, but using Google’s Cloud Print service. The problem is, as Marco Arment &lt;a href="http://the-magazine.org/4/anti-apple-anger"&gt;writes&lt;/a&gt;, Apple is in the business of saying “no”. No to customizing the interface, and no to modifying the operating system. This is what I consider the biggest advantage of &lt;a href="http://en.wikipedia.org/wiki/IOS_jailbreaking"&gt;jailbreaking&lt;/a&gt;. Jailbreaking gives you the ability to sidestep Apple, and say “yes”. Not only this, but developing software for jailbroken devices, in the form of &amp;#8220;tweaks&amp;#8221;, proves to be a fun challenge. This is an account of how I integrated Google Cloud Print into Apple&amp;#8217;s existing AirPrint functionality.&lt;/p&gt;

&lt;h2&gt;Building The Client&lt;/h2&gt;

&lt;p&gt;The first step to integrate Google Cloud Print into iOS was to implement a client. Google documents the &lt;a href="https://developers.google.com/cloud-print/docs/appInterfaces"&gt;Cloud Print API&lt;/a&gt; on their website, so the only thing that I needed to do was write a client for it. There are &lt;em&gt;many&lt;/em&gt; ways to approach this, but I wanted to try something I have not tried before. I decided to delve into Core Data with Mattt Thompson’s &lt;a href="https://github.com/AFNetworking/AFIncrementalStore"&gt;AFIncrementalStore&lt;/a&gt;. AFIncrementalStore is a relatively new project, with the ambitious goal of mapping Core Data to a RESTful web service. I created a data model with &lt;code&gt;Job&lt;/code&gt; and &lt;code&gt;Printer&lt;/code&gt; entities, and implemented an &lt;code&gt;AFRESTClient&lt;/code&gt; subclass to interact with the API. AFIncrementalStore is intended to be transparent, so I need only execute standard Core Data calls to use it. To fetch a list of all printers in alphabetical order, I can execute a standard &lt;code&gt;NSFetchRequest&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Printer"];
fetchRequest.sortDescriptors = @[ [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES] ];
NSArray *printers = [context executeFetchRequest:request error:nil];
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To send a job to a given printer, I can insert a new Job entity into the context, and a request will be fired off in the background, transparently. Here is an example of sending a job to a printer:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;CPJob *job = [NSEntityDescription insertNewObjectForEntityForName:@"Job" inManagedObjectContext:context];
job.title = @"TestJob";
job.printer = printer;
job.fileData = [NSData dataWithContentsOfFile:filePath];
job.contentType = @"application/pdf”;
[context save:nil];
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It is pretty cool to not have to interact with the network layer to use a RESTful API. For my purposes, I have found this approach to be great, but Core Data is not for everything or everyone. It is general knowledge among iPhone developers that Core Data is difficult to get right, and that when things do go wrong, they go &lt;em&gt;horribly&lt;/em&gt; wrong. In this project, there are relatively few objects in the store, and the relationships between them are simple. I have yet to come across a serious problem (&lt;em&gt;knocks on wood&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;In addition to interacting with the Cloud Print API, the client also needed to authenticate using &lt;a href="http://oauth.net/2/"&gt;OAuth2&lt;/a&gt;. There are many implementations of OAuth2 on iOS, but I was attracted to &lt;a href="https://github.com/AFNetworking/AFOAuth2Client"&gt;AFOAuth2Client&lt;/a&gt; in particular, because it is based on AFNetworking, just as AFIncrementalStore is. However, AFOAuth2Client in its current state is terribly outdated and feature incomplete. This led me to give it an &lt;a href="https://github.com/AFNetworking/AFOAuth2Client/pull/6"&gt;overhaul&lt;/a&gt; to better conform to the OAuth2 spec, and to add some features. One feature I added was the ability to easily store tokens in the keychain for safe storage.&lt;/p&gt;

&lt;h2&gt;Diving Into PrintKit&lt;/h2&gt;

&lt;p&gt;In order to integrate Google Cloud Print into iOS, it was integral to understand how Apple approaches the problem of printing on iOS. All of Apple&amp;#8217;s magic lies in a private framework on iOS named &lt;code&gt;PrintKit.framework&lt;/code&gt;. To understand this magic, I conducted static and dynamic analysis. For disassembly and static analysis, I have a copy of &lt;a href="http://www.hex-rays.com/products/ida/index.shtml"&gt;IDA Starter&lt;/a&gt;, which is considered to be the standard in static analysis. I also use &lt;code&gt;class-dump&lt;/code&gt;, which parses the Objective-C metadata in a binary, and uses the data to generate readable class definitions. For dynamic analysis, I use Jay Freeman’s &lt;a href="http://www.cycript.org"&gt;cycript&lt;/a&gt;, pronounced “sscript”, a hybrid between JavaScript and Objective-C. The interpeter can inject into a running process and provide a shell to do just about anything you want.&lt;/p&gt;

&lt;p&gt;From analyzing PrintKit, I determined a few useful pieces of information. PrintKit has two components, the framework itself and its associated daemon. The first component, the framework, is relatively small with only six classes. Each class is a wrapper over a portion of the &lt;a href="http://www.cups.org/documentation.php/doc-1.5/api-cups.html"&gt;CUPS API&lt;/a&gt;, which is compiled into the framework. You can see this for yourself by looking at the symbols in the framework (you must run this on OS X with the iOS SDK installed in order for it to work):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;conradev@air :: ~ » nm $(xcode-select --print-path)/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.0.sdk/System/Library/PrivateFrameworks/PrintKit.framework/PrintKit | grep -c cups 
328
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The second component, the daemon, is known as &lt;code&gt;printd&lt;/code&gt;. It is configured with &lt;code&gt;launchd&lt;/code&gt; to listen over a UNIX socket. &lt;code&gt;printd&lt;/code&gt; is actually a modified version of the CUPS daemon. This can be seen from its usage page (you must run this on a jailbroken iPhone in order for it to work):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;iPhone:~ root# /System/Library/PrivateFrameworks/PrintKit.framework/printd -h
CUPS v1.5.0
Copyright 2008-2010 by Apple Inc.  All rights reserved.
...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The framework and daemon communicate over the UNIX socket the same way they would normally be communicating over port 631. The daemon is started on demand, meaning it is only running when it needs to be.&lt;/p&gt;

&lt;p&gt;However, in integrating Google Cloud Print, the daemon is of little importance. The proper layer to inject into and modify is the Objective-C layer, the six classes that serve as the API to the framework. Of these six, three are of particular interest: &lt;code&gt;PKPrinterBrowser&lt;/code&gt;, &lt;code&gt;PKPrinter&lt;/code&gt; and &lt;code&gt;PKJob&lt;/code&gt;. The first, &lt;code&gt;PKPrinterBrowser&lt;/code&gt;, functions as its name suggests. It browses for printers using Bonjour. Here is the header for &lt;code&gt;PKPrinterBrowser&lt;/code&gt;, abridged to only show the parts we might care about:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@protocol PKPrinterBrowserDelegate
-(void)addPrinter:(PKPrinter *)printer moreComing:(BOOL)coming;
-(void)removePrinter:(PKPrinter *)printer moreGoing:(BOOL)going;
@end

@interface PKPrinterBrowser : NSObject

@property (strong, nonatomic) NSMutableDictionary* printers;

+ (id)browserWithDelegate:(id&amp;lt;PKPrinterBrowserDelegate&amp;gt;)delegate;
- (id)initWithDelegate:(id&amp;lt;PKPrinterBrowserDelegate&amp;gt;)delegate;

@end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Each browser has a &lt;code&gt;printers&lt;/code&gt; property, which contains the printers, and a &lt;code&gt;delegate&lt;/code&gt; property, which wants to be notified of any changes. A browser object is created when you browse for nearby printers in the AirPrint dialog. The remaining two classes, &lt;code&gt;PKPrinter&lt;/code&gt; and &lt;code&gt;PKJob&lt;/code&gt; are model objects describing printers and jobs, respectively. Additionally, &lt;code&gt;PKPrinter&lt;/code&gt; has methods for submitting jobs.&lt;/p&gt;

&lt;h2&gt;Putting It All Together&lt;/h2&gt;

&lt;p&gt;After implementing the Cloud Print client and thoroughly investigating PrintKit, I was now able to work on integrating the two. This was the most challenging part, but also the most fun. This is the point where the code entered the bounds prohibited by Apple. The code written prior, the API client, is independent and can be used anywhere. For example, I wrote an application using the API client for debugging purposes.&lt;/p&gt;

&lt;p&gt;For those unfamiliar with jailbreaking, the piece of software that enables one to cleanly modify existing software is CydiaSubstrate. CydiaSubstrate is similar to &lt;a href="http://www.culater.net/software/SIMBL/SIMBL.php"&gt;SIMBL&lt;/a&gt; (which dates back to 2003) in principle, but has a more robust implementation. On a jailbroken iOS device, CydiaSubstrate is loaded into every process spawned by &lt;code&gt;launchd&lt;/code&gt;. Once loaded into a process, CydiaSubstrate checks a directory for user-installed libraries, called tweaks, and selectively loads them into the process. Once loaded into the process, these libraries can then modify existing functionality.&lt;/p&gt;

&lt;p&gt;As I mentioned earlier, the Objective-C layer of PrintKit is the best place to make modifications. It is low enough of a level where I would not need to modify any interface code, but high enough of a level so as to avoid the CUPS API. One of the goals is to display Google Cloud Print printers to the user. To do this, I can insert custom printer objects into PrintKit that represent printers in Google Cloud Print. &lt;code&gt;PKPrinter&lt;/code&gt; objects are normally created by &lt;code&gt;PKPrinterBrowser&lt;/code&gt;, so this seems like the logical place to insert them. Other objects see which printers &lt;code&gt;PKPrinterBrowser&lt;/code&gt; has found by checking its &lt;code&gt;printers&lt;/code&gt; property. Thus, if I was to modify the getter of this property, other objects would see my modifications. The advantage of only modifying the getter is that the modifications do not interfere with the internal state of the object, as the instance variable containing the printers is not modified. Here is some code from the project doing just this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;%hook PKPrinterBrowser

- (NSMutableDictionary *)printers {
    NSMutableDictionary *orig = %orig();

    NSMutableDictionary *combined = [NSMutableDictionary dictionaryWithDictionary:orig];
    [combined addEntriesFromDictionary:thePrinters]; // Printers from somewhere

    return combined;
}

%end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now, if you are familiar with Objective-C, you are probably wondering about some of the funky syntax above: &lt;code&gt;%hook&lt;/code&gt;, &lt;code&gt;%orig()&lt;/code&gt;, and &lt;code&gt;%end&lt;/code&gt;. The code above is written for something called Logos. Logos is a preprocessor, written in Perl, developed by &lt;a href="http://twitter.com/dhowett"&gt;Dustin Howett&lt;/a&gt;. What Logos does is it takes the code above, and translates it into Objective-C runtime calls to “hook” that method. It replaces the implementation of the method with a custom one, and makes the original implementation available with the &lt;code&gt;%orig()&lt;/code&gt; macro. Here is the above example, ran through Logos, and made human readable:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;static NSMutableDictionary * (*originalImplementation)(PKPrinterBrowser*, SEL);
static NSMutableDictionary *replacedImplementation(PKPrinterBrowser* self, SEL _cmd) {
    NSMutableDictionary *orig = originalImplementation(self, _cmd);

    NSMutableDictionary *combined = [NSMutableDictionary dictionaryWithDictionary:orig];
    [combined addEntriesFromDictionary:thePrinters]; // Printers from somewhere

    return combined;
}
static __attribute__((constructor)) void initializeHooks() {
    Class _class = objc_getClass("PKPrinterBrowser");
    Method _method = class_getInstanceMethod(_class, @selector(printers));

    IMP superImplementation = class_getMethodImplementation(class_getSuperclass(_class), @selector(printers));    

    if (_method) {
        originalImplementation = superImplementation;
        if (!class_addMethod(_class, @selector(printers), (IMP)&amp;amp;replacedImplementation, method_getTypeEncoding(_method))) {
            originalImplementation = method_setImplementation(_method, (IMP)&amp;amp;replacedImplementation);
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see, the first example is orders of magnitude cleaner and easier to maintain than the second. This is why Logos is so incredibly useful for writing hooks. It makes writing hooks almost natural, and removes the need to muck around in the runtime manually and repetitively. This approach of directly replacing implementations is somewhat similar to method &amp;#8216;swizzling&amp;#8217; that many Cocoa developers are familiar with. One of the key differences between swizzling and directly replacing the implementation is that swizzling involves adding a method to a class via a category. This can only be done when the target class is directly linkable, which is not always the case. Mike Ash &lt;a href="http://www.mikeash.com/pyblog/friday-qa-2010-01-29-method-replacement-for-fun-and-profit.html"&gt;wrote&lt;/a&gt; a great article outlining both of these methods.&lt;/p&gt;

&lt;p&gt;But back to adding printers. Now that I am able to insert custom printer objects, I need to get these printer objects from the cloud to instances of &lt;code&gt;PKPrinterBrowser&lt;/code&gt;. This is where the API client comes in. I can simply insert the API client into my tweak, and use it to fetch the printer objects. However, it is not that simple. There are many problems with doing this. The first is that a client would be created for every single application that invokes a print dialog. This is horribly inefficient. The second is that the copies of AFIncrementalStore and AFNetworking within my tweak would clash with the copies in any process that also uses these libraries, and lead to undefined behavior. This is very unstable. Both of these problems can be solved by moving the client out of the tweak, and into its own daemon. Within a daemon, nothing would clash, and there would only be a single client running at once.&lt;/p&gt;

&lt;p&gt;The tweak could then communicate with the daemon, and ask it for printer objects. Beginning with OS X Lion and iOS 5, Apple added the &lt;a href="http://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingXPCServices.html"&gt;XPC Services API&lt;/a&gt;. XPC stands for cross process communication, and it is designed to facilitate communication between daemons, or services, and other code. Beginning with OS X Mountain Lion and iOS 6, Apple added the NSXPCConnection API, which is an Objective-C wrapper built on top of the C API. On iOS, both XPC APIs are currently private, but they are exactly the same as on OS X. This means that the documentation is also the same.&lt;/p&gt;

&lt;p&gt;I went ahead and added the API client to a daemon. I further modified the &lt;code&gt;PKPrinterBrowser&lt;/code&gt; class so that each instance opens a connection to the daemon and retrieves printer objects from it. I chose to use the NSXPCConnection API for convenience. Sadly, this forces me to drop iOS 5 support in my project. One thing I had to do in order to get this approach to work was convert the printer objects from &lt;code&gt;NSManagedObject&lt;/code&gt; subclasses into &lt;code&gt;PKPrinter&lt;/code&gt; subclasses, so they were compatible with &lt;code&gt;PKPrinterBrowser&lt;/code&gt; and independent of the Core Data store. Here is a screenshot of the whole thing in action, working:&lt;/p&gt;

&lt;p&gt;&lt;img src="http://media.tumblr.com/tumblr_mf57ryMSte1qkoqlq.png" alt="Printer list"/&gt;&lt;/p&gt;

&lt;p&gt;I also wrote a preference bundle that allows a user to authenticate using OAuth2 from within the iOS Settings application. The entire project is built using &lt;a href="https://github.com/DHowett/theos"&gt;Theos&lt;/a&gt;, which is a makefile based build system written by Dustin Howett that eliminates many of the headaches that come with using makefiles. Theos was made expressly for the purpose of compiling projects for jailbroken iOS devices, and has many conveniences. Theos includes the ability to automagically preproccess files using Logos. It also includes support for building Debian packages, because APT is the package manager used on all jailbroken iOS devices.&lt;/p&gt;

&lt;h2&gt;So What?&lt;/h2&gt;

&lt;p&gt;While the tweak does not support sending print jobs yet, I have made the project &lt;a href="https://github.com/conradev/GoogleCloudPrint"&gt;open source&lt;/a&gt; under the MIT license for those who want to look through the code, play around with it, or even use parts of it. I do intend to eventually finish it and release it. I set out to integrate Google Cloud Print and iOS in the best way possible and the resulting project came out great. On top of this, I learned a whole lot in the process of building it.&lt;/p&gt;

&lt;p&gt;I wanted to write this post to demonstrate a few things. First, that by jailbreaking, the possibilities are endless. Not as a user, but as a developer. Nothing in the userland is off limits, and everything is modifiable. In very few places in the mobile ecosystem is this offered. Android certainly has more freedom with their SDK, but there are still certain things off limits. Even when rooted, Java is a static language, making modification of other software difficult. The same goes for almost every other mobile operating system. The only exception I know of is &lt;a href="http://www.webos-internals.org"&gt;WebOS&lt;/a&gt; because it is open by default, and a lot of it is written in JavaScript. Modification via patches is easy.&lt;/p&gt;

&lt;p&gt;The second point I wanted to illustrate is that developing software outside of the sandbox makes you a better iOS developer. I am not saying that those who develop outside of the sandbox are better than those who develop within. Software written for the sandbox is certainly more important, as it impacts a much larger market. What I &lt;em&gt;am&lt;/em&gt; saying is that developing software outside of the sandbox is a constant challenge, and you will &lt;em&gt;certainly&lt;/em&gt; learn a few things by trying it. I am a strong believer in the idea that you must take something apart to understand how it works. A great way of doing this is by disecting iOS and writing software to co-exist with it. Developing software for jailbroken devices transformed me from an Xcode kiddy into what I am today. I now have a thorough understanding of the Objective-C runtime, reverse engineering, dynamic libraries, et cetera.&lt;/p&gt;

&lt;p&gt;Lastly, developing tweaks is just plain &lt;em&gt;fun&lt;/em&gt;. I have seen many people exercise their design talent once in a while and create an iOS concept video. While it looks great on video, how awesome would it be to actually create it and try it out? Tweaks do not necessarily have to be big, either. They can be as small as adding seconds to the lockscreen clock. Here are &lt;a href="http://tweakweek.com"&gt;some&lt;/a&gt; &lt;a href="https://github.com/conradev/Tweaks"&gt;great&lt;/a&gt; &lt;a href="https://github.com/Xuzz/tweaks"&gt;examples&lt;/a&gt; of small and simple tweaks. Developing for jailbroken devices can be a fun and challenging hobby, so I encourage other iOS developers to &lt;a href="http://iphonedevwiki.net/index.php/Theos/Getting_Started"&gt;jump right in&lt;/a&gt; and give it a try!&lt;/p&gt;

&lt;p&gt;Feel free to &lt;a href="http://twitter.com/conradev"&gt;follow me&lt;/a&gt; on Twitter or check out my &lt;a href="http://kramerapps.com/cydia/"&gt;software&lt;/a&gt;. Additionally, if your company is hiring mobile dev interns this upcoming summer, and has no problem hiring a high school student, be sure to &lt;a href="mailto:conrad@kramerapps.com"&gt;get in touch&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Discuss on Hacker News &lt;a href="http://news.ycombinator.com/item?id=4932420"&gt;here&lt;/a&gt;.&lt;/p&gt;</description><link>http://blog.kramerapps.com/post/38090565883</link><guid>http://blog.kramerapps.com/post/38090565883</guid><pubDate>Mon, 17 Dec 2012 09:00:00 -0500</pubDate></item><item><title>Vim, LaTeX and High School</title><description>&lt;p&gt;This September, after a summer full of programming, I was forced back into my junior year in high school. Back to writing English essays, lab reports, and projects. Luckily, sometime over the summer I discovered LaTeX. LaTeX has &lt;a href="http://www.eng.cam.ac.uk/help/tpl/textprocessing/latex_advocacy.html"&gt;many&lt;/a&gt; &lt;a href="http://nitens.org/taraborelli/latex"&gt;advantages&lt;/a&gt; over a proprietary WYSIWYG word proccesor like Microsoft Word or Apple’s Pages. Its free, it’s portable, and it’s friendly with mathematical and scientific notation out of the box. However, It also has its share of disadvantages. One of these disadvantages is the steep learning curve. Unlike the WYSIWYG editors, it’s not straightforward to set up or use. This is why I am writing this blog post, to share my experiences and help bootstrap someone eager to get started with LaTeX.&lt;/p&gt;

&lt;h2&gt;The Setup&lt;/h2&gt;

&lt;p&gt;Installing and setting up LaTeX on your machine varies, depending on what operating system you are on. The LaTeX &lt;a href="http://www.latex-project.org/ftp.html"&gt;project website&lt;/a&gt; lists some good TeX distributions available for download. I own a MacBook running OS X, so I have downloaded and installed &lt;a href="http://www.tug.org/mactex/"&gt;MacTeX&lt;/a&gt;. It is a big download (&amp;gt;1GB), but it is comprehensive, including everything you need to get started.&lt;/p&gt;

&lt;p&gt;To build TeX files into PDFs, I have found &lt;a href="https://launchpad.net/rubber"&gt;Rubber&lt;/a&gt; to be the easiest and most &lt;a href="http://tex.blogoverflow.com/2011/12/building-documents-with-rubber/"&gt;comprehensive&lt;/a&gt; solution out there. It abstracts away all the tasks involved with building a TeX document, and works on both Linux and OS X without problem. It is available for download and install in many package managers, including Homebrew on OS X.&lt;/p&gt;

&lt;p&gt;If you use Vim, I highly recommend the &lt;a href="http://www.vim.org/scripts/script.php?script_id=3230"&gt;TeX-PDF&lt;/a&gt; plugin. As the name implies, the plugin’s sole purpose is to build TeX into finished PDFs, using whatever is available. It will use Rubber if it finds it on the system. The plugin is well suited for high school projects, because building to PDFs is probably the only thing you need to do. Using &lt;a href="https://github.com/gmarik/vundle"&gt;Vundle&lt;/a&gt;, installation is as simple as adding &lt;code&gt;Bundle "TeX-PDF”&lt;/code&gt; to your &lt;code&gt;.vimrc&lt;/code&gt; file.&lt;/p&gt;

&lt;h2&gt;Getting Started&lt;/h2&gt;

&lt;p&gt;There are many &lt;a href="http://www.tug.org/interest.html#doc"&gt;resources&lt;/a&gt; available to those starting out with LaTeX. I have chosen to learn as I go, and figure out how to do something when I need to do it. However, I have learned some tips and tricks that would be particulary useful for fellow high school students.&lt;/p&gt;

&lt;h3&gt;Science&lt;/h3&gt;

&lt;p&gt;In writing lab reports for science classes, I have found the packages &lt;a href="http://ctan.org/pkg/mhchem"&gt;&lt;code&gt;mhchem&lt;/code&gt;&lt;/a&gt; and &lt;a href="http://ctan.org/pkg/siunitx"&gt;&lt;code&gt;siunitx&lt;/code&gt;&lt;/a&gt; to be very useful. Both of these are included in the TeX Live and MacTeX distributions. The first package, &lt;code&gt;mhchem&lt;/code&gt;, makes it very easy to write out chemical formulae. It is extremely comprehensive, and supports all the notation I have needed for AP Chemistry thus far. To write the formula for dichromate, it simplifies&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$3\,\mathrm{Cr}_2^{\strut}\mathrm{O}_7^{2-}$
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;into&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;\ce{3Cr2O7^2-}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;to draw&lt;/p&gt;

&lt;p&gt;&lt;img src="http://media.tumblr.com/tumblr_mbhylsxuzG1qkoqlq.png" alt=""/&gt;&lt;/p&gt;

&lt;p&gt;The other package, &lt;code&gt;siunitx&lt;/code&gt;, allows you to typeset physical quantities with ease. For example, you can express the specific heat capacity of water with&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;\SI{4.18}{\joule\per\gram\per\celsius}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;to draw&lt;/p&gt;

&lt;p&gt;&lt;img src="http://media.tumblr.com/tumblr_mbhyoejMmH1qkoqlq.png" alt=""/&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;siunitx&lt;/code&gt; supports (allmost) every SI unit under the sun.&lt;/p&gt;

&lt;h3&gt;English&lt;/h3&gt;

&lt;p&gt;Writing English essays in LaTeX is very easy to do, thanks to the &lt;a href="http://www.ctan.org/pkg/mla-paper"&gt;&lt;code&gt;mla-paper&lt;/code&gt;&lt;/a&gt; package. It takes care of the MLA header in one line, which is very useful.&lt;/p&gt;

&lt;p&gt;&lt;img src="http://media.tumblr.com/tumblr_mbhygeePKX1qkoqlq.png" alt=""/&gt;&lt;/p&gt;

&lt;p&gt;and the code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;\documentclass[12pt]{article}
\pagestyle{plain}

\usepackage{fullpage}
\usepackage{ifpdf}
\usepackage{mla}

\begin{document}
\begin{mla}{First}{Last}{Teacher}{Class}{Date}{Title}

One of the great American classics, \emph{The Great Gatsby} by F. Scott Fitzgerald \ldots

\end{mla}
\end{document}
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;Plotting&lt;/h3&gt;

&lt;p&gt;In all of my science classes, I have had to plot points on a graph, in one form or another. Yes, &lt;em&gt;there is a package for that&lt;/em&gt;. Based on the graphics package pgf, &lt;a href="http://www.ctan.org/pkg/pgfplots"&gt;pgfplots&lt;/a&gt; can be used to create high quality plots of all kinds. Here is a recent example of a project I did in AP Calculus, graphing a logistic function:&lt;/p&gt;

&lt;p&gt;&lt;img src="http://media.tumblr.com/tumblr_mbhyb3C07I1qkoqlq.png" alt=""/&gt;&lt;/p&gt;

&lt;p&gt;This example has four plots overlaid on top of one another. A scatter plot, the logistic regression, and its first and second derivatives. This example also includes labeled nodes, and a legend. &lt;code&gt;pgfplots&lt;/code&gt;, like many of the other packages, is extremely comprehensive and extensible. Here is the code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;\documentclass[12pt]{article}
\pagestyle{plain}

\usepackage{pgfplots}

\begin{document}

\centering

\begin{tikzpicture}
\begin{axis}[
  height=10cm,
  width=\textwidth,
  axis y line=left,
  axis x line=middle,
  title=Spread of the Virus,  
  xlabel=Round (Day),
  ylabel=Number of People Infected]

% Points
\addplot[only marks, forget plot, blue] table[x=Day,y=People]{
Day People
1   1
2   2
3   4
4   8
5   14
6   19
7   24
8   28
9   30
10  30
11  32
};

% Regression
\addplot[smooth,blue,mark=none, domain=0:11,samples=40]{ 31.808 / (1 + (60.9 * e^(-0.756 * x))) };
\addplot[smooth,red,mark=none, domain=0:11,samples=40]{ (1464.45 * e^(0.756 * x))/(60.9+e^(0.756 * x))^2 };
\addplot[smooth,green,mark=none, domain=0:11,samples=40]{ (e^(-0.756 * x) * (67424 * e^(1.512 * x) - 1107.13 * e^(2.268 * x)))/(60.9+e^(0.756 * x))^3 };

% Important points
\node[pin=135:{\shortstack{Inflection Point \\ $(5.435,15.905)$}}] at (axis cs:5.435,15.905) {};
\node[pin=45:{\shortstack{Relative Maximum \\ $(5.435,6.012)$}}] at (axis cs:5.435,6.012) {};
\node[pin=15:{\shortstack{Zero \\ $(5.435,0)$}}] at (axis cs:5.435, 0) {};

% Legend
\addlegendentry{ $f(x)$ }
\addlegendentry{ $f'(x)$ }
\addlegendentry{ $f''(x)$ }

\end{axis}
\end{tikzpicture}

\end{document}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Deciding to switch to using only LaTeX for my schoolwork this year was a fantastic decision. Although I had to learn as I went, often under time constraints, it has certainly paid off. I can now edit my schoolwork with Vim. Mathematical and scientific notation is easy to write, and not a hassle anymore. I don’t have to rely on a proprietary word processor. I plan on taking this skill with me when I eventually head off to college.&lt;/p&gt;

&lt;p&gt;Discuss on HN &lt;a href="http://news.ycombinator.com/item?id=4622223"&gt;here&lt;/a&gt;.&lt;/p&gt;</description><link>http://blog.kramerapps.com/post/33045194977</link><guid>http://blog.kramerapps.com/post/33045194977</guid><pubDate>Sat, 06 Oct 2012 20:33:00 -0400</pubDate></item><item><title>Deploy a website using git in Ubuntu</title><description>&lt;p&gt;This is a follow up to my &lt;a href="http://kramerapps.com/blog/post/22551999777/flask-uwsgi-nginx-ubuntu"&gt;previous post&lt;/a&gt; on how to set up a Flask web app with nginx and uWSGI. This post will run down how to set up a git-based deployment system for that web app. Git is pretty popular for deployment, and is used in services like &lt;a href="https://devcenter.heroku.com/articles/git"&gt;Heroku&lt;/a&gt;. Heroku is great, but I prefer to have full control over my server, and roll my own stuff, all while maintaining the same ease of use.&lt;/p&gt;

&lt;h2&gt;Repository Setup&lt;/h2&gt;

&lt;p&gt;To continue from my previous example, the website is deployed in &lt;code&gt;/srv/www/helloworld&lt;/code&gt;. This tutorial should work with pretty much any website, but it will still focus on Flask based ones.&lt;/p&gt;

&lt;p&gt;First, if you have not already done so, install git.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sudo apt-get install git
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Next, put your website under version control with git&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cd /srv/www/helloworld
git init
git add application.py
git commit -m 'First commit'
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A gitignore file is also a good idea. For a Flask app, put the following in &lt;code&gt;.gitignore&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;env
*.pyc
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and to add it to the repository&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git add .gitignore
git commit -m 'Added .gitignore file'
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we are going to create a bare &amp;#8216;hub&amp;#8217; repository that will act as an intermediary between the active deployment folder and the rest of the world.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sudo mkdir -p /srv/git
sudo chown -R $USER:$GROUP /srv/git
cd /srv/git
git clone --bare /srv/www/helloworld
cd helloworld.git
git remote rm origin
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Next, add the hub as a remote for the deployment repository&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cd /srv/www/helloworld
git remote add hub /srv/git/helloworld.git
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Add the magic&lt;/h2&gt;

&lt;p&gt;To automatically update the deployment repository when changes are pushed to the hub, we are going to use git hooks. Git hooks are scripts that are executed after certain changes occur within the repository.&lt;/p&gt;

&lt;p&gt;To begin, add the following to &lt;code&gt;/srv/git/helloworld.git/hooks/post-update&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!/bin/sh
echo
echo "Pulling changes into deployment repository"
echo
git --git-dir /srv/www/helloworld/.git --work-tree /srv/www/helloworld pull hub master
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and make sure that it is executable&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;chmod 755 /srv/git/helloworld.git/hooks/post-update
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This &lt;code&gt;post-update&lt;/code&gt; script updates the deployment repository when the hub is updated. Next, we are going to setup the reverse, a hook to update the hub when changes are committed in the deployment directory (this should be rare, but just in case). Add the following to &lt;code&gt;/srv/www/helloworld/.git/hooks/post-commit&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!/bin/sh
echo
echo "Pushing changes to hub"
echo
git push hub
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and add make it executable&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;chmod 755 /srv/www/helloworld/.git/hooks/post-commit
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Further Modification&lt;/h2&gt;

&lt;p&gt;If you went ahead and tested the deployment system, you&amp;#8217;d find that the changes aren&amp;#8217;t reflected in your browser yet. uWSGI is still using the old compiled python files, and did not notice the changes to the directory. To get uWSGI to notice the changes, you have to reload it every time you push changes. A reload command can be added to the git hook, but it isn&amp;#8217;t as easy as it sounds. You need root privileges to reload uWSGI, and when you push changes to the server, you are most likely logging in as your own personal user. The solution to this problem is to create a setuid binary that reloads uWSGI.&lt;/p&gt;

&lt;p&gt;First, install the Ubuntu &lt;code&gt;build-essential&lt;/code&gt; package&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sudo apt-get install build-essential
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Next, put the following in &lt;code&gt;~/reload_uwsgi.c&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include &amp;lt;stdio.h&amp;gt;
#include &amp;lt;sys/types.h&amp;gt;
#include &amp;lt;unistd.h&amp;gt;
#include &amp;lt;stdlib.h&amp;gt;

int main() {
    setuid(0);
    system("/sbin/initctl reload uwsgi");
    return 0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now to compile, install and configure the binary&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cd ~
sudo gcc reload_uwsgi.c -o /usr/local/bin/reload_uwsgi
rm reload_uwsgi.c
sudo chown root:root /usr/local/bin/reload_uwsgi
sudo chmod 4755 /usr/local/bin/reload_uwsgi
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And lastly add this executable to our git hooks, which should look like the following&lt;/p&gt;

&lt;p&gt;&lt;code&gt;/srv/git/helloworld.git/hooks/post-update:&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!/bin/sh
echo
echo "Pulling changes into deployment repository"
echo
git --git-dir /srv/www/helloworld/.git --work-tree /srv/www/helloworld pull hub master
/usr/local/bin/reload_uwsgi
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code&gt;/srv/www/helloworld/.git/hooks/post-commit:&lt;/code&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!/bin/sh
echo
echo "Pushing changes to hub"
echo
git push hub
/usr/local/bin/reload_uwsgi
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Testing it out&lt;/h2&gt;

&lt;p&gt;Clone the repository on your local machine&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;git clone user@server:/srv/git/helloworld.git
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Make some changes, commit them to master, and push them to the server&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;vim application.py
git commit -am 'Made some changes!'
git push origin master
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and voila! The change should be reflected on the website.&lt;/p&gt;

&lt;p&gt;Discuss on Hacker News &lt;a href="http://news.ycombinator.com/item?id=4067056"&gt;here&lt;/a&gt;&lt;/p&gt;</description><link>http://blog.kramerapps.com/post/24447423014</link><guid>http://blog.kramerapps.com/post/24447423014</guid><pubDate>Mon, 04 Jun 2012 22:41:00 -0400</pubDate></item><item><title>Getting a Flask website up and running in Ubuntu</title><description>&lt;p&gt;This is a guide to get a Flask website up and running on Ubuntu 12.04 LTS using nginx and uWSGI. There are &lt;a href="http://me.veekun.com/blog/2012/05/05/python-faq-webdev/"&gt;many routes&lt;/a&gt; to take when it comes to Python on the web; this just is my personal favorite. Some people enjoy configuring servers, while others view it as a chore. Regardless, this guide should get you up, running, and ready to make something awesome in no time!&lt;/p&gt;

&lt;h1&gt;Installation&lt;/h1&gt;

&lt;h2&gt;nginx&lt;/h2&gt;

&lt;p&gt;To install nginx you first need to add the repository. Add the following to &lt;code&gt;/etc/apt/sources.list.d/nginx-lucid.list&lt;/code&gt;&amp;#160;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;deb &lt;a href="http://nginx.org/packages/ubuntu/"&gt;http://nginx.org/packages/ubuntu/&lt;/a&gt; lucid nginx
deb-src &lt;a href="http://nginx.org/packages/ubuntu/"&gt;http://nginx.org/packages/ubuntu/&lt;/a&gt; lucid nginx
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You will also want to add the gpg key to the &lt;code&gt;apt&lt;/code&gt; keyring:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;wget &lt;a href="http://nginx.org/keys/nginx_signing.key"&gt;http://nginx.org/keys/nginx_signing.key&lt;/a&gt;
sudo apt-key add nginx_signing.key
rm nginx_signing.key
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Finally, to install nginx, run:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;apt-get update
apt-get install nginx
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;uWSGI&lt;/h2&gt;

&lt;p&gt;You can use pip to install the latest version of uWSGI by doing the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sudo apt-get install python-dev build-essential python-pip
sudo pip install uwsgi
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To configure uWSGI to run as a daemon, you first want to create a separate &lt;code&gt;uwsgi&lt;/code&gt; user:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sudo useradd -c 'uwsgi user,,,' -g nginx -d /nonexistent -s /bin/false uwsgi
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You then want to create an upstart configuration file, to run uWSGI in the background. Add the following to &lt;code&gt;/etc/init/uwsgi.conf&lt;/code&gt;&amp;#160;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;description "uWSGI"
start on runlevel [2345]
stop on runlevel [06]

respawn

exec uwsgi --master --processes 4 --die-on-term --uid uwsgi --gid nginx --socket /tmp/uwsgi.sock --chmod-socket 660 --no-site --vhost --logto /var/log/uwsgi.log
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To set up logging, you can add a logrotate configuration file at &lt;code&gt;/etc/logrotate.d/uwsgi&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/var/log/uwsgi.log {
    rotate 10
    daily
    compress
    missingok
    create 640 uwsgi adm
    postrotate
        initctl restart uwsgi &amp;gt;/dev/null 2&amp;gt;&amp;amp;1
    endscript
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and to prime the log file, you can run:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sudo touch /var/log/uwsgi.log
sudo logrotate -f /etc/logrotate.d/uwsgi
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It is okay if there is an error with the postrotate script. uWSGI cannot be restarted because it is not currently running.&lt;/p&gt;

&lt;h2&gt;virtualenv&lt;/h2&gt;

&lt;p&gt;Using virtualenv is a good idea because it compartmentalizes the environment of your application. To install virtualenv, you can use pip:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sudo pip install virtualenv
&lt;/code&gt;&lt;/pre&gt;

&lt;h1&gt;Configuration&lt;/h1&gt;

&lt;h2&gt;Flask&lt;/h2&gt;

&lt;p&gt;Now to set up the website! In this case, the website is going to be called &amp;#8216;helloworld&amp;#8217; and it is going to be set up in &lt;code&gt;/srv/www/helloworld&lt;/code&gt;. Feel free to change it, just adjust these instructions accordingly.&lt;/p&gt;

&lt;p&gt;The first step is to create the directory:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sudo mkdir -p /srv/www/helloworld
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and a subdirectory for static files, to be hosted by nginx:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cd /srv/www/helloworld
mkdir static
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The next step is to create a virtual environment for the application to run in:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;virtualenv ./env
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and to install Flask in that environment:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;source env/bin/activate
pip install Flask
deactivate
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now that that is done, let&amp;#8217;s create a sample &amp;#8216;Hello World&amp;#8217; application, in &lt;code&gt;application.py&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The permissions of the directory now have to be configured. uWSGI needs read permission to read the contents of the scripts, and write permission to save compiled python files:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sudo usermod -a -G nginx $USER
sudo chown -R $USER:nginx /srv/www/helloworld
sudo chmod -R g+w /srv/www/helloworld
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Nginx&lt;/h2&gt;

&lt;p&gt;The final step is to configure nginx. First, remove the default configuration file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sudo rm /etc/nginx/conf.d/default.conf
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now, add the helloworld configuration file at &lt;code&gt;/etc/nginx/conf.d/helloworld.conf&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;server {
    listen       80;
    server_name  localhost;

    location /static {
        alias /srv/www/helloworld/static;
    }

    location / {
        include uwsgi_params;
        uwsgi_pass unix:/tmp/uwsgi.sock;
        uwsgi_param UWSGI_PYHOME /srv/www/helloworld/env;
        uwsgi_param UWSGI_CHDIR /srv/www/helloworld;
        uwsgi_param UWSGI_MODULE application;
        uwsgi_param UWSGI_CALLABLE app;
    }

    error_page   404              /404.html;

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Running it&lt;/h2&gt;

&lt;p&gt;Now that you have successfully configured your website, you can run it using:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sudo service uwsgi restart
sudo service nginx restart
&lt;/code&gt;&lt;/pre&gt;

&lt;h1&gt;Extensions&lt;/h1&gt;

&lt;h2&gt;Flask&lt;/h2&gt;

&lt;p&gt;Flask is fantastic because it is very extensible. Check out the &lt;a href="http://flask.pocoo.org/docs/"&gt;documentation&lt;/a&gt; to get started.&lt;/p&gt;

&lt;h2&gt;More Websites!&lt;/h2&gt;

&lt;p&gt;It is really easy to add more websites to this configuration. Simply create a new application directory, set it up, and create a second nginx configuration. uWSGI is configured to be in virtualhost mode, so it can handle multiple websites at once.&lt;/p&gt;

&lt;h2&gt;Portability&lt;/h2&gt;

&lt;p&gt;You can also use uWSGI as an http server, for testing purposes. If you have a copy of your website checked out in the current directory, you can run&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;uwsgi --http 127.0.0.1:9090 --pyhome ./env --module application --callable app
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and uWSGI will create a HTTP server hosting your application on port 9090. This is incredibly useful for development.&lt;/p&gt;

&lt;p&gt;Discuss on Hacker News &lt;a href="http://news.ycombinator.com/item?id=3937691"&gt;here&lt;/a&gt;&lt;/p&gt;</description><link>http://blog.kramerapps.com/post/22551999777</link><guid>http://blog.kramerapps.com/post/22551999777</guid><pubDate>Sun, 06 May 2012 19:00:00 -0400</pubDate></item></channel></rss>
