Are you looking for my non-technical blog?

This is now my technical-only blog, my non-technical blog is here.
Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

12 January 2006

Sqlite - Date and Time Data Types

SQLite handles dates quite strangely. If you create a table and put a date in it, the only way SQLite will take the input is "2004-06-01 12:00:00" anything else it won't recognize as a date and thus none of the date functions will work. Assuming you have a date entered propely (like above) you get date information from the db like so.
SELECT date(DateField) FROM Table; SELECT time(DateField) FROM Table; SELECT datetime(DateField) FROM Table;
If you want unix time (seconds since the epoch) you have to format the output.
SELECT strftime("%s",DateField) FROM Table;
However that will return the time in UTC which is probably not what you want (it's not what I wanted). I want it to compensate for my local timezone and thus you have to tell it to use your timezone.
SELECT strftime("%s",DateField,'localtime') FROM Table;

Related Posts:
Green Data: Pysqlite

Sources: Perturb.org , Sqlite Wiki
Tags: , ,

07 January 2006

PyFusker

Python implementation of Fusker Introduction: Most probably you are redirected from Wikipedia to this page, so please if you have any comment on the code just leave it here so that I can improve it. Also if you can help me know why are people interested in the fusker technology that much, and what web sites do you usually fusker.
The Python Code
#!/usr/bin/python
""" PyFusker """
""" Author: Tarek Amr """
""" Version: 0.1 """
""" File: pyfusker.py """
""" Date: 07 January 2006 """
""" Replce [TAB] with \t """
class Fusker:
[TAB]def __init__(self, url):
[TAB][TAB]self.url = url
[TAB][TAB]self.urls = []
[TAB][TAB]self._generate()
[TAB]def _generate(self):
[TAB][TAB]comp = re.compile("\\[.+\\]")
[TAB][TAB]x = comp.findall(self.url)
[TAB][TAB]if not x:
[TAB][TAB][TAB]print "Url parsing error!"
[TAB][TAB][TAB]sys.exit()
[TAB][TAB]try:
[TAB][TAB][TAB]x[0] = x[0].strip("[")
[TAB][TAB][TAB]x[0] = x[0].strip("]")
[TAB][TAB][TAB]x1,x2 = x[0].split("-")
[TAB][TAB][TAB]x1 = string.atoi(x1)
[TAB][TAB][TAB]x2 = string.atoi(x2)
[TAB][TAB]except:
[TAB][TAB][TAB]print "Url parsing error!"
[TAB][TAB][TAB]sys.exit()
[TAB][TAB]if x1 > x2:
[TAB][TAB][TAB]print "Invalid range"
[TAB][TAB][TAB]sys.exit()
[TAB][TAB]temp_url = comp.split(url)
[TAB][TAB]i = x1
[TAB][TAB]while i < x2 :
[TAB][TAB][TAB]self.urls.append(string.join(temp_url,"%s" % i))
[TAB][TAB][TAB]i = i + 1
[TAB][TAB]return self.urls
[TAB]def list_urls(self):
[TAB][TAB]print self.urls
[TAB]def download_urls(self):
[TAB][TAB]for u in self.urls:
[TAB][TAB][TAB]try:
[TAB][TAB][TAB][TAB]print "Downloading ... ", u
[TAB][TAB][TAB][TAB]os.system("wget %s" % u)
[TAB][TAB][TAB]except:
[TAB][TAB][TAB][TAB]print "Wget Error!"
[TAB][TAB][TAB][TAB]continue
if __name__ == "__main__":
[TAB]try:
[TAB][TAB]url = sys.argv[1]
[TAB]except:
[TAB][TAB]print "Usage: python fusker.py http://www.website.com/img[01-06].jpg"
[TAB][TAB]sys.exit()
[TAB]f = Fusker(url)
[TAB]f.download_urls()
Tags: , ,

Pyblish

It is hard to write programs source code on your own blog or webpage especially when writing a language like Python where tabs and white spaces do matter. However blogs are the best place to share your coding ideas and receive comments and bugs fixes on them. So one nice idea is to replace the tab or "\t" with [TAB], and since it is really hard to do it by hand this is a python proggie to replace them automatically.
''' Pyblish - Python Publisher '''
''' Author: Tarek Amr '''
''' Version: 0.1'''
''' File: pyblish.py'''
''' Date: 07 Jan 2006 '''
import string, sys
if __name__ == "__main__":
[TAB]try:
[TAB][TAB]filein = sys.argv[2]
[TAB][TAB]mode = sys.argv[1]
[TAB]except:
[TAB][TAB]print "Usage: python pyblish [ --decode | --encode ] INPUT_FILE_NAME"
[TAB][TAB]sys.exit()
[TAB]if mode == "--decode":
[TAB][TAB]temp = filein.split(".")
[TAB][TAB]temp[-1] = ".txt"
[TAB][TAB]fileout = string.join(temp)
[TAB]elif mode == "--encode":[TAB]
[TAB][TAB]temp = filein.split(".")
[TAB][TAB]temp[-1] = ".py"
[TAB][TAB]fileout = string.join(temp)
[TAB]else:
[TAB][TAB]print "Usage: python pyblish [ --decode | --encode ] INPUT_FILE_NAME"
[TAB][TAB]sys.exit()
[TAB]fdin = open(filein,"r")
[TAB]fdout = open(fileout,"w")
[TAB]for line in fdin.readlines():
[TAB][TAB]if mode == "--decode":
[TAB][TAB][TAB]line = line.replace("\t","[TAB]")
[TAB][TAB]elif mode == "--encode":
[TAB][TAB][TAB]line = line.replace("[TAB]","\t")
[TAB][TAB]fdout.write(line)
[TAB]fdin.close()
[TAB]fdout.close()
By the way this code has nothing to do with that web server and application framework hosted at sourceforge and called Pyblish too

Tags: , ,

23 December 2005

GMailRCS - Version 1.00

GmailRCS is a way to use your Gmail account as a lightweight Revision Control System (RCS) in order to backup and restore the different versions of your source code. The software is written in Python, using libgmail
GmailRCS: http://sourceforge.net/projects/gmailrcs/


Tags: , ,

16 December 2005

Python - libgmail Tutorial

This is a short tutorla about libgmail. Which is a Library to provide access to Gmail via Python. Tabs are important in python as they indicate the different code blocks, since they do not have "{" and "}" like those in C and C++. So I'll replace the tabs here with [TAB], since it's hard to write the proper format in HTML.

First of all lets see how can we get the libgmail help, a.k.a man pages:
>>>import libgmail
>>>help(libgmail)
Then lets see how can we retrieve the messages in our the inbox:
>>>import libgmail
>>>ga = libgmail.GmailAccount("username@gmail.com", "password")
>>>ga.login()
>>>folder = ga.getMessagesByFolder("inbox", True)
>>>for thread in folder:
>>>[TAB]print "Thread:", thread.id, "Subject:", thread.subject
>>>[TAB]for msg in thread:
>>>[TAB][TAB]print "Msg:", msg.id, ",Author", msg.author, ",Subject:", msg.subject
Now lets say we want to print all the attached files in all the messages labled by "projectx"
>>>import libgmail
>>>ga = libgmail.GmailAccount("username@gmail.com", "password")
>>>ga.login()
>>>folder = ga.getMessagesByLabel("projectx", True)
>>>for tread in folder:
>>>[TAB]for msg in thread:
>>>[TAB][TAB]for attach in msg.attachments:
>>>[TAB][TAB][TAB]print attach._getContent()
You may also send a message this way:
>>>import libgmail
>>>ga = libgmail.GmailAccount("username@gmail.com", "password")
>>>ga.login()
>>>msg=libgmail.GmailComposedMessage("friend@gmail.com", "SubjectHere", "BodyHere")
>>>ga.sendMessage(msg)
To send attachmented files into the message:
>>>import libgmail
>>>ga = libgmail.GmailAccount("username@gmail.com", "password")
>>>ga.login()
>>>myFiles = ["/file1", "/file2", "/file3"]
>>>msg=libgmail.GmailComposedMessage("friend@gmail.com", "SubjectHere", "BodyHere", filenames=myFiles)
>>>ga.sendMessage(msg)
Finally I've noticed that sometimes the sendMessage() function fails - returns "HTTP Error 404: Not Found", and hope that they are going fix it soon. Actually the function fails on the first time but when you call it again it works, so you may use a "try-except" statement like the one below:
>>>try:
>>>[TAB]ga.sendMessage(msg)
>>>except:
>>>[TAB]ga.sendMessage(msg)

Tags: , ,

04 December 2005

Del.icio.us Python Popular Links

Want to stay on the cutting edge of what’s hot in the Python community? This is the way to do it. The site tracks the most popular URLs tagged with Python, so you get a continuous feed of interesting and helpful links. I’ve added the RSS feed for the page as a Live Bookmark in Firefox, making it easy to skim the list. If you don’t already have a del.icio.us account, go get one now (although you don’t need one just to view other people’s links).

Source: Import This @ Think Hole Labs

Tags: , , ,

03 December 2005

Python Mobile Bluetooth Console

So, now you wanna write Python scripts on your phone, but you are sick of the phone keyboard. Then it is time for BTConsole (Bluetooth Console), where you can have a console connection to the Mobile Phone from your PC using the Bluetooth connection as a Serial Port Emulator. This can be done on both Windows or Linux, but I am going to describe the Linux part as I don't like Windows and also I failed to set it up on it. First of all you have to have the Bluetooth Protocol Stack (BlueZ) installed on your machine. You may also use an "ipconfig" or "ifconfig" like command on you Computer to get information about your Computer's Bluetooth Address (It looks like the MAC Address) and so ... this command is called "hciconfig" Also to discover the Bluetooth devices near you, use "hcitool scan" Now create a Virtual Port (/dev/rfcomm0) on your Linux Machine for the Bluetoot connection and start listening on that port ... Type the following two commands on you computer:
"sdptool add-channel=2 SP" (It shall tell you someting like "Serial Port service registered" now) "rfcomm listen /dev/rfcomm0 2" (It shall tell you something like "Waiting for connection on Channel2")
Then on you Mobile Phone, go to Python (You have Python for Series60 installed on your phone, don't you !?). And choose Bluetooth Console from the Options menu. It should connect to the computer now. And the following will be shown on you computer "Connection from AA:BB:CC:DD:EE:FF to /dev/rfcomm0" then "Press CTRL-C for hangup", where AA:BB:CC:DD:EE:FF is your Mobile's Bluetoot Address The Linux equivalent to HyperTerminal is called minicom, so it's time to use it to open a console connection to the mobile phone. To run minicom type "minicom -s -m" then choose "Serial Port Setup" and set the Serial Device to "/dev/rfcomm0" and leave the rest as it is. Now press escape and exit the Serial Port Setup Menu. Here we go, you are now connected to the Python Shell on your Mobile Phone. If you'd like you may use this to send an SMS from your PC:
>>> import messaging
>>> messaging.sms_send("+20101234567",u"Hello World")
Where +20101234567 is the phone number you want to send your SMS to. Resources:
By the way if this doesn't work, try the following howto by Dankoozy: HOWTO: Use the Bluetooth console in PyS60

Tags: , , , , ,