Category Archives: Code

Will Python ever be taken seriously?

I’ve been writing Python for almost a year now and have been pleasantly surprised by the language. Even though Python has been around for a few decades now it still hasn’t been widely accepted as a production grade programming language.

Its primary use is still in the online world where it has developed a large rivalry with Ruby. It’s been my observation that Ruby wins this match up in the eyes of developers about 80% of the time. In the embedded world the use of Python is almost unheard of and I’ve personally never seen it used exclusively for a full stand alone application.

The language is aesthetically pleasing, requires less typing, and is fantastic for rapid prototyping. It definitely has its quarks and drawbacks but what language doesn’t? When I mention to other developers that I’m currently writing in Python the most common reaction is disbelief. The language just isn’t taken seriously. Why?

PyQt Charts

The Qt framework doesn’t contain any useful charting widgets. There are a few python charting modules out there, most notably PyQwt. As a PyQt developer I didn’t find this module very useful. What I really wanted was a charting widget that used QWidget as its base class. At the time of this post I couldn’t find anything so I wrote my own based on the google charts module.

What I love about this snippet is that it mimics the C++ template functionality in Python. The QChart function below abstracts the PyQtChart class definition and any pygooglechart object can be instantiated as a QWidget.

__author__	  = "Christopher Piekarski"
__email__	  = "@c_piekarski"

import time, os, sys
from PyQt4 import QtCore, QtGui
from pygooglechart import *

def QChart(parent, type, **kwargs):
	class PyQtChart(type, QtGui.QWidget):
		def __init__(self, parent, **kwargs):
			QtGui.QWidget.__init__(self, parent, **kwargs)
			type.__init__(self, kwargs["size"].width(), kwargs["size"].height())
			self.pix = QtGui.QPixmap()

		def download(self):
			file = "./%f.png" % time.time()
			type.download(self, file)
			self.pix.load(file)

		def paintEvent(self, event):
			p = QtGui.QPainter(self)
			p.drawPixmap(0,0,self.pix)
			super(PyQtChart, self).paintEvent(event)

	return PyQtChart(parent, **kwargs)

class MainWindow(QtGui.QMainWindow):
	def __init__(self, **kwargs):
		super(QtGui.QMainWindow, self).__init__(**kwargs)

		t = QChart(self, PieChart3D, size=QtCore.QSize(250,100))
		t.add_data([10,20])
		t.set_pie_labels(['Hello', 'World'])
		t.download()

if __name__ == '__main__':
	app = QtGui.QApplication(sys.argv)
	app.setApplicationName("PyQt Charting Demo")
	app.setQuitOnLastWindowClosed(True)

	scaledSize = QtCore.QSize(500,500)
	window = MainWindow(size=scaledSize)
	window.setWindowTitle("PyQt Charting Demo")
	window.show()

	sys.exit(app.exec_())

Web Apps – The More Custom The Better

I’m a big fan of the WebKit Qt framework integration. It will without a doubt change the face of web based content delivery over the next few decades (previous post). By far the most powerful aspect of this integration is the ability to create custom JavaScript APIs for hybrid web based applications in a browser.

Put simply, browsers can customize the functionally they offer by implementing features into the browser that can be accessed by web content via JavaScript.  Web apps that exercise this functionally must be written to do so, making them “custom” web apps.  Meaning that an app written to utilize features defined in certain browsers will not work without modification in Explorer, Firefox, or Chrome. For example, when GE integrates a web browser into their next generation refrigerators, it would be beneficial to expose an API that allowed an app to check the inside temperature or level of the ice tray.

I’ve been in many debates with other engineers about this option.  Not one engineer has ever agreed with me right off the bat.  Most oppose doing it as it limits were an app can be run and defeats the purpose of web content.  The “purpose” being mass distribution and play-ability on many different standardize browsers.  Most don’t understand why you’d create a web app that can only be executed on a limited number of browsers.  Many also argue that it burdens app developers with having to learn yet another JavaScript API.  Regardless of the objection, this option is widely opposed and not fully understood by most engineers.

