Inspirated

 
 

August 30, 2009

HOWTO: Add grid lines to a GtkDrawingArea in PyGTK

Filed under: Blog — krkhan @ 6:29 pm

Recently, I needed to create some visualizations in a drawing area for one of my PyGTK apps. The PyGTK tutorial had an excellent writeup complete with a working example for immediate help. Unfortunately, my requirements were of a “grid” view on which other objects would be drawn. Naturally, I hoped for some variable on the GtkDrawingArea which I would set to true and have the grid lines drawn automatically. But since I couldn’t find any such magic setting in the API, I had to draw the lines manually.

Consequently, I could use either of the following approaches:

  • Loop horizontally and vertically while draw_line()ing.
  • Draw a 10×10 box as a tile and repeat it over the background.

The first approach would’ve worked faster but involved writing more code. The second was uglier — especially for larger images — but resulted in me having to add only a few lines to the example:

72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
        xpm_data = ["10 10 2 1",
            " 	c #EEEEEE",
            ".	c #FFFFFF",
            "          ",
            " ........ ",
            " ........ ",
            " ........ ",
            " ........ ",
            " ........ ",
            " ........ ",
            " ........ ",
            " ........ ",
            "          "]
        tile_pixmap, tile_mask = gtk.gdk.pixmap_create_from_xpm_d(
            area.window, None, xpm_data)
        tile_gc = area.window.new_gc(fill = gtk.gdk.TILED,
            tile = tile_pixmap)
        width = int(self.hruler.get_range()[3])
        height = int(self.vruler.get_range()[3])
        area.window.draw_rectangle(tile_gc, True, 0, 0, width, height)

Turning this:

GtkDrawingArea Example

Into this:

GtkDrawingArea Grid Example

Note that the 10×10 tiles’ borders match prettily with the markers on top and left rulers. There will definitely be some more efficient method for achieving this but for the time being tiling serves my needs perfectly.

Tags: , , , , , , ,

August 28, 2009

Brace yourself and join the euphoria: Nokia N900 has been announced

Filed under: Blog — krkhan @ 10:18 pm

Rarely do I feel the urge to jump on the buzzword bandwagon. This time, however, the product deserves the hype. Before you hear me any further, jump straightaway to the Nokia 900 website and stagger yourself into oblivion. Cliff notes:

  • First Linux-based cellphone from Nokia — world’s largest manufacturer of mobile phones. The previous Linux tablets from the Finnish giants (e.g., N810) were nice but lacked the basic phone functionality.
  • A plethora of insane mouth-watering features that are just too many to list here in their entirety.
  • S**.

If you still aren’t convinced, let me be lazy and shamelessly copy some items from the linked page:

  • ARM Cortex – A8 superscalar microprocessor core running at 600 MHz
  • Up to 1 GB of application memory (256 MB RAM, 768 MB virtual memory)
  • 3D graphics accelerator with OpenGL ES 2.0 support
  • 32 GB internal storage
  • 3.5G and WLAN connectivity
  • Quadband GSM with GPRS and EDGE
  • 5-megapixel digital camera
  • Carl Zeiss optical lens
  • Touch-sensitive screen
  • Assisted-GPS receiver

Essentially, that’s iPhone+N810+N96+Neo FreeRunner for you. An year ago, I did have a feeling that Nokia was planning big things with Linux when it acquired Trolltech but I had absolutely no idea that the definition of “big” would be this exotic.

Can’t. Wait.

Tags: , , , , ,

August 23, 2009

Workaround for fixing X.org acceleration issues on Intel chipsets

Filed under: Blog — krkhan @ 1:39 pm

