Space in HTML Page

There’re several methods to add spaces in html web page. This blog entry is a summary of several approaches I’ve used.

1. Line Break

If you want to start a new line, you can use <br>, the line break tag. It has no end tag, and can be used anywhere within <body></body> tags.

Below is a simple html page,

    test line 1<br>
    test line 2

When open it up in a web browser, this is what you see,


2. Blank Space

html page collapse multiple normal space into one. For example, if you write 1          2, it will be seen as 1 2. The ten space are reduced to one. HTML defines &nbsp; character entitity for no-break space. (character entities are used to represent reserved characters.) The &nbsp; character entity is normally used in two situations,

  • Create multiple spaces: multiple &nbsp; won’t shrink to a single space.
  • Keep elements together: browsers won’t break up two elements with &nbsp; in between.

Below is a sample html page,

    a                              line<br>

If you save the page and open it up in a web browser, this is what you see,


3. Padding with <span>

<span> tag is used to group elements of a document, it can be used to add styles to part of a text or document.

Below is a sample html page,

    here<span style="padding-left:20px">am I</span>

And if you save the page and open it using a browser, this is what you see,


4. Pre-format tag <pre>

<pre> tag defines preformatted text. Text within in <tag></tag> is displayed using fixed-width font, and both line breaks and spaces are preserved.

Below is a sample html page,

    here I

And if you save the page and open it up in a web browser, this is what you see,


Serial Port Communication in Python

pyserial is a python module that allows one to access serial port. It’s easy to use and one can start test serial port communication in minutes.

1. Install pyserial

If your machine doesn’t have pyserial module installed, you can install the module using easy_install.

sudo easy_install pyserial

In case you don’t have easy_install installed, you can install it by entering the following command,

sudo apt-get install python-setuptools

Then you can run the command above to install pyserial.

2. A Sample Program

The sample program use pyserial to communicate with a modem device with its serial port interface at /dev/ttyUSB0 in Ubuntu Linux.

import serial, time
#initialization and open the port
#possible timeout values:
#    1. None: wait forever, block call
#    2. 0: non-blocking mode, return immediately
#    3. x, x is bigger than 0, float allowed, timeout block call
ser = serial.Serial()
ser.port = "/dev/ttyUSB0"
#ser.port = "/dev/ttyS2"
ser.baudrate = 9600
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
#ser.timeout = None          #block read
ser.timeout = 0             #non-block read
#ser.timeout = 2              #timeout block read
ser.xonxoff = False     #disable software flow control
ser.rtscts = False     #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False       #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2     #timeout for write
except Exception, e:
    print "error open serial port: " + str(e)
if ser.isOpen():
        ser.flushInput() #flush input buffer, discarding all its contents
        ser.flushOutput()#flush output buffer, aborting current output 
                     #and discard all that is in buffer
        #write data
        print("write data: AT+CSQ=?x0D")
        time.sleep(0.5)  #give the serial port sometime to receive the data
        numOfLines = 0
        while True:
            response = ser.readline()
            print("read data: " + response)
            numOfLines = numOfLines + 1
            if (numOfLines >= 5):
    except Exception, e1:
        print "error communicating...: " + str(e1)
    print "cannot open serial port "


The program send out AT commands to query modem signal strength. If you want to know more about modem AT commands, refer to post here.

If you set the timeout as 2, the readline() method is blocking call with timeout, the output will be as below,

write data: AT+CSQ=?
read data: AT+CSQ=?

read data: +CSQ: (0-31,99),(99)

read data: 

read data: OK

read data: 

If you set the timeout as None, the readline() method is non-blocking call, the output is,

write data: AT+CSQ=?
read data: AT+CSQ=?

read data: +CSQ: (0-31,99),(99)

read data: 

read data: OK

Note that there is less lines of output, program hangs and cannot exit.

If you set the timeout as 0, the readline() method will return immediately, the output is,

write data: AT+CSQ=?
read data: AT+CSQ=?

read data: +CSQ: (0-31,99),(99)

read data: 

read data: OK

read data: 



pyserial documentation:

Do it Slowly, Don’t Do it Again and Do it Automatically

Software development never ends once it’s started. Programmers are busy. We work long hours and we try to act fast.

Well, that’s the way I work most of the time, and it turns out not so efficient.