The engineering objections are easy to argue against.  First of all, there is no such thing as a standardized browser.  Despite standardization efforts from W3C,  the JavaScript language is a mess.  The big three, IE, Firefox, and Chrome all use a different JavaScript engine and have varying degrees of standardization completeness (some even have features not covered by W3C).  If you want your website to work across the big 3 you already have to add additional code.  I know its a stretch, but this is already a form of web app customization.

The real value add of customized web apps is from a business perspective.  I come from the embedded device world where the number of units sold is the driving factor (compared to the number of hits). By forcing apps to write to your API you are ensuring a certain level of stickiness.  It can be a competitive advantage to limit the devices an app can run on by exposing custom functionality through the browser.  GE won’t want its ice tray level app to run on LG with no modification for the same reason Apple does’t want its apps to run on Android without a rewrite.

Adding a custom JavaScript API to your Qt WebKit browser is easy.  Nokia has a great blog post on its forum here. To illustrate its simplicity I’ve included my own snippet below.

Any C++ object can be complied into the browser and exposed to the JS engine.

class FakeObject
{
public:
	FakeObject(QObject *parent);
public slots:
	posterInternalCommand(QString command, QString data);
signals:
	fakeSignal();
}

FakeObject::FakeObject(QObject *parent)
{

}

bool FakeObject::postInternalCommand(QString command, QString data)
{
	// Do something with data
	return True;
}

FakeObject::emitSignalTest()
{
	emit fakeSignal();
}

After instantiation the object is exposed to the JS engine using a QWebFrame method.

FakeObject* m_pfake = new FakeObject(webView);
webView->page()->mainFrame()->addToJavaScriptWindowObject(QString("fake"),m_pFake);

The exposed object can now be acted on via JavaScript. Public slots are methods that can be called directly from JS. Signals can also be connected to local JS methods making for more asynchronous functionality.

b = window.fake.postInternalCommand("fakeCommand", "fakeData")

function fakeCallBack(){
	x = x + 1
}

window.fake.fakeSignal.connect(fakeCallBack)

Qt & WebKit Browsers

I don’t recall if it was Nokia or Trolltech who originally decided to add a WebKit widget to Qt. Regardless, its a fantastic addition to the framework and the ramifications to the world are still not yet fully known.

We’re all familiar with web browsers primarily on our PCs and mobile phones. That is going to change… in a big way. Qt has made it simple for development teams to create custom browsers that can run anywhere and inside any application. As a result we’re going to start seeing web browser in our cars, kitchen appliances, digital picture frames, remote controls, and even exercise equipment.

Below you will find an example I wrote using the Qt WebKit support. Its a very simple “custom” browser that allows an application to instantiate the object and render any HTML.

Header file (wijibrowser.h):

#include <QtGui>
#include <QWebView>

class WijiBrowser : public QMainWindow
{
    Q_OBJECT

public:
    WijiBrowser();
    ~WijiBrowser();

    bool loadUrl(QString name, QString url);
    bool loadHTML(QString name, QString html);
    QString contentName() { return m_name; }
    QString url() { return (view ? view->url().toString() : QString("none")); }

protected slots:
    void finishLoading(bool ok);

private:
    QString m_name;
    QWebView *view;
};

CPP file (wijibrowser.cpp):

#include <QtGui>
#include <QtWebKit>
#include "wijibrowser.h"

WijiBrowser::WijiBrowser()
{
    m_name = "unknown";

    QNetworkProxyFactory::setUseSystemConfiguration(true);

    view = new QWebView(this);
    view->load(QUrl("http://www.immersivelabs.com"));
    connect(view, SIGNAL(loadFinished(bool)), SLOT(finishLoading(bool)));

    setCentralWidget(view);
    setUnifiedTitleAndToolBarOnMac(true);
}