Recent X.org drivers for Intel chipsets have introduced a new acceleration method called UXA which is supposed to provide “simpler, faster” code. However, for whatever reason, this bleeding-edge feature actually results in a loss of performance and reliability for particular chipsets (e.g. 915 family) on most distributions (Fedora and Ubuntu to name the foremost). In order to work around these issues, two solutions can be used:

  1. Enable Tiling in xorg.conf.

    Section "Device"
    	Identifier  "Videocard0"
    	Driver      "intel"
    	Option      "Tiling" "False"
    EndSection

    This fix does help the low framerate issue encountered on most distros, but it introduces screen tearing on some installations and worse, can happen in occasional X crashes as well.

  2. Use “greedyMigrationHeuristic with EXA instead:

    Section "Device"
    	Identifier  "Videocard0"
    	Driver      "intel"
    	Option      "AccelMethod" "EXA"
    	Option      "MigrationHeuristic" "greedy"
    	Option      "NoDDC"
    EndSection

    While this completely bypasses the UXA acceleration, it seems to work well for most users.

For the time being, I’m sticking with the second workaround since I have no issues with using the older acceleration architecture until the new one achieves some decent stability.

Tags: , , , , , , , , ,

August 18, 2009

Fedora Software Patents FAQ

Filed under: Blog — krkhan @ 8:48 pm

Going through the Planet Fedora feed, I spotted this excellent write-up which tries to explain Fedora-related patent questions such as “why the $*#@ won’t Red Hat give us MP3 playback support“. I would be straight-down lying if I said that the article offered nothing new to me. In fact, some answers, such as this one … :

Patent licenses are usually granted via payment of royalty based on the number of users. Since Fedora is free and open source software, the effective number of users is essentially unrestricted. Patent holders are generally unwilling to give a blanket patent license for unlimited use, and the royalty payments for these licenses would be too high to purchase them outright. Proprietary operating systems like Microsoft Windows include the cost of the patent license as part of the product being sold to the end users. Fedora is not sold commercially, so there is no way to recoup these substantial expenses. Even assuming funds are available to do so, licenses such as the GPL require a written patent grant (in regions where software patents are enforced) compatible with royalty free distribution and modification. Since meeting this requirement effectively nullifies the effect of a patent, patent holders are also generally unwilling to do this.

… clarified in my mind a few long-held confusions about Fedora’s reluctance regarding patent infringement. For the general user, RPM Fusion works around all that crap; but a read of the linked FAQ is recommended nevertheless for having an idea about the issues inherently involved with seemingly simple tasks such as playing DVDs.

Tags: , , , ,

July 23, 2009

Microsoft’s open-source contribution traced back to GPL violation

Filed under: Blog — krkhan @ 11:36 pm

(Or: Things still make sense.)

Last week — just as Wayne Rosso stopped comparing RIAA to Stalin — M$ did its own volte-face and not only stopped calling GPL a “cancer” but decided to release some 20,000 lines of code carrying the plague itself. Pigs started flying. Some of the open-source evangelists started fantasizing about Microsoft as an ally suddenoutbreakofcommonsense and the cautious ones — who suspected some ulterior motive behind the move — were declared by them to be paranoid and rabid haters.

The storm didn’t last long though, as it was later reported that the change of heart was prompted by a GPL violation in Hyper-V. Some see this as a win for GPL. Some see this as a perfect backdrop for FUD against open-source (“it’s so goddamned viral it even infected us when we wanted interoperablity”) while some see this as a failure at M$’ part for not honestly explaining the reasons behind the code release. Whichever category you belong to, it’s nice to know that swine still have their feet firmly on ground.

Tags: , , , ,

July 5, 2009

The top 5 worst mistakes on command-line

Filed under: Blog — krkhan @ 10:58 pm

I could start off with an intro paragraph here but I’ll prefer keeping it sweet and simple: command-line is addictive.

For many kinds of tasks — ranging from system administration to organizing folders — I find CLI to be extraordinarily more productive than GUI clicking. For example, vim-ing through a code, if I decide I need to lookup a particular symbol in the current directory, I can quickly do a recursive grep without even taking my hands off the keyboard. Similarly, I find utilities such as mv or cp to be significantly faster than GUI file managers’ equivalent features. The learning curve is definitely steep and I also am not implying that everyone should find it equally productive but for me at least, it works like a charm.

It wouldn’t be an exaggeration to say that CLI provides a terrible amount of power at fingertips of its users. While that power is tremendous fun, it also can be a source of epic fails if not handled with caution. The fact of the matter is, as one grows accustomed to quickly doing work through text-based input, overlooking those cautions almost becomes second nature. It’s not uncommon to find a commandaholic holding his head in his hands while staring at the screen in disbelief. GUI does get credit for being a little more prone to accidental mistakes by consistently providing a visual view of what’s about to happen.

