Your Python smells like Java

Whether you like it or not, you already use different languages each day: SQL, Javascript, Python, C++ & more. Wisdom goes that learning different programming languages will help you become a better programmer, but many programmers don't get this benefit & feel that it's a waste of time. After talking & working with many of them for many years, I found out that they learn the syntax of the language, maybe some libraries, but they don't learn the soul of the language.

Examples

# Bad: you need to read to the end to know the code intention
img.find('.jpg') != -1
img.find('.jpg') >= 0

# Easier to read
'.jpg' in img
'.jpg' not in img
# Bad. Hard-coded number
img[-4:] == '.jpg'

# Good. Works with any string of any length
img.endswith('.jpg')
# Bad
(img.endswith('.jpg') or img.endswith('.jpeg') or img.endswith('.png') or 
    img.endswith('.gif')

# Good: uses python built-in capabilities to make code more compact
img.endswith((".jpg", ".jpeg", ".png", ".gif"))
# Bad
path == 'js' or path == 'css' or path == 'img' or path == 'font' or path == 'fonts'

# Good. Compact code.
path in ('js', 'css', 'img', 'font', 'fonts')
# Bad
(os.path.exists(os.path.join(path, "space")) or 
    os.path.exists(os.path.join(path, "bucket")) or 
    os.path.exists(os.path.join(path, "actor"))

# Good. Compact code. Reads better. The list can be moved to a different file
any(os.path.exists(os.path.join(path, item)) for item in ["space", "bucket", "actor"])
# Bad
for i in range(len(lst)):
    elt = lst[i]
    print i, elt

# Good. Uses built-in python functions
for i, elt in enumerate(lst):
    print i, elt
# Bad
print 'Hello ', name, '. You are ', age, ' years old'

# Good. Reflects the structure of the intended output
print 'Hello {name}. You are {age} years old'.format(name=name, age=age)
# Bad
if not (key in dict):
    print 'Key missing'

# Good. Reads better
if key not in dict:
    print 'Key missing'
# Bad
s = names[0]
for name in names[1:]:
    s += ', ' + name

# Good. Doesn't have the off-by-one issues. Also faster
s = ', '.join(names)
# Bad
# Find if array1 is a subset of array2
is_subset = True
for x in array1:
    found = False
    for y in array2:
        if x == y:
            found = True
            break

    if not found:
        is_subset = False
        break

# Good. 2 lines instead of 10!
def subset_of(array1, array2):
    return set(array1).issubset(array2)
# Bad 
if case_sensitivity.lower() == 'sensitive':
    matcher = fnmatch.fnmatchcase
elif case_sensitivity.lower() == 'insensitive':
    def matcher(fname, pattern):
        return fnmatch.fnmatchcase(fname.lower(), pattern.lower())
else:
    matcher = fnmatch.fnmatch

# Good. The match code can be moved to a different file
matchers = {
'sensitive': fnmatch.fnmatchcase
'insensitive': lambda fname, pattern: fnmatch.fnmatchcase(fname.lower(), pattern.lower())
}.get(case_sensitivity.lower(), fnmatch.fnmatch)

Read more

Why don't you make your side project?

Slides, Source

SoundCloud playlist downloader

SoundCloud is a great resource for interesting audio tracks audio tracks. I found this playlist that I wanted to download. Although the author is allowing download of tracks, I've to download each track manually, which is a time-consuming task. I searched for any tool to help me download the whole playlist, but I didn't find any. So I did what a great programmer should do: I made it myself.

Please don't use it to steal other people's audio tracks.

Yahoo, please respect my choices!

Yahoo added me to different marketing newsletters without my permissions. When I unsubscribed they told me that it will take 10 business days to take effect! This is the 3rd time I do this!

Yahoo, I know you want to make more money, but please respect my choices!

Building websites on Google Cloud

Slides, Source

Front-end optimizations

Slides, Source

My toolbox

It makes me sad when I find out that a lot of people use bad tools, so here is a list of tools that I use almost everyday (as of May 2013). Most of them are great & some of them are acceptable. Feel free to suggest better tools.

Your life is miserable without these

VLC Player

There are 2 types of people:

People who try to open a movie with Windows Media Player, but find that they cannot open any movie with it, so they download the XviD codec & install it. Later, they try to open a movie with extension RMVB, then they find that they want another codec which conflicts with the 1st codec, so they remove the 1st codec & install the 2nd, but not all movies requiring XviD works, so they ask a friend who tells them about the Combined Community Codec Pack which plays all kind of videos except Real Media & QuickTime, but if you install Real Alternative & QuickTime Lite to play RM & MOV videos. Now they just need to install DirectVobSub for subtitles & they are finished. This is just for Windows.

The 2nd type of people installed VLC player & lived happily ever after.

Everything search engine

So you want to search for files by their name or extension. You open Windows search & type the file name, then you wait, and wait, and wait, and ....

During this, I downloaded & installed Everything search engine, searched for the files I need, found them & already working on them.

Now, Windows just showed the results. Please remind me why I searched for these files?

SumatraPDF

Why install 48 MB slow application to view PDFs when you can install a 5MB lightning-fast application which can view PDF, MOBI & many different formats?

Google Chrome or FireFox

Which one you choose depends on you, but you should not use IE.

Paint.net

Swiss-army knife for raster image editing. What MS Paint is supposed to be.

Virtual CloneDrive

Free Virtual CD program without ads. You won't find a better one.

Free Download manager (FDM)

Free & easy to use download manager.

youtube-dl

Did you see James Shore series Let's Play TDD & wondered how you are going to download all of these videos to see them offline? youtube-dl can download from youtube & tens of other sites as well.

ffmpeg

FFmpeg is a media conversion tool. I've mixed feelings against it. It's very powerful & fast, but also very hard to use. Each time I've to google how I can use it, but it's performance makes it practical than other conversion tools I tried.

CCleaner & Defraggler

The best crap cleaner & disk defragmenter.

For command-line gurus

ConEmu

It's a shell container which groups all your shells in a single window with multiple tabs, including putty.

PyCmd

A smarter shell for Windows. I like that when you press TAB it shows all the available options, instead of cycling through all the options. It also supports persistent history.

For the Ninja programmer

Python

I used different programming languages, but Python is the swiss-army knife that I use when I've the choice, and it didn't fail me. I used it for small scripts, GUI apps, to high-performance web apps.

Sublime text

I wanted a powerful text editor (like VI or Emacs) but didn't need me to relearn how to use a text editor. I used Notepad++ for a long time, before I switch to Sublime.

SQLite & Postgres

SQLite is convenient for development, because it doesn't require installation of any kind.

I had nice experience with Postgres when I built rawa7.com. Installing PostGIS (Postgres GIS extension) with other GeoDjango dependencies on Windows is painful, but after this it's a joy to use.

It also supports compression, recursive queries, Multiversion concurrency control, custom types, table inheritance, regular expressions & other interesting features. DB choice is probably the hardest thing to change in an enterprise, but Postgres is worth a try.

Ask Developer Podcast - Episode 9 - Passionate Developer

Dynamic languages on .net

Today was the 2nd joint event by dotnetworks and EGJUG. There was 2 sessions: Oracle ADF a practical experience (which I didn't attend, unfortunately), and dynamic languages on .net, by yours truely :). There were very few people who attended, about 15 people. They were very active and participating, and I believe they liked the session. The main goal of the session was introducing Python (specially IronPython) to the people, differences and similarities to C# & Java, and what to apply lessons learnt from Python to these languages. This is the presentation (which is very simple, because most of the session was practical)

Also you will find the DreamPie session (with the sample files used in the session). DreamPie is an excellent Python shell, which can integrate with CPython, IronPython and Jython, also giving you correct AutoComplete. As a bonus, this is also an example of using BeautifulSoup - a Python library for parsing badly-formatted HTML - from C# 4.0. BeautifulSoupUser.zip, 11.csv.zip, 11 - Copy.csv.zip, Python-Session-2011-01-22.html

MIX09 videos

MIX conference is my favorite conference. It is always full of surprises, and it is not restricted to Microsoft technologies. It has been a habit for me to grab the links to MIX videos since MIX 07, and I'm keeping this habit for this year too :). Here is the source code to the Python program which grabs the links. It generates two files: mix09_links.txt which contain only the links so you can import them in your favorite text editor, and mix09_title.txt which contain the title of every session and its URL, so you know the title of the session.

from urllib import urlopen
import re
links_file = open('mix09_links.txt', 'w')
description_file = open('mix09_title.txt', 'w')
try:
    for i in range(16):
        url = 'http://videos.visitmix.com/MIX09/page%s' % (i+1)
        print url # for tracking
        s = urlopen(url).read()
        links = re.findall(r'<h2 class="title" title="(.*?)"><a href="/MIX09/(.*?)">.*?</a></h2>', s)
        for link in links:
            links_file.write('http://mschannel9.vo.msecnd.net/o9/mix/09/wmv-hq/%s.wmv\\n' % link[1].lower())
            description_file.write('%s\\nhttp://mschannel9.vo.msecnd.net/o9/mix/09/wmv-hq/%s.wmv\\n\\n' % (link[0].lower(), link[1]))
finally:
    links_file.close()
    description_file.close()

and for the lazy person, here are the two files: mix09_title.txt, mix09_links.txt

© 2014 Mohammad Tayseer

Theme by Anders NorenUp ↑