WijiBrowser::~WijiBrowser()
{
	delete view;
}

void WijiBrowser::finishLoading(bool ok)
{
	QString status = (ok ? "OK" : "Failed");
	QString url = view->url().toString();
	QString msg = QString("finishLoading %1 - %2").arg(url).arg(status);
	qDebug(msg);
}

bool WijiBrowser::loadUrl(QString name, QString url)
{
	m_name = name;
    view->load(QUrl(url));
}

bool WijiBrowser::loadHTML(QString name, QString html)
{
	m_name = name;
	view->setHtml(html);
}

And here is a simple main.cpp to launch it:

#include <QtGui>
#include "wijibrowser.h"

int main(int argc, char * argv[])
{
    QApplication app(argc, argv);
    WijiBrowser browser;
    browser.show();
    return app.exec();
}

Getting the System IP Address with Python

The default Python 2.7.1 distribution has very limited functionality for getting the system IP. If your not willing to install an external module then you really only have one choice… open a socket, establish a connection, and get the active IP from the socket name tuple.

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('immersivelabs.com', 0))
s.getsockname()[0]

Although this solution works, it has a few issues. The biggest draw back is that it only returns one of the systems IP addresses. Fortunately, there is a great module called pynetinfo. Install the module using easy_install and then wrap its functionality with the following methods.

import netinfo

def getSystemIfs():
    return netinfo.list_active_devs()

def getSystemIps():
    """ will not return the localhost one """
    IPs = []
    for interface in getSystemIfs():
        if not interface.startswith('lo'):
            ip = netinfo.get_ip(interface)
            IPs.append(ip)
    return IPs

def getIPString():
    """ return comma delimited string of all the system IPs"""
    return ",".join(getSystemIps())

You can now easily get a list or a string containing all the active IP addresses on the system (POSIX Only).

Thrift RPC Framework

At TechStars, Alessio Signorini and I had the opportunity to experiment with Facebook’s Thrift remote procedure call (RPC) framework. I was thoroughly impressed with the framework and feel it takes distributed computing to whole new level. Every developer regularly working on both large and small client/server architectures must be familiar with this tool.

Developers can easily specify data types (parameters) and server interface definitions (API) in a plain text file. Thrift uses this text file to create programming language independent client and server stub files. What makes this so powerful, is that system architects can now choose the appropriate programing language for each area of the system.

Not all programing languages are created equal and no one language contains just positive attributes. It is often the case that the ideal language for a server is Java or C++, but the client would best be written in Python. Thrift allows you to easily choose the best language for the job without having to reinvent the communication protocol every-time you change the language.

This framework is a game changer for software developers and system architects. If you haven’t already done so I strongly encourage you to start playing with it. Below is an example thrift file that defines several data types and one service. Once this interface is defined it can easily be converted into stubs for any language which keeps the interface API separate from the implementation. Read the whitepaper here.

#!/usr/local/bin/thrift --gen cpp:pure_enums --gen php

namespace cpp displaymanager

enum pushResult
{
  OK,
  BUSY,
  INVALID
}

struct pushUrl
{
  1:  string name,
  2:  string url
}

struct pushHtml
{
  1:   string name,
  2:   string data
}

service displaymanager
{
  pushResult fetchUrl(1: pushUrl url);
  pushResult postHtml(1: pushHtml html);
  string	 whatsLoaded();
  string	 currentUrl();
}

Python – Love / Hate

I hate about Python because:

1) Really bad at managing threads.
2) All class properties require “self” keyword.
3) Inheritance is supported but can be difficult to invoke.
4) Private members are difficult to encapsulate.
5) More difficult to deploy then traditional compiled languages.
6) Default timer class is limiting.

I love about Python because:

1) Tuples.
2) Keyword parameters.
3) Everything is an object.
4) The “pass” keyword.
5) Generator objects.
6) Method objects.
7) Dynamic code insertion.
8) PEP8.