Moving on from the ill-starred mischief that I posted about last week, I thought I should compile a list of all time worst incidents of me cursing my fingers for being so familiar with the CLI. Here they are:

  1. Ctrl-C

    Sometimes, I blame Christopher Sholes for putting the Z and C keys so close on the keyboard. ‘Nuff said.

  2. Deleting the wrong partition in parted

    (parted) help rm                                                          
      rm NUMBER                                delete partition NUMBER
    
    	NUMBER is the partition number used by Linux.  On MS-DOS disk labels,
            the primary partitions number from 1 to 4, logical partitions from 5
            onwards.

    If you’re wondering why deleting a partition is placed so low on the list, the answer is TestDisk. Mere seconds after I deleted my primary partition containing all my data, I stopped all activities, booted into a rescue mode and used the God-sent utility to restructure my partition table like before with a cumulative data-loss of 0%.

  3. e2fscking e2fucking a mounted file-system

    [root@orthanc ~]# e2fsck /dev/sda2
    e2fsck 1.41.4 (27-Jan-2009)
    /dev/sda2 is mounted.  
    
    WARNING!!!  Running e2fsck on a mounted filesystem may cause
    SEVERE filesystem damage.
    
    Do you really want to continue (y/n)? 

    See that SHOUTING WARNING? I did too. But back then, I ignored it as casually as anyone ignores licensing agreements. Needless to say, the results weren’t as inconsequential as clicking “I accept” and moving on without a hint of doing something legally binding.

  4. rm -rfing the wrong directory

           -f, --force
                  ignore nonexistent files, never prompt
    
           -r, -R, --recursive
                  remove directories and their contents recursively
    

    If the last tool had the F-word in its title as the warning, this one should be read as rm --recursive-f***. The H-bomb of command-line tools, once you detonate it on a directory you didn’t mean to set it upon, even CTRL-C won’t be able keep you in one piece because of rm‘s ruthless speed and efficiency. The only ray of hope is ext3grep, but depending on numerous factors (partition structure, number of files, file types, alignment of stars etc.) your recovery prospects would range anywhere from ±100% to ±100%. You read that right.

  5. mkfsing the wrong partition

           mkfs  is  used to build a Linux file system on a device, usually a hard
           disk partition.  filesys is either the device  name  (e.g.   /dev/hda1,
           /dev/sdb2).   blocks  is  the  number of blocks to be used for the file
           system.

    The granddaddy of all command-line fuckups. If you have confused /dev/sdb for /dev/sda (an easy slip up — as I learned the hard way), it’s time to move on. Sure, you will find people selling tools for recovering data from formatted Ext3 partitions; expecting those tools to work would be a lot like expecting the King of Pop to miraculously pop up from his coffin on Tuesday and perform a ground-breaking reenactment of 83’s Motown performance.

“Blessed are the forgetful; for they get the better even of their blunder.” — Friedrich Nietzsche

Tags: , , , , , ,

July 2, 2009

Workaround for autostarting applications in a particular order on Xfce/GNOME/KDE

Filed under: Blog — krkhan @ 11:04 pm

Among many of freedesktop.org’s vital contributions to GUI computing on POSIX platforms, a divine one has been the uniform specification for automatically launching programs at initiation of a desktop session. Informally put (or theoretically at least), it means that you can add programs to startup in the appropriate settings, and they will be launched automatically at initiation of your session regardless of which desktop environment you use.

It’s been about 4 years since I migrated to Xfce for everyday work and it does come with a basic tool for managing startup entries (accessed through Application Menu > Preferences > Session and Startup). Still, if you need anything more than rudimentary addition/deletion of the entries you’re pretty much out of luck. For example, I wanted to start the applications in a particular order. I don’t know whether GNOME or KDE have the feature yet, but Xfce lacked the support for maintaining any such arrangement. The proper way to deal with the issue would have been to code the feature in the session manager myself, but since I barely get time to even read fortune-mod these days I instead had to rely on an ugly workaround. If you’re in the same sticky situation, here it is: Go to the autostart directory (usually ~/.config/autostart), open the startup script you’re concerned with, and edit the Exec line like this:

Before:
Exec=awn-autostart

After:
Exec=bash -c "sleep 3 && awn-autostart"

The ugliness arises from the fact that the new Exec line is merely launching the program with a delay of 3 seconds. Now, you can add another program with a delay of 4 and it will almost be guaranteed to start after the 3 seconds’ one across all desktop environments. I really hope that the specification itself would be revised soon to provide a uniform way of setting the startup order. But until that gets done, I can thank sleep for making my life simpler.

Tags: , , , , , ,

June 27, 2009

The highs and lows of Leonidas — This. Is. Fedora!

Filed under: Blog — krkhan @ 12:43 am

There is a reason why I never evangelize Fedora much: it’s far from perfect. There is also a reason why I use Fedora for my everyday Linux-ing: it’s good when it starts working. The two seemingly conflicting viewpoints are not mutually exclusive, since Fedora’s instability as well as its appeal can be termed in one word: bleeding-edge.

The biannual cycle of backup-reinstall-reconfigure for each new Fedora release works fine for me. It takes a day or two to get everything back to the way want them to be, but the trade-off is almost always worth it. Consider this, upgrading from a Fedora version to the next will almost never work seamlessly. Nevertheless, the re-installation mantra allowed me to use PulseAudio’s “perfect” setup much before most of the other distros’ users. The fact that I got a clean start for the new sound architecture also explains why I never had any incompatibility issues with it and consequently, my status as one of its huge fans.

Another reason why I’m still hanging on to Fedora is because of the familiarity factor, as I no longer have the ample time for trying out newer distributions just for the sake of it. Linux From Scratch was a mighty fun experience, but keeping it up-to-date was nothing short of a Herculean task. Gentoo sounds very appealing, but I don’t want to download a DVD, go through the hassle of installing and getting familiar with the new distro and then emerge a whole universe of updates on an internet connection as reliable as Fedora on Hurd. The perfect solution would be to install a new release of Gentoo but unfortunately, it’s been over an year now since I started waiting for one.

Which brings us to Fedora 11 — lovingly nicknamed after everyone’s favorite Spartan king.

The predominant aspects of the new release which affect me as a user are the Ext4 filesystem and the Kernel Modesetting feature. So far, I am not even using the former. Yes, yes, I know I bragged about bleeding-edge before, but let me explain why I did not go for it in this particular case:

  • Filesystem is the most critical aspect of a system for me. I can toy around and experiment with everything but this holy grail. If my audio fails, I can try fixing it. If X stops working, ditto. If my data is corrupted, I’m FUBAR.
  • Anaconda crashed when I tried to update the boot-loader configuration for a system with Ext4 partitions.
  • I couldn’t find a way to use Ext4 without using the Logical Volume Manager. I like my partitions as /dev/sdaX and entries such as /dev/mapper/yourmom/blahblahblah/finallythedrive in the fstab file turn me off.

Nevertheless, KMS made up for the Ext4 — or lack thereof.

  • Booting is now prettier.
  • Working in runlevel 3 is so much more efficient because of all the extra space provided by higher resolution.
  • Switching virtual terminals and X sessions is a breeze.
  • Suspend/Resume is a bit more stable.

Other significant changes include Xfce 4.6, Firefox 3.5 and the reworked volume management in Pulse. Overall, I’m pretty satisfied with my decision to upgrade, and here’s to the hoping that the next 6 months will go as smooth as the previous ones.

Tags: , , , , , ,

May 17, 2009

Inbox Stats v1.0 — Because graphs speak louder than numbers

Filed under: Blog — krkhan @ 4:00 am

Inbox Stats v1.0

Changelog:

  • As can be seen from the screenshot above, graphs can be turned on through the options menu. Implementing them resulted in two useful modules:
    • scrolledcanvas: Provides a derived Canvas class which has built-in support for scrolling oversizes images.
    • roundedrectangle: Provides functions for drawing rectangles with rounded corners on a Canvas or Image. Optionally, text can be given which will be prettily centered (and truncated upon requirement) in the drawn shapes.
  • More minor code enhancements and bugfixes.