A lot of times that I am in a rush, I started to try different ideas without much thinking. Most of the time, the trials would fail and time would fly. When I finally realized I need to think more, calm down, started to think the problem carefully and do it slowly, the problem is quickly solved a lot of times. So first reminder for myself, do things slowly. When you’re acting slow, you tend to think more and make less mistakes.

Once I heard a sentence from someone I can’t recall, “one important goal of doing something is never do it again”. Well, considering the amount of time that I spent on repeated tasks, I must say I should remember this by heart. If we can really achieve this goal when we’re doing something, it doesn’t mean the job we’ve done is good that we don’t need to repeat it, it also means we only spend time on something once.

Well, maybe it’s difficult to avoid doing it again, but at least we should ensure we can do it much faster if we have to do it again. Ya, that’s one of the reasons this blog exist (I make notes so I can recall the stuff much faster when I need them again). Software development is going to be a long term journey for me, so I really need to work better on this. Taking more notes, summarizing more and writting more blogs. Smile

Lastly, there’re certain tasks we’ll have to repeat it, and if a task is ever repeated, it’s likely to be repeated again, and again. So automate it! Make the computers work for us! And they’re the ones that good at repeated tasks.

Linux Get udev Device Information in Python–pyudev

udev is the device manager for the Linux kernel. It consists of 3 parts, libudev, the library that provides access to device information; the daemon udevd, manages the virtual file system normally mounted at /dev, running in user space; and udevadm, an utility tool for diagnostics.

This entry covers how to access the device information through udev in Python.

1. Install pyudev

A python module pyudev needs to be installed first. One can use easy_install to install python module. If easy_install is not available on your system, run the following command (using Ubuntu as example),

sudo apt-get install python-setuptools


Then type the following command to install pyudev,

sudo easy_install pyudev

pyudev is a python binding to libudev. One can import pyudev namespace and then use classes and functions in this library. The most important object in pyudev is Device, which gives you access to all the information about a device.

2. A Sample Python Program

Below is a sample program that uses pyudev to query usb device information. One can extend it or modify it easily to suit his/her own needs.

If a sysfs path is provided, the program will retrieve the information for the particular device; otherwise, the program loop through all usb devices and output information for every one of them.

import pyudev, sys
from datetime import datetime

def log(level, msg):
    #strToWrite = str( + ":" + str(msg)
    i = 0
    strToWrite = ""
    while True:
        if (i >= level):
        strToWrite = strToWrite + "  "
        i = i + 1
    strToWrite = strToWrite + str(msg)
    print strToWrite

def getInfoForADevice(aDevice, level):
    msgStr = "*****************************************************"
    log(level, msgStr)
    msgStr = "sys_path: %s:" % aDevice.sys_path
    log(level, msgStr)
    msgStr = "device_path: " + aDevice.device_path
    log(level, msgStr)
    msgStr = "sys_name: " + aDevice.sys_name
    log(level, msgStr)
    msgStr = "subsystem: " + str(aDevice.subsystem)
    log(level, msgStr)
    msgStr = "driver: " + str(aDevice.driver)
    log(level, msgStr)
    msgStr = "device type: " + str(aDevice.device_type)
    log(level, msgStr)
    msgStr = "device node: " + str(aDevice.device_node)
    log(level, msgStr)
    msgStr = "----------ATTRIBUTES----------"
    log(level, msgStr)
    for attrName, attrValue in aDevice.attributes.iteritems():
        msgStr = attrName + ": " + str(attrValue)
        log(level, msgStr)
    for aChildDevice in aDevice.children:
        getInfoForADevice(aChildDevice, level + 1)

if __name__ == '__main__':
    global context
    context = pyudev.Context()
    if (len(sys.argv) == 1):
        devices = context.list_devices(subsystem="usb") 
        #devices = context.list_devices()
        if not devices:
            print "no device found"
        for aDevice in devices:
            getInfoForADevice(aDevice, 0) 
        aDevice = pyudev.Device.from_path(context, sys.argv[1])
        getInfoForADevice(aDevice, 0)


The program first get a list of usb Device objects,  and access the information of each one by calling method getInfoForADevice(). Notice that this method is recursive and the child device information is also accessed.

You can redirect the output to a file first and examine it later by entering the following command,

./ > output.txt


If you want to query information for a specific device, following the format below,

./ <sys_path>

An example is,

./ /sys/devices/pci0000:00/0000:00:06.0/usb2/2-1/2-1:1.0



pyudev documentation:



How to Reset USB Device in Linux–using libusb

This is a follow up of the previous entry How to Reset USB Device in Linux. The previous blog covers a method to reset usb device using ioctl system call. This blog gives an alternative approach to reset usb device, using libusb.

libusb is a cross-platform library giving user level application uniform access to usb devices. You’ll need to install the development package first. Simply typing the following commands to your terminal (using Ubuntu as an example),

sudo apt-get install libusb-1.0-0-dev

After installation, you can use the methods in libusb. Below is the C source code to reset usb device using libusb API,

#include <stdio.h>
#include <stdlib.h>
#include <libusb-1.0/libusb.h>

//compile: gcc usbreset.c -o usbreset -lusb-1.0
//usage: ./usbreset 2 6
//use lsusb to check out the bus number and device number

struct libusb_device_handle *devh;
struct libusb_device *dev;
struct libusb_device **devs;

void resetUSB() {
    int success;
    int bpoint = 0;
    do {
        success = libusb_reset_device(devh);
        if ((bpoint % 10) == 0) {
        if (bpoint > 100) {
            success = 1;
    } while (success < 0);
    if (success) {
        printf("nreset usb device failed:%dn", success);
    } else {
        printf("nreset usb device okn");

struct libusb_device* search_device(int _busNum, int _devNum) { 
    libusb_device *l_dev;
    int i = 0;
    int l_busNum, l_devNum;
    while ((l_dev = devs[i++]) != NULL) {
        printf("check against %d devicen", i);
        l_busNum =(int) libusb_get_bus_number(l_dev);
        l_devNum =(int) libusb_get_device_address(l_dev);
        printf("bus number: %d; device number: %dn", l_busNum, l_devNum);
        if ((l_busNum == _busNum) && (l_devNum == _devNum)) {
            printf("found devicen");
            return l_dev;
    return NULL;

int main(int argc, char **argv) {
    //parse the input parameters to get the bus number and device number
    int l_busNum, l_devNum;
    int l_ret;

    printf("program started!n");
    if (argc < 3) {
        printf("not enough arguments!n");
        printf("usage: ./usbreset <bus number> <dev number>n");
        return 0;
    printf("bus number: %sn", argv[1]);
    printf("dev number: %sn", argv[2]);

    l_busNum = atoi(argv[1]);
    l_devNum = atoi(argv[2]);
    printf("bus number: %d; dev number: %dn", l_busNum, l_devNum);

    l_ret = libusb_init(NULL);
    if (l_ret < 0) {
        return l_ret;
    l_ret = libusb_get_device_list(NULL, &devs);
    if (l_ret < 0) {
        return (int) l_ret;
    dev = search_device(l_busNum, l_devNum);
    if (dev == NULL) {
        printf("device not foundn");
        return 0;
    l_ret = libusb_open(dev, &devh);    
    if (l_ret == 0) {
        printf("got the usb handle successfully.n");
    } else {
        printf("error getting usb handle.n");
    //reset the usb device
    //free the device list
    libusb_free_device_list(devs, 1);

    return 0;

The code can be compiled using

gcc usbreset.c -o usbreset -lusb-1.0

To use the complied program usbreset, you can simply use,

sudo ./usbreset <bus number> <device number>

To check the bus number and device number of a usb device, you can use lsusb command.

To check if a device is resetted or not, you can use tail -f /var/log/messages.

An detailed example is given in How to Reset USB Device.

My First Open Source Project, and More

Looks like I’ve been writing a lot of entries for “Coding Beyond Technique” recently, mainly because I’m buried by company work and my master thesis project and writing these entries are a enjoyable relaxation. Smile

I’ve released one of my Android apps – Advanced Phone Log as open source project, you can refer here. The app has 6946 downloads and 1957 active users as of Jun 5 2011. Many users have given valuable feedbacks and look forward to seeing new features. But I might not have time to work on this app any more, so I decided to release it as open source.

Recently I’ve  been thinking of being more focused on Multimedia applications. There’re several Android apps that I developed doesn’t belong to this category and I decided to give up on them. (It really hurts as I have spent a lot of time on them.)

I once read a post on Hacker News, saying “if you are going to give up your source code, make it open source”. I definietely agree with it. And therefore, I’m going to open source all those projects, once I have time to upload them. (If someone else can adopt them, it will make me hurt less Smile)

ya, I guess I’ll have to let them go to be more focused.