HTML, CSS and Tables: The Beauty of Data: "Our CSS:
table {
border:1px solid #000;
border-collapse:collapse;
font-family:arial,sans-serif;
font-size:80%;
}
td,th{
border:1px solid #000;
border-collapse:collapse;
padding:5px;
}
#fn,#dp,#ar{width:58px;}
#fr,#to{width:138px;}
caption{
background:#ccc;
font-size:140%;
border:1px solid #000;
border-bottom:none;
padding:5px;
text-align:left;
}
thead th{
background:#9cf;
text-align:left;
}
tbody th{
text-align:left;
background:#69c;
}
tfoot td{
text-align:right;
font-weight:bold;
background:#369;
}
tbody td{
background:#999;
}
tbody tr.odd td{
background:#ccc;
}
However, to ensure that our lines meet, we need to set the cellspacing attribute in our HTML to 0, and cellspacing is a deprecated attribute for XHTML.
For XHTML documents we can use the border-collapse selector in the CSS to achieve the effect.
Lets take a look, shall we?
Our markup:
<table summary='This table lists all the flights by XYZ Air leaving London today.'>
<caption>Flight Schedule</caption>
<thead>
<tr>
<th id='fn' scope='col'>Flight Number:</th>
<th id='fr' scope='col'>From:</th>
<th id='to' scope='col'>To:</th>
<th id='dp' scope='col'>Departure:</th>
<th id='ar' scope='col'>Arrival:</th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan='5'>Total: 3 flights</td>
</tr>
</tfoot>
<tbody>
<tr>
<th scope='row'>BA 3451</th>
<td>Heathrow</td>
<td>Nuremberg</td>
<td>19:20</td>
<td>19:50</td>
</tr>
<tr class='odd'>
<th scope='row'>BA 1254</th>
<td>Luton</td>
<td>Alicante</td>
<td>19:40</td>
<td>20:50</td>
</tr>
<tr>
<th scope='row'>LH 331</th>
<td>Heathrow</td>
<td>Hamburg</td>
<td>20:00</td>
<td>20:20</td>
</tr>
</tbody>
</table>"
Sunday, December 28, 2008
Wednesday, December 24, 2008
Read or Write Dictionary to/from File - Python
import pprint
d = {'name': 'Sakthi', 'Age': 25, 'Address':{'Door No':'5/20','Street':'Nehru Street','City':'Chennai','Pincode':'33223242'}}
# Write Dictionary into File
f = open("C:\dictData.txt","w")
print >> f, d
f.close()
# Read Dictionary from File
f=open('C:\dictData.txt','r')
d=f.readlines()[0]
d=eval(d)
print "Name : ",d.get("name")
f.close()
# Write Formatted Dictionary into File
f = open("C:\dictData.txt","w")
pp = pprint.PrettyPrinter(width=2,stream=f)
pp.pprint(d)
f.close()
d = {'name': 'Sakthi', 'Age': 25, 'Address':{'Door No':'5/20','Street':'Nehru Street','City':'Chennai','Pincode':'33223242'}}
# Write Dictionary into File
f = open("C:\dictData.txt","w")
print >> f, d
f.close()
# Read Dictionary from File
f=open('C:\dictData.txt','r')
d=f.readlines()[0]
d=eval(d)
print "Name : ",d.get("name")
f.close()
# Write Formatted Dictionary into File
f = open("C:\dictData.txt","w")
pp = pprint.PrettyPrinter(width=2,stream=f)
pp.pprint(d)
f.close()
Monday, December 22, 2008
Send HTML Mail From Python « ActiveState Code
Send HTML Mail From Python « ActiveState Code: "def createhtmlmail (html, text, subject): '''Create a mime-message that will render HTML in popular MUAs, text in better ones''' import MimeWriter import mimetools import cStringIO out = cStringIO.StringIO() # output buffer for our message htmlin = cStringIO.StringIO(html) txtin = cStringIO.StringIO(text) writer = MimeWriter.MimeWriter(out) # # set up some basic headers... we put subject here # because smtplib.sendmail expects it to be in the # message body # writer.addheader('Subject', subject) writer.addheader('MIME-Version', '1.0') # # start the multipart section of the message # multipart/alternative seems to work better # on some MUAs than multipart/mixed # writer.startmultipartbody('alternative') writer.flushheaders() # # the plain text section # subpart = writer.nextpart() subpart.addheader('Content-Transfer-Encoding', 'quoted-printable') pout = subpart.startbody('text/plain', [('charset', 'us-ascii')]) mimetools.encode(txtin, pout, 'quoted-printable') txtin.close() # # start the html subpart of the message # subpart = writer.nextpart() subpart.addheader('Content-Transfer-Encoding', 'quoted-printable') # # returns us a file-ish object we can write to # pout = subpart.startbody('text/html', [('charset', 'us-ascii')]) mimetools.encode(htmlin, pout, 'quoted-printable') htmlin.close() # # Now that we're done, close our writer and # return the message body # writer.lastpart() msg = out.getvalue() out.close() print msg return msg if __name__=='__main__': import smtplib f = open('newsletter.html', 'r') html = f.read() f.close() f = open('newsletter.txt', 'r') text = f.read() subject = 'Today's Newsletter!' message = createhtmlmail(html, text, subject) server = smtplib.SMTP('localhost') server.sendmail('agillesp@i-noSPAMSUCKS.com', 'agillesp@i-noSPAMSUCKS.com', message) server.quit()"
Saturday, December 20, 2008
Python Programming on Win32: Chapter 12 Advanced Python and COM
Python Programming on Win32: Chapter 12 Advanced Python and COM: " Getting name of the local machine:
import win32api
win32api.GetComputerName() # Output: SYS10
import win32api
win32api.GetComputerName() # Output: SYS10
Thursday, December 18, 2008
Nabble - Python - python-list - How to get current module object
Nabble - Python - python-list - How to get current module object: "
C:\junk>type whoami.py
def showme():
import sys
modname = globals()['__name__']
print repr(modname)
module = sys.modules[modname]
print repr(module)
print dir(module)
C:\junk>python
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
Type 'help', 'copyright', 'credits' or 'license' for more information.
>>> import whoami
>>> whoami.showme()
'whoami'
<module 'whoami' from 'whoami.py'>
['__builtins__', '__doc__', '__file__', '__name__', 'showme']"
C:\junk>type whoami.py
def showme():
import sys
modname = globals()['__name__']
print repr(modname)
module = sys.modules[modname]
print repr(module)
print dir(module)
C:\junk>python
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
(Intel)] on win32
Type 'help', 'copyright', 'credits' or 'license' for more information.
>>> import whoami
>>> whoami.showme()
'whoami'
<module 'whoami' from 'whoami.py'>
['__builtins__', '__doc__', '__file__', '__name__', 'showme']"
Python GMail SMTP Example « Code Comments
Python GMail SMTP Example « Code Comments: "Python GMail SMTP Example
I need to be able to send an email from my python script, and I wanted to be able to use my GMail for the outgoing SMTP server. It becomes a little tricky because the GMail servers require authentication. I searched around and found some good examples on the Internet and then fine tuned them a bit.
import os
import smtplib
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.MIMEAudio import MIMEAudio
from email.MIMEImage import MIMEImage
from email.Encoders import encode_base64
def sendMail(subject, text, *attachmentFilePaths):
gmailUser = ‘yo.mama@gmail.com’
gmailPassword = ‘bogus!’
recipient = ‘test@test.com’
msg = MIMEMultipart()
msg['From'] = gmailUser
msg['To'] = recipient
msg['Subject'] = subject
msg.attach(MIMEText(text))
for attachmentFilePath in attachmentFilePaths:
msg.attach(getAttachment(attachmentFilePath))
mailServer = smtplib.SMTP(’smtp.gmail.com’, 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmailUser, gmailPassword)
mailServer.sendmail(gmailUser, recipient, msg.as_string())
mailServer.close()
print(’Sent email to %s’ % recipient)
def getAttachment(attachmentFilePath):
contentType, encoding = mimetypes.guess_type(attachmentFilePath)
if contentType is None or encoding is not None:
contentType = ‘application/octet-stream’
mainType, subType = contentType.split(’/', 1)
file = open(attachmentFilePath, ‘rb’)
if mainType == ‘text’:
attachment = MIMEText(file.read())
elif mainType == ‘message’:
attachment = email.message_from_file(file)
elif mainType == ‘image’:
attachment = MIMEImage(file.read(),_subType=subType)
elif mainType == ‘audio’:
attachment = MIMEAudio(file.read(),_subType=subType)
else:
attachment = MIMEBase(mainType, subType)
attachment.set_payload(file.read())
encode_base64(attachment)
file.close()
attachment.add_header(’Content-Disposition’, ‘attachment’, filename=os.path.basename(attachmentFilePath))
return attachment
Derived from: http://kutuma.blogspot.com/2007/08/sending-emails-via-gmail-with-python.html and http://mail.python.org/pipermail/python-list/2003-September/225540.html"
I need to be able to send an email from my python script, and I wanted to be able to use my GMail for the outgoing SMTP server. It becomes a little tricky because the GMail servers require authentication. I searched around and found some good examples on the Internet and then fine tuned them a bit.
import os
import smtplib
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.MIMEAudio import MIMEAudio
from email.MIMEImage import MIMEImage
from email.Encoders import encode_base64
def sendMail(subject, text, *attachmentFilePaths):
gmailUser = ‘yo.mama@gmail.com’
gmailPassword = ‘bogus!’
recipient = ‘test@test.com’
msg = MIMEMultipart()
msg['From'] = gmailUser
msg['To'] = recipient
msg['Subject'] = subject
msg.attach(MIMEText(text))
for attachmentFilePath in attachmentFilePaths:
msg.attach(getAttachment(attachmentFilePath))
mailServer = smtplib.SMTP(’smtp.gmail.com’, 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmailUser, gmailPassword)
mailServer.sendmail(gmailUser, recipient, msg.as_string())
mailServer.close()
print(’Sent email to %s’ % recipient)
def getAttachment(attachmentFilePath):
contentType, encoding = mimetypes.guess_type(attachmentFilePath)
if contentType is None or encoding is not None:
contentType = ‘application/octet-stream’
mainType, subType = contentType.split(’/', 1)
file = open(attachmentFilePath, ‘rb’)
if mainType == ‘text’:
attachment = MIMEText(file.read())
elif mainType == ‘message’:
attachment = email.message_from_file(file)
elif mainType == ‘image’:
attachment = MIMEImage(file.read(),_subType=subType)
elif mainType == ‘audio’:
attachment = MIMEAudio(file.read(),_subType=subType)
else:
attachment = MIMEBase(mainType, subType)
attachment.set_payload(file.read())
encode_base64(attachment)
file.close()
attachment.add_header(’Content-Disposition’, ‘attachment’, filename=os.path.basename(attachmentFilePath))
return attachment
Derived from: http://kutuma.blogspot.com/2007/08/sending-emails-via-gmail-with-python.html and http://mail.python.org/pipermail/python-list/2003-September/225540.html"
Python and Excel
Python and Excel: "Integrating Python and MS Excel
Basic example
# this example starts Excel, creates a new workbook,
# puts some text in the first and second cell
# closes the workbook without saving the changes
# and closes Excel. This happens really fast, so
# you may want to comment out some lines and add them
# back in one at a time ... or do the commands interactively
from win32com.client import Dispatch
xlApp = Dispatch('Excel.Application')
xlApp.Visible = 1
xlApp.Workbooks.Add()
xlApp.ActiveSheet.Cells(1,1).Value = 'Python Rules!'
xlApp.ActiveWorkbook.ActiveSheet.Cells(1,2).Value = 'Python Rules 2!'
xlApp.ActiveWorkbook.Close(SaveChanges=0) # see note 1
xlApp.Quit()
xlApp.Visible = 0 # see note 2
del xlApp
# raw_input('press Enter ...')
Notes
1. I changed xlApp.Close(SaveChanges=0) to xlApp.ActiveWorkbook.Close(SaveChanges=0), because I was advised that the former didn't work.
2. On 14-Feb-2006, Stef Cruz informed me: 'I find that you must make x1App.Visible=0 before you use del x1App, otherwise EXCEL.EXE remains in memory. Try out the code again with Task Manager running, you'll see what I mean.'"
Basic example
# this example starts Excel, creates a new workbook,
# puts some text in the first and second cell
# closes the workbook without saving the changes
# and closes Excel. This happens really fast, so
# you may want to comment out some lines and add them
# back in one at a time ... or do the commands interactively
from win32com.client import Dispatch
xlApp = Dispatch('Excel.Application')
xlApp.Visible = 1
xlApp.Workbooks.Add()
xlApp.ActiveSheet.Cells(1,1).Value = 'Python Rules!'
xlApp.ActiveWorkbook.ActiveSheet.Cells(1,2).Value = 'Python Rules 2!'
xlApp.ActiveWorkbook.Close(SaveChanges=0) # see note 1
xlApp.Quit()
xlApp.Visible = 0 # see note 2
del xlApp
# raw_input('press Enter ...')
Notes
1. I changed xlApp.Close(SaveChanges=0) to xlApp.ActiveWorkbook.Close(SaveChanges=0), because I was advised that the former didn't work.
2. On 14-Feb-2006, Stef Cruz informed me: 'I find that you must make x1App.Visible=0 before you use del x1App, otherwise EXCEL.EXE remains in memory. Try out the code again with Task Manager running, you'll see what I mean.'"
Writing TO Excel file - Python
Writing TO Excel file - Python: Writing TO Excel file
from win32com.client import Dispatch
import os
#file path
file_name = 'D:\\dev\\PyWork\\ExcelWrite\\SensiTest.xls'
#The win32com function to open Excel
excel = Dispatch('Excel.Application')
excel.Visible = True #If we want to see it change, it's fun
#Open the file we want in Excel
workbook = excel.Workbooks.Open(file_name)
#Extract some of the file's components we may need
workBook = excel.ActiveWorkbook
activeSheet = excel.ActiveSheet
sheets = workBook.Sheets
#Add another sheet for example
sheets.Add(None, sheets('Sheet3')).Name = 'MySheetx'
#Activate the necessary sheet, assuming we know it exists,
#didn't put in the test for that, just verify its exitance in 'sheets'...
sheet = sheets('The_Sheet_I_Need')
sheet.Activate()
#Write smth in a Cell
line = 4
col = 5
sheet.Cells(line,col).Value = 99
#Read something is just as easy
print sheet.Cells(line,col).Value
#The remove doesn't work for me, but I simply save as different file...
#I just put the lines for you to see what I had found...
#if os.path.exists(file_name):
#os.remove(file_name)
workBook.SaveAs('D:\\dev\\PyWork\\ExcelWrite\\SensiTest_modif.xls')#change name
#The end...
workBook.Saved = 0 #p.248 Using VBA 5
workBook.Close(SaveChanges=0) #to avoid prompt
excel.Quit()
excel.Visible = 0
#must make Visible=0 before del self.excelapp or EXCEL.EXE remains in memory.
del excel
from win32com.client import Dispatch
import os
#file path
file_name = 'D:\\dev\\PyWork\\ExcelWrite\\SensiTest.xls'
#The win32com function to open Excel
excel = Dispatch('Excel.Application')
excel.Visible = True #If we want to see it change, it's fun
#Open the file we want in Excel
workbook = excel.Workbooks.Open(file_name)
#Extract some of the file's components we may need
workBook = excel.ActiveWorkbook
activeSheet = excel.ActiveSheet
sheets = workBook.Sheets
#Add another sheet for example
sheets.Add(None, sheets('Sheet3')).Name = 'MySheetx'
#Activate the necessary sheet, assuming we know it exists,
#didn't put in the test for that, just verify its exitance in 'sheets'...
sheet = sheets('The_Sheet_I_Need')
sheet.Activate()
#Write smth in a Cell
line = 4
col = 5
sheet.Cells(line,col).Value = 99
#Read something is just as easy
print sheet.Cells(line,col).Value
#The remove doesn't work for me, but I simply save as different file...
#I just put the lines for you to see what I had found...
#if os.path.exists(file_name):
#os.remove(file_name)
workBook.SaveAs('D:\\dev\\PyWork\\ExcelWrite\\SensiTest_modif.xls')#change name
#The end...
workBook.Saved = 0 #p.248 Using VBA 5
workBook.Close(SaveChanges=0) #to avoid prompt
excel.Quit()
excel.Visible = 0
#must make Visible=0 before del self.excelapp or EXCEL.EXE remains in memory.
del excel
Wednesday, December 10, 2008
HTML-Graphs Example
HTML-Graphs Example: "This is an example page for HTML-Graphs. Click 'Create Graph' and see how the graph looks different each time you change the form fields:
Graph Type:
Show Values:
Values (comma-separated):
Labels (comma-separated):
Bars Width:
Bars Length Ratio (0.1 - 2.9):
Labels Font Size:
Values Font Size:
Percentage Font Size:
Graph Padding:
Graph BG Color:
Graph Border:
Bars Color:
Bars BG Color:
Bars Border:
Labels Color:
Labels BG Color:
Labels Border:
Values Color:
Values BG Color:
Values Border:
Graph
Horses 123
4%
Dogs 456
14%
Cats 789
24%
Birds 987
30%
Pigs 654
20%
Cows 321
10%
Code"
Graph Type:
Show Values:
Values (comma-separated):
Labels (comma-separated):
Bars Width:
Bars Length Ratio (0.1 - 2.9):
Labels Font Size:
Values Font Size:
Percentage Font Size:
Graph Padding:
Graph BG Color:
Graph Border:
Bars Color:
Bars BG Color:
Bars Border:
Labels Color:
Labels BG Color:
Labels Border:
Values Color:
Values BG Color:
Values Border:
Graph
Horses 123
4%
Dogs 456
14%
Cats 789
24%
Birds 987
30%
Pigs 654
20%
Cows 321
10%
Code"