Commit 54d4f6dd authored by Austin Clements's avatar Austin Clements
Browse files

These are the dslice libraries from Planetlab's SF repository. They

are necessary to run the Planetlab manager.
parent e6ce08a1
#! /usr/bin/env python
"Provide some supporting classes to simplify Input Forms with HTMLgen"
#'$Id: Formtools.py,v 1.1 2003-08-19 17:17:07 aclement Exp $'
# COPYRIGHT (C) 1999 ROBIN FRIEDRICH email: Robin.Friedrich@pdq.net
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and
# that both that copyright notice and this permission notice appear in
# supporting documentation.
# THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
# SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
from HTMLgen import *
from HTMLcolors import *
import string
class InputTable:
"""InputTable(entries, [keyword=value]...)
Entries is a list of 2 or 3-element tuples (name, input_object, note) where
name will label the input object on the left column, the input_object
can be anything, and the note is a string to provide optional notations
to the right of the input widgets.
"""
def __init__(self, entries=None, **kw):
self.entries = []
self.leftcolor = GREY2 #color used for left label column
self.centercolor = WHITE #color used for center input column
self.rightcolor = WHITE #color used for right label column
self.notecolor = RED #color used for notation text
self.leftalign = 'right' #text alignment for left label column
self.defaultsize = 20
if entries is not None:
for entry in entries:
self.append(entry)
for item in kw.keys():
if self.__dict__.has_key(item):
self.__dict__[item] = kw[item]
else:
detail = "%s not a valid parameter of the %s class." % (item, self.__class__)
raise KeyError, detail
def append(self, *items):
for item in items:
li = len(item)
if li == 1:
self.entries.append((item[0], Input(name=item[0], size=self.defaultsize), ''))
elif li == 2:
self.entries.append((item[0], item[1], ''))
elif li == 3:
self.entries.append((item[0], item[1], item[2]))
else:
raise ValueError('Appended item must be a sequence of 1, 2, or 3 elements')
def __str__(self):
table = TableLite(border=0, cellspacing=4)
for label, input, note in self.entries:
row = TR()
row.append(TD(label, align=self.leftalign, bgcolor=self.leftcolor))
row.append(TD(input, bgcolor=self.centercolor))
if note:
row.append(TD(Font(note, color=self.notecolor),
bgcolor=self.rightcolor))
table.append(row)
return str(table)
class RadioButtons:
"""RadioButtons(itemlist, keyword=value):
"""
widgettype = 'radio'
def __init__(self, items, **kw):
self.items = items
self.name = 'choice'
self.orient = 'vertical'
self.selected = []
for (item, value) in kw.items():
setattr(self, item, value)
def __str__(self):
if self.orient[0] == 'v':
sep = '<BR>\n'
else:
sep = ', \n'
if type(self.selected) is type(""):
self.selected = [self.selected]
s = []
for item in self.items:
if item in self.selected:
s.append(str(Input(type=self.widgettype, name=self.name, checked=1)))
else:
s.append(str(Input(type=self.widgettype, name=self.name)))
s.append(str(item))
s.append(sep)
return string.join(s[:-1], "")
class CheckBoxes(RadioButtons):
widgettype = 'checkbox'
def test1():
doc = SimpleDocument(title='Income Survey', bgcolor=WHITE) # if this in a CGI prog use cgi=1
F = Form('http://www.kettleman.edu/cgi-bin/income-survey.py') # the URL of the CGI program
survey = []
survey.append(['City', Input(name='city', size=30), 'Required'])
survey.append(['State', Input(name='state', size=20), 'Required'])
survey.append(['Sex', RadioButtons(['Male', 'Female', 'Other']), ''] )
incomes = [('$0 - $10K', 0), ('$10K - $25K', 1), ('$25K - $40K', 2), ('$40K +', 3)]
survey.append(['Income', Select(incomes, name='income', size=1), 'Required'] )
F.append(InputTable(survey))
doc.append(F)
doc.write('survey.html')
def test2():
doc = SimpleDocument(title='YourDorm Pizza Delivery', bgcolor=WHITE)
form = Form()
stuff = ['Extra Cheese', 'Pepperoni', 'Sausage', 'Mushrooms',
'Peppers', 'Onions', 'Olives']
sizes = ['Small', 'Medium', 'Large', 'Extra Large']
tab = ( ('Name', Input(name='Name',size=30)),
('Dorm', Input(name='Dorm',size=30)),
('Room', Input(name='Room',size=5)),
('Size', RadioButtons(sizes, name='size', selected='Large')),
('Toppings', CheckBoxes(stuff, name='toppings',orient='horiz'))
)
form.append(InputTable(tab))
doc.append(form)
doc.write('test.html')
def test():
doc = SimpleDocument(bgcolor=WHITE)
form = Form()
doc.append(form)
stuff = []
names = ( ('Name', 'Required'),
('Street1', 'Required'),
('Street2', ''),
('City', 'Required'),
('State/Province', 'Required'),
('Postal Code', 'Required'),
('Country', ''),
('Phone', '') )
for (name, note) in names:
stuff.append( [name, Input(name=name, size=30), note] )
form.append(InputTable(stuff, rightcolor=GREY2))
doc.write('test.html')
#
# The Python Imaging Library.
# $Id: GifImagePluginH.py,v 1.1 2003-08-19 17:17:07 aclement Exp $
#
# GIF file handling
#
# History:
# 95-09-01 fl Created
# 96-12-14 fl Added interlace support
# 96-12-30 fl Added animation support
# 97-01-05 fl Added write support, fixed local colour map bug
# 97-02-23 fl Make sure to load raster data in getdata()
# 97-07-05 fl Support external decoder
#
# Copyright (c) Secret Labs AB 1997.
# Copyright (c) Fredrik Lundh 1995-97.
#
# See the README file for information on usage and redistribution.
#
__version__ = "0.4"
import array
import ImageH, ImageFileH, ImagePaletteH
# --------------------------------------------------------------------
# Helpers
def i16(c):
return ord(c[0]) + (ord(c[1])<<8)
def o16(i):
return chr(i&255) + chr(i>>8&255)
# --------------------------------------------------------------------
# Identify/read GIF files
def _accept(prefix):
return prefix[:6] in ["GIF87a", "GIF89a"]
class GifImageFile(ImageFileH.ImageFile):
format = "GIF"
format_description = "Compuserve GIF"
def data(self):
s = self.fp.read(1)
if s and ord(s):
return self.fp.read(ord(s))
return None
def _open(self):
# Screen
s = self.fp.read(13)
if s[:6] not in ["GIF87a", "GIF89a"]:
raise SyntaxError, "not a GIF file"
self.info["version"] = s[:6]
self.size = i16(s[6:]), i16(s[8:])
self.tile = []
flags = ord(s[10])
bits = (flags & 7) + 1
if flags & 128:
# get global palette
self.info["background"] = ord(s[11])
self.global_palette = self.palette =\
ImagePaletteH.raw("RGB", self.fp.read(3<<bits))
self.fp2 = self.fp # FIXME: hack
self.offset = 0
self.dispose = None
self.frame = -1
self.seek(0) # get ready to read first frame
def seek(self, frame):
# FIXME: can only seek to next frame; should add rewind capability
if frame != self.frame + 1:
raise ValueError, "cannot seek to frame %d" % frame
self.frame = frame
self.tile = []
self.fp = self.fp2 # FIXME: hack
if self.offset:
# backup to last frame
self.fp.seek(self.offset)
while self.data():
pass
self.offset = 0
if self.dispose:
self.im = self.dispose
self.dispose = None
self.palette = self.global_palette
while 1:
s = self.fp.read(1)
if not s or s == ";":
break
elif s == "!":
#
# extensions
#
s = self.fp.read(1)
block = self.data()
if ord(s) == 249:
#
# graphic control extension
#
flags = ord(block[0])
if flags & 1:
self.info["transparency"] = ord(block[3])
self.info["duration"] = i16(block[1:3]) * 10
try:
# disposal methods
if flags & 8:
# replace with background colour
self.dispose = ImageH.core.fill("P", self.size,
self.info["background"])
elif flags & 16:
# replace with previous contents
self.dispose = self.im.copy()
except (AttributeError, KeyError):
pass
elif ord(s) == 255:
#
# application extension
#
self.info["extension"] = block, self.fp.tell()
if block[:11] == "NETSCAPE2.0":
self.info["loop"] = 1 # FIXME
while self.data():
pass
elif s == ",":
#
# local image
#
s = self.fp.read(9)
# extent
x0, y0 = i16(s[0:]), i16(s[2:])
x1, y1 = x0 + i16(s[4:]), y0 + i16(s[6:])
flags = ord(s[8])
interlace = (flags & 64) != 0
if flags & 128:
bits = (flags & 7) + 1
self.palette =\
ImagePaletteH.raw("RGB", self.fp.read(3<<bits))
# image data
bits = ord(self.fp.read(1))
self.offset = self.fp.tell()
self.tile = [("gif",
(x0, y0, x1, y1),
self.offset,
(bits, interlace))]
break
else:
pass
# raise IOError, "illegal GIF tag `%x`" % ord(s)
if not self.tile:
self.fp2 = None
raise EOFError, "no more images in GIF file"
self.mode = "L"
if self.palette:
self.mode = "P"
def tell(self):
return self.frame
# --------------------------------------------------------------------
# Write GIF files
try:
import _imaging_gif
except ImportError:
_imaging_gif = None
RAWMODE = {
"1": "L",
"L": "L",
"P": "P",
}
def _save(im, fp, filename):
if _imaging_gif:
# call external driver
try:
_imaging_gif.save(im, fp, filename)
return
except IOError:
pass # write uncompressed file
# header
for s in getheader(im):
fp.write(s)
# local image header
fp.write("," +
o16(0) + o16(0) + # bounding box
o16(im.size[0]) + # size
o16(im.size[1]) +
chr(0) + # flags
chr(8)) # bits
ImageFileH._save(im, fp, [("gif", (0,0)+im.size, 0, RAWMODE[im.mode])])
fp.write("\0") # end of image data
fp.write(";") # end of file
try:
fp.flush()
except: pass
def _save_netpbm(im, fp, filename):
#
# If you need real GIF compression and/or RGB quantization, you
# can use the external NETPBM/PBMPLUS utilities. See comments
# below for information on how to enable this.
import os
file = im._dump()
if im.mode != "RGB":
os.system("ppmtogif %s >%s" % (file, filename))
else:
os.system("ppmquant 256 %s | ppmtogif >%s" % (file, filename))
try: os.unlink(file)
except: pass
# --------------------------------------------------------------------
# GIF utilities
def getheader(im):
"""Return a list of strings representing a GIF header"""
try:
rawmode = RAWMODE[im.mode]
except KeyError:
raise IOError, "cannot save mode %s as GIF" % im.mode
s = [
"GIF87a" + # magic
o16(im.size[0]) + # size
o16(im.size[1]) +
chr(7 + 128) + # flags: bits + palette
chr(0) + # background
chr(0) # reserved/aspect
]
# global palette
if im.mode == "P":
# colour palette
s.append(im.im.getpalette("RGB"))
else:
# greyscale
for i in range(256):
s.append(chr(i) * 3)
return s
def getdata(im, offset = (0, 0), **params):
"""Return a list of strings representing this image.
The first string is a local image header, the rest contains
encoded image data."""
class collector:
data = []
def write(self, data):
self.data.append(data)
im.load() # make sure raster data is available
fp = collector()
try:
im.encoderinfo = params
# local image header
fp.write("," +
o16(offset[0]) + # offset
o16(offset[1]) +
o16(im.size[0]) + # size
o16(im.size[1]) +
chr(0) + # flags
chr(8)) # bits
ImageFileH._save(im, fp, [("gif", (0,0)+im.size, 0, RAWMODE[im.mode])])
fp.write("\0") # end of image data
finally:
del im.encoderinfo
return fp.data
# --------------------------------------------------------------------
# Registry
ImageH.register_open(GifImageFile.format, GifImageFile, _accept)
ImageH.register_save(GifImageFile.format, _save)
ImageH.register_extension(GifImageFile.format, ".gif")
ImageH.register_mime(GifImageFile.format, "image/gif")
#
# Uncomment the following line if you wish to use NETPBM/PBMPLUS
# instead of the built-in "uncompressed" GIF encoder
# Image.register_save(GifImageFile.format, _save_netpbm)
#!/usr/bin/env python
# COPYRIGHT (C) 1997 ROBIN FRIEDRICH
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this permission notice appear in
# supporting documentation.
# THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
# EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR
# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
# USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
"""Generate HTML calendars
This module reads a text file containing appointment information and
generates web pages containing those scheduled appointments in a
nicely formatted linear table for each month."""
import string, time
from HTMLcolors import *
from HTMLgen import SimpleDocument, TableLite, TD, TR, Font, Name, H, Center, Href
from types import IntType
from calendar import day_name, month_name, mdays, weekday
__version__ = '$Id: HTMLcalendar.py,v 1.1 2003-08-19 17:17:07 aclement Exp $'
__author__ = 'Robin Friedrich'
__date__ = '10/13/97'
# Constants
day_month_order = 0 # set to 1 to parse day/month ordering (europe)
# set to 0 to parse month/day ordering (usa)
DateError = 'date error'
PAGECOLOR = PEACH
WEEKDAYCOLOR = GRAY1
WEEKENDCOLOR = GREEN3
TIMECOLOR = BLUE
SOURCETEXTFILE = 'appt.txt'
HTMLSUFFIX = 'html' # use htm if you must
def main():
"""Main routine to drive script and serve as usage example.
"""
parsed_appts = read_appt_file(SOURCETEXTFILE)
current_year = Year()
current_year.load_appointments(parsed_appts)
current_year.write('./', 'Calendar')
class Appointment:
"""Represent an appointment entry.
"""
def __init__(self, hr='9', min='00', text='Nothing'):
self.hr = hr
self.min = min
self.text = text
def __str__(self):
return "%s %s" % (Font(self.hr +':'+ self.min,
size = -1, color = TIMECOLOR),
Font(self.text, size = -1))
class Day:
"""Represent a day record.
Appointment instances are appended to instances of this class.
"""
def __init__(self, year=1997, month=1, day=1):
self.weekday = day_name[weekday(year,month,day)]
self.year = `year`
self.month = `month`
self.day = `day`
self.appointments = []
def append(self, appt):
self.appointments.append(appt)
def repr_date_cell(self):
return '%s %s' % (self.weekday,
Name(self.month +'-'+self.day, self.day))
def repr_appt_cell(self):
strlist = map(str, self.appointments)
return string.join(strlist, '<BR>')
def make_row(self):
if self.weekday in ('Saturday','Sunday'):
row = TR(bgcolor=WEEKENDCOLOR)
else:
row = TR(bgcolor=WEEKDAYCOLOR)
row.append(TD(self.repr_date_cell(), align='right',html_escape='off'))
row.append(TD(self.repr_appt_cell(),html_escape='off'))
return row
def __str__(self):
return str(self.make_row())
class DateTable( TableLite ):
"""Table of days used to represent the month in HTML.
Adds methods allowing direct indexing by day of month.