You can find both the modules and the application itself here. All code is released under the PSF license so feel free to use it any way you want. Oh, and if you still haven’t figured out why anyone would be interested in the SMS stats in the first place, here’s a little quote for you:

“Statistics are like a bikini. What they reveal is suggestive, but what they conceal is vital.”

Tags: , , , , , , , , , , , ,

May 14, 2009

User-defined iterators in Python

Filed under: Blog — krkhan @ 5:19 am

Iterable classes are one of the features which make Python code more readable. Simply put, they let you iterate over a container a la:

1
2
for s in ("Spam", "Eggs"):
	print s

Here, s iterates over the tuple printing the words one by one.:

Spam
Eggs

Now comes the interesting part: How do I make my own classes iterable? The official Python Tutorial gives a working example for how to do it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Reverse:
	"Iterator for looping over a sequence backwards"
	def __init__(self, data):
		self.data = data
		self.index = len(data)
 
	def __iter__(self):
		return self
 
	def next(self):
		if self.index == 0:
			raise StopIteration
		self.index = self.index - 1
		return self.data[self.index]
 
value = Reverse('spam')
for char in value:
		print char

Output:

m
a
p
s

The example appeared perfectly fine to a beginner like me. However, since I’m just kinda twisted in the head, I added a new line in the for loop:

16
17
18
19
value = Reverse('spam')
for char in value:
	if char in value:
		print char

Which resulted in the (quite unexpected) output:

 

That’s it. Nothing. Even though the code should make perfect sense and does work in case of built-in types. For example:

1
2
3
4
tup = ("Spam", "Eggs")
for s in tup:
	if s in tup: 
		print s

So daisy-ly gives:

Spam
Eggs

The culprit in case of tutorial’s example for user-defined iterators? After toying around the code sample a little, here’s what I pinned down:

  • On the nested lines where another iterator is required, the Reverse class is supposed to return instance of an iterator which would define the next() method for returning successive values.
  • Since the Reverse class returns only itself in this scenario, the self.index variable is shared among iterators of the Reverse('spam').
  • As a result, Reverse.next() raises the StopIteration in the nested condition.

Once I understood the underlying problem, some further head-scratching and a can of malted drink resulted in the solutions:

  • Return a copy for the iterative functions instead of the instance itself:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    
    import copy
     
    class Reverse:
    	"Iterator for looping over a sequence backwards"
    	def __init__(self, data):
    		self.data = data
    		self.index = len(data)
     
    	def __iter__(self):
    		return copy.copy(self)
     
    	def next(self):
    		if self.index == 0:
    			raise StopIteration
    		self.index = self.index - 1
    		return self.data[self.index]
     
    value = Reverse('spam')
    for char in value:
    	if char in value:
    		print char

    Pro: Less strain on the programmer, only a couple of extra lines of code are needed.
    Con: copying the instance can be expensive in case of larger containers.

  • Use another class:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    
    class Reverse:
    	"Iterator for looping over a sequence backwards"
    	def __init__(self, data):
    		self.data = data
     
    	def __iter__(self):
    		return ReverseIter(self)
     
    class ReverseIter:
    	def __init__(self, inst):
    		self.inst = inst
    		self.index = len(self.inst.data)
     
    	def next(self):
    		if self.index == 0:
    			raise StopIteration
    		self.index = self.index - 1
    		return self.inst.data[self.index]
     
    value = Reverse('spam')
    for char in value:
    	if char in value:
    		print char

    Pro: Since the whole container is not copied, only the index is unique among iterators — less burden on the memory.
    Con: Not everyone likes defining new classes.

Both solutions worked equally well and resulted in the same output (the expected one this time):

m
a
p
s

The choice of either solution is solely dependent on the programmer’s preference. As a side note, after equating Python programming with carnal activities in few of my previous posts, I’m gonna take it to the next step and finally tag this post accordingly.

Tags: , , , , , , , , , ,
« Previous PageNext Page »