rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
a = abs(valueMax) valueMax = valueMax + a valueMin = valueMin - a
if valueMax>0: valueMax = 1.2*valueMax valueMin = 0.0 else: valueMax = 0.0 valueMin = 1.2*valueMin
def _setRange(self, dataSeries): """Set minimum and maximum axis values.
dir = dir and os.path.join(_archive,dir.replace('/',os.sep)) or _archive
dir = (dir=='.' or not dir) and _archive or os.path.join(_archive,dir.replace('/',os.sep))
def rl_get_module(name,dir): if sys.modules.has_key(name): om = sys.modules[name] del sys.modules[name] else: om = None try: f = None try: f, p, desc= imp.find_module(name,[dir]) return imp.load_module(name,f,p,desc) except: if isCompactDistro(): #attempt a load from inside the zip archive import zipimport dir = _startswith_rl(dir) dir = dir and os.path.join(_archive,dir.replace('/',os.sep)) or _archive zi = zipimport.zipimporter(dir) return zi.load_module(name) raise ImportError('%s[%s]' % (name,dir)) finally: if om: sys.modules[name] = om del om if f: f.close()
__namedColors = None
_namedColors = None
def colorDistance(col1, col2): """Returns a number between 0 and root(3) stating how similar two colours are - distance in r,g,b, space. Only used to find names for things.""" return math.sqrt( (col1.red - col2.red)**2 + (col1.green - col2.green)**2 + (col1.blue - col2.blue)**2 )
if __namedColors is not None: return __namedColors
global _namedColors if _namedColors is not None: return _namedColors
def getAllNamedColors(): #returns a dictionary of all the named ones in the module # uses a singleton for efficiency if __namedColors is not None: return __namedColors import colors __namedColors = {} for (name, value) in colors.__dict__.items(): if isinstance(value, Color): __namedColors[name] = value return __namedColors
__namedColors = {}
_namedColors = {}
def getAllNamedColors(): #returns a dictionary of all the named ones in the module # uses a singleton for efficiency if __namedColors is not None: return __namedColors import colors __namedColors = {} for (name, value) in colors.__dict__.items(): if isinstance(value, Color): __namedColors[name] = value return __namedColors
__namedColors[name] = value return __namedColors
_namedColors[name] = value return _namedColors
def getAllNamedColors(): #returns a dictionary of all the named ones in the module # uses a singleton for efficiency if __namedColors is not None: return __namedColors import colors __namedColors = {} for (name, value) in colors.__dict__.items(): if isinstance(value, Color): __namedColors[name] = value return __namedColors
map = aClass._attrMap.items() map.sort()
map = aClass._attrMap if map: map = map.items() map.sort() else: map = []
def beginAttributes(self, aClass): "Append a list of annotated attributes of a class."
print 'wrap', aW, aH, W, H
def wrap(self, aW, aH): W = 0 H = 0 F = self._flowables for f in F: w,h = f.wrap(aW,0xfffffff) if f is not F[0]: h = h + f.getSpaceBefore() if f is not F[-1]: h = h + f.getSpaceAfter() W = max(W,w) H = H+h print 'wrap', aW, aH, W, H self._CPage = H>aH return W, 0xffffff # force a split
print 'wrap', aW, aH, self._CPage
def split(self, aW, aH): print 'wrap', aW, aH, self._CPage S = self._CPage and [CondPageBreak(aH+1)] or [] for f in self._flowables: S.append(f) return S
self.streamContent = string.join(imagedata[2:-1],'')
self.streamContent = string.join(imagedata[3:-1],'')
def loadImageFromA85(self,source): IMG=[] imagedata = map(string.strip,pdfutils.cacheImageFile(source,returnInMemory=1,IMG=IMG)) words = string.split(imagedata[1]) self.width, self.height = map(string.atoi,(words[1],words[3])) self.colorSpace = 'DeviceRGB' self.bitsPerComponent = 8 self._filters = 'A85','Fl' if IMG: self._checkTransparency(IMG[0]) else: self.mask = None self.streamContent = string.join(imagedata[2:-1],'')
from reportlab.pdfbase.pdfmetrics import _py_stringWidth, _py_getFont, registerFont
from reportlab.pdfbase.pdfmetrics import _py_stringWidth, getFont, registerFont, _fonts
def testStringWidth(self): from _rl_accel import stringWidthU from reportlab.pdfbase.pdfmetrics import _py_stringWidth, _py_getFont, registerFont from reportlab.pdfbase.ttfonts import TTFont from sys import getrefcount ttfn = 'Luxi-Serif' t1fn = 'Times-Roman' registerFont(TTFont(ttfn, "luxiserif.ttf")) ttf = _py_getFont(ttfn) t1f = _py_getFont(t1fn) testCp1252 = 'copyright %s trademark %s registered %s ReportLab! Ol%s!' % (chr(169), chr(153),chr(174), chr(0xe9)) enc='cp1252' senc = 'utf8' intern(senc) ts = 'ABCDEF\xce\x91\xce\xb2G' utext = 'ABCDEF\xce\x91\xce\xb2G'.decode('utf8') fontSize = 12. def tfunc(ts,fn,fontSize,enc): w1 = stringWidthU(ts,fn,fontSize,enc) w2 = _py_stringWidth(ts,fn,fontSize,enc) assert abs(w1-w2)<1e-10,"stringWidthU(%r,%r,%s,%r)-->%r != _py_stringWidth(...)-->%r" % (ts,fn,fontSize,enc,w1,w2) tfunc(testCp1252,t1fn,fontSize,enc) tfunc(ts,t1fn,fontSize,senc) tfunc(utext,t1fn,fontSize,senc) tfunc(ts,ttfn,fontSize,senc) tfunc(testCp1252,ttfn,fontSize,enc) tfunc(utext,ttfn,fontSize,senc)
from sys import getrefcount
def testStringWidth(self): from _rl_accel import stringWidthU from reportlab.pdfbase.pdfmetrics import _py_stringWidth, _py_getFont, registerFont from reportlab.pdfbase.ttfonts import TTFont from sys import getrefcount ttfn = 'Luxi-Serif' t1fn = 'Times-Roman' registerFont(TTFont(ttfn, "luxiserif.ttf")) ttf = _py_getFont(ttfn) t1f = _py_getFont(t1fn) testCp1252 = 'copyright %s trademark %s registered %s ReportLab! Ol%s!' % (chr(169), chr(153),chr(174), chr(0xe9)) enc='cp1252' senc = 'utf8' intern(senc) ts = 'ABCDEF\xce\x91\xce\xb2G' utext = 'ABCDEF\xce\x91\xce\xb2G'.decode('utf8') fontSize = 12. def tfunc(ts,fn,fontSize,enc): w1 = stringWidthU(ts,fn,fontSize,enc) w2 = _py_stringWidth(ts,fn,fontSize,enc) assert abs(w1-w2)<1e-10,"stringWidthU(%r,%r,%s,%r)-->%r != _py_stringWidth(...)-->%r" % (ts,fn,fontSize,enc,w1,w2) tfunc(testCp1252,t1fn,fontSize,enc) tfunc(ts,t1fn,fontSize,senc) tfunc(utext,t1fn,fontSize,senc) tfunc(ts,ttfn,fontSize,senc) tfunc(testCp1252,ttfn,fontSize,enc) tfunc(utext,ttfn,fontSize,senc)
ttf = _py_getFont(ttfn) t1f = _py_getFont(t1fn)
ttf = getFont(ttfn) t1f = getFont(t1fn)
def testStringWidth(self): from _rl_accel import stringWidthU from reportlab.pdfbase.pdfmetrics import _py_stringWidth, _py_getFont, registerFont from reportlab.pdfbase.ttfonts import TTFont from sys import getrefcount ttfn = 'Luxi-Serif' t1fn = 'Times-Roman' registerFont(TTFont(ttfn, "luxiserif.ttf")) ttf = _py_getFont(ttfn) t1f = _py_getFont(t1fn) testCp1252 = 'copyright %s trademark %s registered %s ReportLab! Ol%s!' % (chr(169), chr(153),chr(174), chr(0xe9)) enc='cp1252' senc = 'utf8' intern(senc) ts = 'ABCDEF\xce\x91\xce\xb2G' utext = 'ABCDEF\xce\x91\xce\xb2G'.decode('utf8') fontSize = 12. def tfunc(ts,fn,fontSize,enc): w1 = stringWidthU(ts,fn,fontSize,enc) w2 = _py_stringWidth(ts,fn,fontSize,enc) assert abs(w1-w2)<1e-10,"stringWidthU(%r,%r,%s,%r)-->%r != _py_stringWidth(...)-->%r" % (ts,fn,fontSize,enc,w1,w2) tfunc(testCp1252,t1fn,fontSize,enc) tfunc(ts,t1fn,fontSize,senc) tfunc(utext,t1fn,fontSize,senc) tfunc(ts,ttfn,fontSize,senc) tfunc(testCp1252,ttfn,fontSize,enc) tfunc(utext,ttfn,fontSize,senc)
fontSize = 12.
fontSize = 12 defns="ttfn t1fn ttf t1f testCp1252 enc senc ts utext fontSize ttf.face ttf.face.charWidths ttf.face.defaultWidth t1f.widths t1f.encName t1f.substitutionFonts _fonts" rcv = getrc(defns)
def testStringWidth(self): from _rl_accel import stringWidthU from reportlab.pdfbase.pdfmetrics import _py_stringWidth, _py_getFont, registerFont from reportlab.pdfbase.ttfonts import TTFont from sys import getrefcount ttfn = 'Luxi-Serif' t1fn = 'Times-Roman' registerFont(TTFont(ttfn, "luxiserif.ttf")) ttf = _py_getFont(ttfn) t1f = _py_getFont(t1fn) testCp1252 = 'copyright %s trademark %s registered %s ReportLab! Ol%s!' % (chr(169), chr(153),chr(174), chr(0xe9)) enc='cp1252' senc = 'utf8' intern(senc) ts = 'ABCDEF\xce\x91\xce\xb2G' utext = 'ABCDEF\xce\x91\xce\xb2G'.decode('utf8') fontSize = 12. def tfunc(ts,fn,fontSize,enc): w1 = stringWidthU(ts,fn,fontSize,enc) w2 = _py_stringWidth(ts,fn,fontSize,enc) assert abs(w1-w2)<1e-10,"stringWidthU(%r,%r,%s,%r)-->%r != _py_stringWidth(...)-->%r" % (ts,fn,fontSize,enc,w1,w2) tfunc(testCp1252,t1fn,fontSize,enc) tfunc(ts,t1fn,fontSize,senc) tfunc(utext,t1fn,fontSize,senc) tfunc(ts,ttfn,fontSize,senc) tfunc(testCp1252,ttfn,fontSize,enc) tfunc(utext,ttfn,fontSize,senc)
from reportlab.pdfbase.pdfmetrics import registerFont, _py_getFont
from reportlab.pdfbase.pdfmetrics import registerFont, getFont, _fonts, unicode2T1
def test_instanceStringWidth(self): from reportlab.pdfbase.pdfmetrics import registerFont, _py_getFont from reportlab.pdfbase.ttfonts import TTFont ttfn = 'Luxi-Serif' t1fn = 'Times-Roman' registerFont(TTFont(ttfn, "luxiserif.ttf")) ttf = _py_getFont(ttfn) t1f = _py_getFont(t1fn) testCp1252 = 'copyright %s trademark %s registered %s ReportLab! Ol%s!' % (chr(169), chr(153),chr(174), chr(0xe9)) enc='cp1252' senc = 'utf8' ts = 'ABCDEF\xce\x91\xce\xb2G' utext = 'ABCDEF\xce\x91\xce\xb2G'.decode(senc) fontSize = 12. def tfunc(f,ts,fontSize,enc): w1 = f.stringWidth(ts,fontSize,enc) w2 = f._py_stringWidth(ts,fontSize,enc) assert abs(w1-w2)<1e-10,"f(%r).stringWidthU(%r,%s,%r)-->%r != f._py_stringWidth(...)-->%r" % (f,ts,fontSize,enc,w1,w2) tfunc(t1f,testCp1252,fontSize,enc) tfunc(t1f,ts,fontSize,senc) tfunc(t1f,utext,fontSize,senc) tfunc(ttf,ts,fontSize,senc) tfunc(ttf,testCp1252,fontSize,enc) tfunc(ttf,utext,fontSize,senc)
ttf = _py_getFont(ttfn) t1f = _py_getFont(t1fn)
ttf = getFont(ttfn) t1f = getFont(t1fn)
def test_instanceStringWidth(self): from reportlab.pdfbase.pdfmetrics import registerFont, _py_getFont from reportlab.pdfbase.ttfonts import TTFont ttfn = 'Luxi-Serif' t1fn = 'Times-Roman' registerFont(TTFont(ttfn, "luxiserif.ttf")) ttf = _py_getFont(ttfn) t1f = _py_getFont(t1fn) testCp1252 = 'copyright %s trademark %s registered %s ReportLab! Ol%s!' % (chr(169), chr(153),chr(174), chr(0xe9)) enc='cp1252' senc = 'utf8' ts = 'ABCDEF\xce\x91\xce\xb2G' utext = 'ABCDEF\xce\x91\xce\xb2G'.decode(senc) fontSize = 12. def tfunc(f,ts,fontSize,enc): w1 = f.stringWidth(ts,fontSize,enc) w2 = f._py_stringWidth(ts,fontSize,enc) assert abs(w1-w2)<1e-10,"f(%r).stringWidthU(%r,%s,%r)-->%r != f._py_stringWidth(...)-->%r" % (f,ts,fontSize,enc,w1,w2) tfunc(t1f,testCp1252,fontSize,enc) tfunc(t1f,ts,fontSize,senc) tfunc(t1f,utext,fontSize,senc) tfunc(ttf,ts,fontSize,senc) tfunc(ttf,testCp1252,fontSize,enc) tfunc(ttf,utext,fontSize,senc)
fontSize = 12.
fontSize = 12 defns="ttfn t1fn ttf t1f testCp1252 enc senc ts utext fontSize ttf.face ttf.face.charWidths ttf.face.defaultWidth t1f.widths t1f.encName t1f.substitutionFonts _fonts" rcv = getrc(defns)
def test_instanceStringWidth(self): from reportlab.pdfbase.pdfmetrics import registerFont, _py_getFont from reportlab.pdfbase.ttfonts import TTFont ttfn = 'Luxi-Serif' t1fn = 'Times-Roman' registerFont(TTFont(ttfn, "luxiserif.ttf")) ttf = _py_getFont(ttfn) t1f = _py_getFont(t1fn) testCp1252 = 'copyright %s trademark %s registered %s ReportLab! Ol%s!' % (chr(169), chr(153),chr(174), chr(0xe9)) enc='cp1252' senc = 'utf8' ts = 'ABCDEF\xce\x91\xce\xb2G' utext = 'ABCDEF\xce\x91\xce\xb2G'.decode(senc) fontSize = 12. def tfunc(f,ts,fontSize,enc): w1 = f.stringWidth(ts,fontSize,enc) w2 = f._py_stringWidth(ts,fontSize,enc) assert abs(w1-w2)<1e-10,"f(%r).stringWidthU(%r,%s,%r)-->%r != f._py_stringWidth(...)-->%r" % (f,ts,fontSize,enc,w1,w2) tfunc(t1f,testCp1252,fontSize,enc) tfunc(t1f,ts,fontSize,senc) tfunc(t1f,utext,fontSize,senc) tfunc(ttf,ts,fontSize,senc) tfunc(ttf,testCp1252,fontSize,enc) tfunc(ttf,utext,fontSize,senc)
from reportlab.pdfbase.pdfmetrics import _py_unicode2T1, _py_getFont
from reportlab.pdfbase.pdfmetrics import _py_unicode2T1, getFont, _fonts
def test_unicode2T1(self): from reportlab.pdfbase.pdfmetrics import _py_unicode2T1, _py_getFont from _rl_accel import unicode2T1 t1fn = 'Times-Roman' t1f = _py_getFont(t1fn) enc = 'cp1252' senc = 'utf8' testCp1252 = ('copyright %s trademark %s registered %s ReportLab! Ol%s!' % (chr(169), chr(153),chr(174), chr(0xe9))).decode(enc) utext = 'This is the end of the \xce\x91\xce\xb2 world. This is the end of the \xce\x91\xce\xb2 world jap=\xe3\x83\x9b\xe3\x83\x86. This is the end of the \xce\x91\xce\xb2 world. This is the end of the \xce\x91\xce\xb2 world jap=\xe3\x83\x9b\xe3\x83\x86'.decode('utf8') def tfunc(f,ts): w1 = unicode2T1(ts,[f]+f.substitutionFonts) w2 = _py_unicode2T1(ts,[f]+f.substitutionFonts) assert w1==w2,"%r != %r" % (w1,w2) tfunc(t1f,testCp1252) tfunc(t1f,utext)
t1f = _py_getFont(t1fn)
t1f = getFont(t1fn)
def test_unicode2T1(self): from reportlab.pdfbase.pdfmetrics import _py_unicode2T1, _py_getFont from _rl_accel import unicode2T1 t1fn = 'Times-Roman' t1f = _py_getFont(t1fn) enc = 'cp1252' senc = 'utf8' testCp1252 = ('copyright %s trademark %s registered %s ReportLab! Ol%s!' % (chr(169), chr(153),chr(174), chr(0xe9))).decode(enc) utext = 'This is the end of the \xce\x91\xce\xb2 world. This is the end of the \xce\x91\xce\xb2 world jap=\xe3\x83\x9b\xe3\x83\x86. This is the end of the \xce\x91\xce\xb2 world. This is the end of the \xce\x91\xce\xb2 world jap=\xe3\x83\x9b\xe3\x83\x86'.decode('utf8') def tfunc(f,ts): w1 = unicode2T1(ts,[f]+f.substitutionFonts) w2 = _py_unicode2T1(ts,[f]+f.substitutionFonts) assert w1==w2,"%r != %r" % (w1,w2) tfunc(t1f,testCp1252) tfunc(t1f,utext)
from reportlab.pdfbase.pdfmetrics import _py_getFont
from reportlab.pdfbase.pdfmetrics import _py_getFont, getFont
def test_getFont(self): from reportlab.pdfbase.pdfmetrics import _py_getFont from _rl_accel import getFontU t1fn = 'Times-Roman' assert _py_getFont(t1fn) is getFontU(t1fn)
self.text = eval(string.join(newtext, ' '))
self.text = newtext
def normalizeText(self): """It contains literal XML text typed over several lines. We want to throw away tabs, newlines and so on, and only accept embedded string like '\n'""" lines = string.split(self.text, '\n') newtext = [] for line in lines: newtext.append(string.strip(line)) #eval turns all the escape sequences into real data self.text = eval(string.join(newtext, ' '))
lines = string.split(string.strip(self.text), '\n')
lines = string.split(string.strip(self.text), '\\n')
def drawOn(self, canv): if self.color is None: return lines = string.split(string.strip(self.text), '\n') canv.saveState() canv.setFont(self.font, self.size) r,g,b = self.color canv.setFillColorRGB(r,g,b) cur_y = self.y for line in lines: if self.align == layout.TA_LEFT: canv.drawString(self.x, cur_y, line) elif self.align == layout.TA_CENTER: canv.drawCentredString(self.x, cur_y, line) elif self.align == layout.TA_RIGHT: canv.drawRightString(self.x, cur_y, line) cur_y = cur_y - 1.2*self.size canv.restoreState()
group = Group() rect = Rect(self.x, self.y, self.width, self.height) rect.fillColor = self.fillColor rect.strokeColor = self.strokeColor rect.strokeWidth = self.strokeWidth return group
if self.fillColor or self.strokeColor and self.strokeWidth: rect = Rect(self.x, self.y, self.width, self.height) rect.fillColor = self.fillColor rect.strokeColor = self.strokeColor rect.strokeWidth = self.strokeWidth return rect else: return None
def makeOuterRect(self): # outer grid rectangle group = Group() #print 'Grid.makeOuterRect(%d, %d, %d, %d)' % (self.x, self.y, self.width, self.height) rect = Rect(self.x, self.y, self.width, self.height) rect.fillColor = self.fillColor rect.strokeColor = self.strokeColor rect.strokeWidth = self.strokeWidth
if g0.useRects == 1 and g1.useRects == 0: group.add(g0.draw()) group.add(g1.draw()) else: group.add(g1.draw()) group.add(g0.draw())
G = g0.useRects == 1 and g1.useRects == 0 and (g0,g1) or (g1,g0) for g in G: group.add(g.makeOuterRect()) for g in G: group.add(g.makeInnerTiles()) group.add(g.makeInnerLines())
def draw(self): group = Group()
print 'Error: '+ cmdname or cmd
print 'Error: '+ (cmdname or cmd)
def do_exec(cmd, cmdname=None): i=os.popen(cmd,'r') print i.read() i = i.close() if i is not None: if cmdname is not None: print 'Error: '+ cmdname or cmd sys.exit(1)
dir = options[0][0]
dir = options[0]
def usage(code=0, msg=''): f = code and sys.stderr or sys.stdout if msg is not None: f.write(msg+'\n') f.write(\
if errmsg!='No module named _rl_accel': raise
if errMsg!='No module named _rl_accel': raise
def _AsciiHexDecode(input): """Decodes input using ASCII-Hex coding. Not used except to provide a test of the inverse function.""" #strip out all whitespace stripped = string.join(string.split(input),'') assert stripped[-1] == '>', 'Invalid terminator for Ascii Hex Stream' stripped = stripped[:-1] #chop off terminator assert len(stripped) % 2 == 0, 'Ascii Hex stream has odd number of bytes' i = 0 output = cStringIO.StringIO() while i < len(stripped): twobytes = stripped[i:i+2] output.write(chr(eval('0x'+twobytes))) i = i + 2 output.reset() return output.read()
fixedEnd = AttrMapValue(isNumberOrNone, desc="Non-zero for a fixed draw end"), fixedStart = AttrMapValue(isNumberOrNone, desc="Non-zero for a fixed draw start"),
fixedEnd = AttrMapValue(isNumberPair, desc="None or fixed draw ends +/-"), fixedStart = AttrMapValue(isNumberPair, desc="None or fixed draw starts +/-"),
def draw(self): _text = self._text self._text = _text or '' self.computeSize() self._text = _text g = Group() g.translate(self.x + self.dx, self.y + self.dy) g.rotate(self.angle)
if self.mask=='auto': if PILImage.info.has_key("transparency") : transparency = PILImage.info["transparency"] * 3 (tred, tgreen, tblue) = map(ord, PILImage.palette.data[transparency:transparency+3]) self.mask = (tred, tred, tgreen, tgreen, tblue, tblue) else: self.mask = None
def loadImageFromPIL(self, PILImage): "Extracts the stream, width and height" zlib = import_zlib() if not zlib: return #standardize it to RGB. We could be more optimal later. if PILImage.mode <> 'RGB': PILImage = PILImage.convert('RGB') imgwidth, imgheight = PILImage.size raw = PILImage.tostring() assert(len(raw) == imgwidth * imgheight, "Wrong amount of data for image") compressed = zlib.compress(raw) encoded = pdfutils._AsciiBase85Encode(compressed) self.colorSpace = 'DeviceRGB' self.bitsPerComponent = 8 self.streamContent = encoded self.width = imgwidth self.height = imgheight
if self.mask=='auto': if PILImage.info.has_key("transparency") : transparency = PILImage.info["transparency"] * 3 (tred, tgreen, tblue) = map(ord, PILImage.palette.data[transparency:transparency+3]) self.mask = (tred, tred, tgreen, tgreen, tblue, tblue) dict["Mask"] = PDFArray(self.mask) else: dict["Mask"] = PDFArray(self.mask)
dict["Mask"] = PDFArray(self.mask)
def format(self, document): S = PDFStream() S.content = self.streamContent
for i in range(10):
for i in xrange(10):
def _test0(self): "This makes one long multi-page paragraph." # Build story. story = [] a = story.append styleSheet = getSampleStyleSheet() h1 = styleSheet['Heading1'] h1.pageBreakBefore = 1 h1.keepWithNext = 1 h2 = styleSheet['Heading2'] h2.frameBreakBefore = 1 h2.keepWithNext = 1 h3 = styleSheet['Heading3'] h3.backColor = colors.cyan h3.keepWithNext = 1 bt = styleSheet['BodyText'] a(Paragraph(""" Subsequent pages test pageBreakBefore, frameBreakBefore and keepTogether attributes. Generated at %s. The number in brackets at the end of each paragraph is its position in the story. (%d)""" % ( time.ctime(time.time()), len(story)), bt)) for i in range(10): a(Paragraph('Heading 1 always starts a new page (%d)' % len(story), h1)) for j in range(3): a(Paragraph('Heading1 paragraphs should always' 'have a page break before. Heading 2 on the other hand' 'should always have a FRAME break before (%d)' % len(story), bt)) a(Paragraph('Heading 2 always starts a new frame (%d)' % len(story), h2)) a(Paragraph('Heading1 paragraphs should always' 'have a page break before. Heading 2 on the other hand' 'should always have a FRAME break before (%d)' % len(story), bt)) for j in range(3): a(Paragraph(randomText(theme=PYTHON, sentences=2)+' (%d)' % len(story), bt)) a(Paragraph('I should never be at the bottom of a frame (%d)' % len(story), h3)) a(Paragraph(randomText(theme=PYTHON, sentences=1)+' (%d)' % len(story), bt)) a(Paragraph('Now we do &lt;br/&gt; tests', h1)) a(Paragraph('First off no br tags',h3)) a(Paragraph(_text1,bt)) a(Paragraph("&lt;br/&gt; after 'the' in line 4",h3)) a(Paragraph(_text1.replace('forms of the','forms of the<br/>',1),bt)) a(Paragraph("2*&lt;br/&gt; after 'the' in line 4",h3)) a(Paragraph(_text1.replace('forms of the','forms of the<br/><br/>',1),bt)) a(Paragraph("&lt;br/&gt; after 'I suggested ' in line 5",h3)) a(Paragraph(_text1.replace('I suggested ','I suggested<br/>',1),bt)) a(Paragraph("2*&lt;br/&gt; after 'I suggested ' in line 5",h3)) a(Paragraph(_text1.replace('I suggested ','I suggested<br/><br/>',1),bt)) doc = MyDocTemplate(outputfile('test_platypus_breaking.pdf')) doc.multiBuild(story)
for j in range(3):
for j in xrange(3):
def _test0(self): "This makes one long multi-page paragraph." # Build story. story = [] a = story.append styleSheet = getSampleStyleSheet() h1 = styleSheet['Heading1'] h1.pageBreakBefore = 1 h1.keepWithNext = 1 h2 = styleSheet['Heading2'] h2.frameBreakBefore = 1 h2.keepWithNext = 1 h3 = styleSheet['Heading3'] h3.backColor = colors.cyan h3.keepWithNext = 1 bt = styleSheet['BodyText'] a(Paragraph(""" Subsequent pages test pageBreakBefore, frameBreakBefore and keepTogether attributes. Generated at %s. The number in brackets at the end of each paragraph is its position in the story. (%d)""" % ( time.ctime(time.time()), len(story)), bt)) for i in range(10): a(Paragraph('Heading 1 always starts a new page (%d)' % len(story), h1)) for j in range(3): a(Paragraph('Heading1 paragraphs should always' 'have a page break before. Heading 2 on the other hand' 'should always have a FRAME break before (%d)' % len(story), bt)) a(Paragraph('Heading 2 always starts a new frame (%d)' % len(story), h2)) a(Paragraph('Heading1 paragraphs should always' 'have a page break before. Heading 2 on the other hand' 'should always have a FRAME break before (%d)' % len(story), bt)) for j in range(3): a(Paragraph(randomText(theme=PYTHON, sentences=2)+' (%d)' % len(story), bt)) a(Paragraph('I should never be at the bottom of a frame (%d)' % len(story), h3)) a(Paragraph(randomText(theme=PYTHON, sentences=1)+' (%d)' % len(story), bt)) a(Paragraph('Now we do &lt;br/&gt; tests', h1)) a(Paragraph('First off no br tags',h3)) a(Paragraph(_text1,bt)) a(Paragraph("&lt;br/&gt; after 'the' in line 4",h3)) a(Paragraph(_text1.replace('forms of the','forms of the<br/>',1),bt)) a(Paragraph("2*&lt;br/&gt; after 'the' in line 4",h3)) a(Paragraph(_text1.replace('forms of the','forms of the<br/><br/>',1),bt)) a(Paragraph("&lt;br/&gt; after 'I suggested ' in line 5",h3)) a(Paragraph(_text1.replace('I suggested ','I suggested<br/>',1),bt)) a(Paragraph("2*&lt;br/&gt; after 'I suggested ' in line 5",h3)) a(Paragraph(_text1.replace('I suggested ','I suggested<br/><br/>',1),bt)) doc = MyDocTemplate(outputfile('test_platypus_breaking.pdf')) doc.multiBuild(story)
words = [f.clone()] words[-1].text = nText elif not _sameFrag(words[-1],f):
g = f.clone() words = [g] g.text = nText elif not _sameFrag(g,f):
def breakLines(self, width): """ Returns a broken line structure. There are two cases A) For the simple case of a single formatting input fragment the output is A fragment specifier with kind = 0 fontName, fontSize, leading, textColor lines= A list of lines Each line has two items. 1) unused width in points 2) word list
words[-1].text = words[-1].text + ' ' words.append(f.clone()) words[-1].text = nText
if hasattr(g,'cbDefn'): i = len(words)-1 while hasattr(words[i],'cbDefn'): i = i-1 words[i].text = words[i].text + ' ' else: g.text = g.text + ' ' g = f.clone() words.append(g) g.text = nText
def breakLines(self, width): """ Returns a broken line structure. There are two cases A) For the simple case of a single formatting input fragment the output is A fragment specifier with kind = 0 fontName, fontSize, leading, textColor lines= A list of lines Each line has two items. 1) unused width in points 2) word list
words[-1].text = words[-1].text + ' ' + nText
g.text = g.text + ' ' + nText
def breakLines(self, width): """ Returns a broken line structure. There are two cases A) For the simple case of a single formatting input fragment the output is A fragment specifier with kind = 0 fontName, fontSize, leading, textColor lines= A list of lines Each line has two items. 1) unused width in points 2) word list
f = i[0].clone() f.text=i[1] words.append(f) maxSize = max(maxSize,f.fontSize)
g = i[0].clone() g.text=i[1] words.append(g) maxSize = max(maxSize,g.fontSize)
def breakLines(self, width): """ Returns a broken line structure. There are two cases A) For the simple case of a single formatting input fragment the output is A fragment specifier with kind = 0 fontName, fontSize, leading, textColor lines= A list of lines Each line has two items. 1) unused width in points 2) word list
words = [f.clone()] words[-1].text = w[1][1]
g = f.clone() words = [g] g.text = w[1][1]
def breakLines(self, width): """ Returns a broken line structure. There are two cases A) For the simple case of a single formatting input fragment the output is A fragment specifier with kind = 0 fontName, fontSize, leading, textColor lines= A list of lines Each line has two items. 1) unused width in points 2) word list
for f in ('xmlparser.c', 'url.c', 'charset.c', 'string16.c', 'ctype16.c', 'dtd.c', 'input.c', 'stdio16.c', 'system.c', 'hash.c', 'version.c', 'namespaces.c', 'http.c'): RXPLIBSOURCES.append(os.path.join(RXPDIR,f))
uRXPLIBSOURCES=[] for f in ('xmlparser.c', 'url.c', 'charset.c', 'string16.c', 'ctype16.c', 'dtd.c', 'input.c', 'stdio16.c', 'system.c', 'hash.c', 'version.c', 'namespaces.c', 'http.c'): RXP_file = os.path.join(RXPDIR,f) uRXP_file = os.path.join(RXPUDIR,f.replace('.','U.')) RXPLIBSOURCES.append(RXP_file) shutil.copy2(RXP_file,uRXP_file) uRXPLIBSOURCES.append(uRXP_file) pyRXPU_c = os.path.join(RXPUDIR,'pyRXPU.c') shutil.copy2('pyRXP.c',pyRXPU_c) uRXPLIBSOURCES.append(pyRXPU_c)
def raiseConfigError(msg): import exceptions class ConfigError(exceptions.Exception): pass raise ConfigError(msg)
version = "0.5", description = "Python RXP interface",
version = VERSION, description = "Python RXP interface - fast validating XML parser",
def raiseConfigError(msg): import exceptions class ConfigError(exceptions.Exception): pass raise ConfigError(msg)
define_macros=[('CHAR_SIZE', 8)],
define_macros=[('CHAR_SIZE', 8),],
def raiseConfigError(msg): import exceptions class ConfigError(exceptions.Exception): pass raise ConfigError(msg)
]
Extension( 'pyRXPU', uRXPLIBSOURCES, include_dirs=[RXPDIR], define_macros=[('CHAR_SIZE', 16),], library_dirs=[], libraries=LIBS, ), ], classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: ReportLab BSD derived', 'Programming Language :: Python', 'Programming Language :: C', 'Operating System :: Unix', 'Operating System :: POSIX', 'Operating System :: Microsoft :: Windows', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Text Processing :: Markup :: XML', ]
def raiseConfigError(msg): import exceptions class ConfigError(exceptions.Exception): pass raise ConfigError(msg)
'greek': (self.start_greek, self.end_greek)
'greek': (self.start_greek, self.end_greek), 'para': (self.start_para, self.end_para)
def __init__(self,verbose=0): if _xmllib_newStyle: xmllib.XMLParser.__init__(self,verbose=verbose) else: xmllib.XMLParser.__init__(self) # set up handlers for various tags self.elements = { 'b': (self.start_b, self.end_b), 'u': (self.start_u, self.end_u), 'i': (self.start_i, self.end_i), 'super': (self.start_super, self.end_super), 'sub': (self.start_sub, self.end_sub), 'font': (self.start_font, self.end_font), 'greek': (self.start_greek, self.end_greek) }
fnroot = os.path.join(getattr(self,'outDir','.'), fnRoot or (getattr(self,'fileNamePattern',(self.__class__.__name__+'%03d') % getattr(self,'chartId',0))))
fnroot = os.path.join(getattr(self,'outDir','.'), fnRoot or (getattr(self,'fileNamePattern',(self.__class__.__name__+'%03d')) % getattr(self,'chartId',0)))
def save(self, formats=['pdf'], verbose=None, fnRoot=None): "Saves copies of self in desired location and formats" ext = '' fnroot = os.path.join(getattr(self,'outDir','.'), fnRoot or (getattr(self,'fileNamePattern',(self.__class__.__name__+'%03d') % getattr(self,'chartId',0))))
s = self._atTop and 0 or flowable.getSpaceBefore()
s = 0 if self._atTop: s = flowable.getSpaceBefore()
def _add(self, flowable, canv, trySplit=0): """ Draws the flowable at the current position. Returns 1 if successful, 0 if it would not fit. Raises a LayoutError if the object is too wide, or if it is too high for a totally empty frame, to avoid infinite loops""" y = self._y p = self._y1p s = self._atTop and 0 or flowable.getSpaceBefore() h = y - p - s if h>0: flowable.canv = canv #so they can use stringWidth etc w, h = flowable.wrap(self._aW, h) del flowable.canv else: return 0
self._atTop = 0
if y<>self._y: self._atTop = 0
def _add(self, flowable, canv, trySplit=0): """ Draws the flowable at the current position. Returns 1 if successful, 0 if it would not fit. Raises a LayoutError if the object is too wide, or if it is too high for a totally empty frame, to avoid infinite loops""" y = self._y p = self._y1p s = self._atTop and 0 or flowable.getSpaceBefore() h = y - p - s if h>0: flowable.canv = canv #so they can use stringWidth etc w, h = flowable.wrap(self._aW, h) del flowable.canv else: return 0
s = self._atTop and 0 or flowable.getSpaceBefore()
s = 0 if self._atTop: s = flowable.getSpaceBefore()
def split(self,flowable,canv): '''Ask the flowable to split using up the available space.''' y = self._y p = self._y1p s = self._atTop and 0 or flowable.getSpaceBefore() flowable.canv = canv #some flowables might need this r = flowable.split(self._aW, y-p-s) del flowable.canv return r
'license.txt'
'license.txt',
def _find_rl_accel(): '''locate where the accelerator code lives''' _ = [] for x in [ './rl_addons/rl_accel', '../rl_addons/rl_accel', '../../rl_addons/rl_accel', './rl_accel', '../rl_accel', '../../rl_accel', './lib'] \ + glob.glob('./rl_accel-*/rl_accel')\ + glob.glob('../rl_accel-*/rl_accel') \ + glob.glob('../../rl_accel-*/rl_accel') \ : fn = pjoin(x,'_rl_accel.c') if isfile(pjoin(x,'_rl_accel.c')): _.append(x) if _: if len(_)>1: _.sort(_cmp_rl_accel_dirs) return abspath(_[0]) return None
p("""Illustrating that remapping using the [DRINKER<=DRINKER, BAR<=BAR] graph eliminates all attributes except DRINKER and
p("""Illustrating that remapping using the [DRINKER&lt;=DRINKER, BAR&lt;=BAR] graph eliminates all attributes except DRINKER and
def pre(txt): s = layout.Spacer(0.1*inch, 0.1*inch) Elements.append(s) p = layout.Preformatted(txt, PreStyle) Elements.append(p)
p("""where b<a<c. Furthermore joins with this table are not
p("""where b&lt;a&lt;c. Furthermore joins with this table are not
def pre(txt): s = layout.Spacer(0.1*inch, 0.1*inch) Elements.append(s) p = layout.Preformatted(txt, PreStyle) Elements.append(p)
if __name__=='__main__': import os, sys, string
def pfxJoin(pfx,*N): R=[] for n in N: R.append(os.path.join(pfx,n)) return R FT_LIB='C:/Python/devel/freetype-2.1.5/objs/freetype214.lib' FT_INCLUDE=None def check_ft_lib(ft_lib=FT_LIB): return os.path.isfile(ft_lib) and ft_lib or '' def main():
def BIGENDIAN(macname,value=None): 'define a macro if bigendian' return sys.byteorder=='big' and [(macname,value)] or []
ROBIN_DEBUG=[('ROBIN_DEBUG',None)] ROBIN_DEBUG=[]
MACROS=[('ROBIN_DEBUG',None)] MACROS=[]
def BIGENDIAN(macname,value=None): 'define a macro if bigendian' return sys.byteorder=='big' and [(macname,value)] or []
def pfxJoin(pfx,*N): R=[] for n in N: R.append(pJoin(pfx,n)) return R
def pfxJoin(pfx,*N): R=[] for n in N: R.append(pJoin(pfx,n)) return R
version = "1.11",
version = VERSION,
def pfxJoin(pfx,*N): R=[] for n in N: R.append(pJoin(pfx,n)) return R
'macros': [('LIBART_COMPILATION',None),]+BIGENDIAN('WORDS_BIGENDIAN')+ROBIN_DEBUG,
'macros': [('LIBART_COMPILATION',None),]+BIGENDIAN('WORDS_BIGENDIAN')+MACROS,
def pfxJoin(pfx,*N): R=[] for n in N: R.append(pJoin(pfx,n)) return R
'macros': ROBIN_DEBUG,
'macros': MACROS,
def pfxJoin(pfx,*N): R=[] for n in N: R.append(pJoin(pfx,n)) return R
include_dirs=[DEVEL_DIR,LIBART_DIR,GT1_DIR], define_macros=[('LIBART_COMPILATION',None)]+ROBIN_DEBUG+[('LIBART_VERSION',LIBART_VERSION)], library_dirs=[],
include_dirs=[DEVEL_DIR,LIBART_DIR,GT1_DIR]+FT_INC_DIR, define_macros=FT_MACROS+[('LIBART_COMPILATION',None)]+MACROS+[('LIBART_VERSION',LIBART_VERSION)], library_dirs=[]+FT_LIB_DIR,
def pfxJoin(pfx,*N): R=[] for n in N: R.append(pJoin(pfx,n)) return R
libraries=LIBS,
libraries=LIBS+FT_LIB,
def pfxJoin(pfx,*N): R=[] for n in N: R.append(pJoin(pfx,n)) return R
if sys.platform=='win32' and ('install' in sys.argv or 'install_ext' in sys.argv):
if sys.hexversion<0x2030000 and sys.platform=='win32' and ('install' in sys.argv or 'install_ext' in sys.argv):
def pfxJoin(pfx,*N): R=[] for n in N: R.append(pJoin(pfx,n)) return R
labels = labels + [''] * m
labels = list(labels) + [''] * m
def makeSectors(self): # normalize slice data if type(self.data) in (ListType, TupleType) and type(self.data[0]) in (ListType, TupleType): #it's a nested list, more than one sequence normData = [] n = [] for l in self.data: t = self.normalizeData(l) normData.append(t) n.append(len(t)) else: normData = self.normalizeData(self.data) n = len(normData)
labels = labels + ['']*i
labels = list(labels) + [''] * i
def makeSectors(self): # normalize slice data if type(self.data) in (ListType, TupleType) and type(self.data[0]) in (ListType, TupleType): #it's a nested list, more than one sequence normData = [] n = [] for l in self.data: t = self.normalizeData(l) normData.append(t) n.append(len(t)) else: normData = self.normalizeData(self.data) n = len(normData)
__version__ = '$Id: ttfonts.py,v 1.7 2002/09/02 16:17:29 mgedmin Exp $'
__version__ = '$Id: ttfonts.py,v 1.8 2002/09/06 15:53:51 mgedmin Exp $'
def getSubsetInternalName(self, subset, doc): '''Returns the name of a PDF Font object corresponding to a given subset of this dynamic font. Use this function instead of PDFDocument.getInternalFontName.'''
if ver_maj not in (1, 2, 3):
if ver_maj not in (1, 2, 3, 4):
def extractInfo(self, charInfo=1): """Extract typographic information from the loaded font file.
loca = apply(pack, [">%d:" % len(loca)] + loca)
loca = apply(pack, [">%dL" % len(loca)] + loca)
def makeSubset(self, subset): """Create a subset of a TrueType font""" output = TTFontMaker()
if (nText!='' and nText[0]!=' ') or hasattr(f,'cbDefn'):
if currentWidth>0 and ((nText!='' and nText[0]!=' ') or hasattr(f,'cbDefn')):
def breakLines(self, width): """ Returns a broken line structure. There are two cases A) For the simple case of a single formatting input fragment the output is A fragment specifier with kind = 0 fontName, fontSize, leading, textColor lines= A list of lines Each line has two items. 1) unused width in points 2) word list
strokeColor = colors.black,
strokeColor = None,
def _Flag_Palestine(self): s = _size g = Group() box = Rect(0, s/3, s*2, s/3, fillColor = colors.mintcream, strokeColor = colors.black, strokeWidth=0) g.add(box)
for f in formats: if f: c().save(formats=[f],outDir='.',fnRoot=c.__name__)
for fmt in formats: if fmt: c().save(formats=[fmt],outDir='.',fnRoot=c.__name__)
def run(format, VERBOSE=0): formats = string.split(format, ',') for i in range(0, len(formats)): formats[i] == string.lower(string.strip(formats[i])) allfiles = glob.glob('*.py') allfiles.sort() for fn in allfiles: f = string.split(fn, '.')[0] c = getclass(f) if c != None: print c.__name__ try: for f in formats: if f: c().save(formats=[f],outDir='.',fnRoot=c.__name__) if VERBOSE: print " %s.%s" % (c.__name__, f) except: print " COULDN'T CREATE '%s.%s'!" % (c.__name__, format)
print " %s.%s" % (c.__name__, f)
print " %s.%s" % (c.__name__, fmt)
def run(format, VERBOSE=0): formats = string.split(format, ',') for i in range(0, len(formats)): formats[i] == string.lower(string.strip(formats[i])) allfiles = glob.glob('*.py') allfiles.sort() for fn in allfiles: f = string.split(fn, '.')[0] c = getclass(f) if c != None: print c.__name__ try: for f in formats: if f: c().save(formats=[f],outDir='.',fnRoot=c.__name__) if VERBOSE: print " %s.%s" % (c.__name__, f) except: print " COULDN'T CREATE '%s.%s'!" % (c.__name__, format)
c = min(1,max(0,c-k) m = min(1,max(0,m-k) y = min(1,max(0,y-k)
c = min(1,max(0,c-k)) m = min(1,max(0,m-k)) y = min(1,max(0,y-k))
def rgb2cmyk(r,g,b): c = 1 - r m = 1 - g y = 1 - b k = min(c,m,y) c = min(1,max(0,c-k) m = min(1,max(0,m-k) y = min(1,max(0,y-k) k = min(1,max(0,k)) return (c,m,y,k)
import string text = join(self.lines, "\n") return "%s'''\\ \n%s''')" % (H, text)
return "%s'''\\ \n%s''')" % (H, string.join(self.lines,'\n'))
def __repr__(self): bT = self.bulletText H = "Preformatted(" if bT is not None: H = "Preformatted(bulletText=%s," % repr(bT) import string text = join(self.lines, "\n") return "%s'''\\ \n%s''')" % (H, text)
else: return w, t
def _listCellGeom(self, V,w,s,W=None,H=None,aH=72000): aW = w-s.leftPadding-s.rightPadding aH = aH - s.topPadding - s.bottomPadding t = 0 w = 0 canv = getattr(self,'canv',None) for v in V: vw, vh = v.wrapOn(canv,aW, aH) if W is not None: W.append(vw) if H is not None: H.append(vh) w = max(w,vw) t = t + vh + v.getSpaceBefore()+v.getSpaceAfter() else: return w, t return w, t - V[0].getSpaceBefore()-V[-1].getSpaceAfter()
failTest('</a>',"Error Error: End tag </a> outside of any element\n in unnamed entity at line 1 char 4 of [unknown]\nerror return=1\nEnd tag\n")
failTest('</a>',"Error Error: End tag </a> outside of any element\n in unnamed entity at line 1 char 4 of [unknown]\nerror return=1\nEnd tag </a> outside of any element\nParse Failed!\n")
def failTest(x,t,tb=1,**kw): goodTest(x,t,tb,**kw)
sum = 0.0 for number in self.data: sum = sum + number normData = [] for number in self.data: normData.append(360.0 * number / sum) return normData
from operator import add data = self.data sum = float(reduce(add,data)) return abs(sum)>=1e-8 and map(lambda x,f=360./sum: f*x, data) or len(data)*[0]
def normalizeData(self): sum = 0.0 for number in self.data: sum = sum + number
return tuple(map(lambda x: int((x*255)&255), self.rgb()))
return tuple(map(lambda x: int(x*255)&255, self.rgb()))
def bitmap_rgb(self): return tuple(map(lambda x: int((x*255)&255), self.rgb()))
def _reduceDocStringLength(docStr):
def reduceDocStringLength(docStr):
def _reduceDocStringLength(docStr): "Return first line of a multiline string." return split(docStr, '\n')[0]
e.g. Ascii, Html, Pdf.
e.g. Ascii, Html, Pdf (default), UmlPdf.
def printUsage(): """docpy0.py - Automated documentation for Python source code.
python docpy0.py -p pingo -f Html
python docpy0.py -p reportlab.platypus -f UmlPdf
def printUsage(): """docpy0.py - Automated documentation for Python source code.
def documentModule0(path, builder=DocBuilder0()):
def documentModule0(path, builder=PdfDocBuilder0()):
def documentModule0(path, builder=DocBuilder0()): """Generate documentation for one Python file in some format. This handles Python standard modules like string, custom modules on the Python search path like e.g. docpy as well as modules specified with their full path like C:/tmp/junk.py. The doc file will always be saved in the current directory with a basename equal to the module's name. """ cwd = os.getcwd() # Append directory to Python search path if we get one. dirName = os.path.dirname(path) if dirName: sys.path.append(dirName) # Remove .py extension from module name. if path[-3:] == '.py': modname = path[:-3] else: modname = path # Remove directory paths from module name. if dirName: modname = os.path.basename(modname) # Load the module. try: module = __import__(modname) except: print 'Failed to import %s.' % modname os.chdir(cwd) return # Do the real documentation work. s = ModuleSkeleton0() s.inspect(module) builder.write(s) # Remove appended directory from Python search path if we got one. if dirName: del sys.path[-1] os.chdir(cwd)
"A callback function used when waking over a package tree."
def _packageWalkCallback(builder, dirPath, files): """A callback function used when waking over a package tree.""" files = filter(lambda f:f != '__init__.py', files) files = filter(lambda f:f[-3:] == '.py', files) if files: for f in files: path = os.path.join(dirPath, f) print path builder.indentLevel = builder.indentLevel + 1 documentModule0(path, builder) builder.indentLevel = builder.indentLevel - 1
def documentPackage0(path, builder=DocBuilder0()):
def documentPackage0(pathOrName, builder=PdfDocBuilder0()):
def documentPackage0(path, builder=DocBuilder0()): """Generate documentation for one Python package in some format. Rigiht now, 'path' must be a filesystem path, later it will also be a package name whose path will be resolved by importing the top-level module. The doc file will always be saved in the current directory. """ name = path if string.find(path, os.sep) > -1: name = os.path.splitext(os.path.basename(path))[0] else: package = __import__(name) name = path path = os.path.dirname(package.__file__) cwd = os.getcwd() builder.beginPackage(name) os.path.walk(path, _packageWalkCallback, builder) builder.endPackage(name) os.chdir(cwd)
name = path if string.find(path, os.sep) > -1: name = os.path.splitext(os.path.basename(path))[0]
if string.find(pathOrName, os.sep) > -1: name = os.path.splitext(os.path.basename(pathOrName))[0] path = pathOrName
def documentPackage0(path, builder=DocBuilder0()): """Generate documentation for one Python package in some format. Rigiht now, 'path' must be a filesystem path, later it will also be a package name whose path will be resolved by importing the top-level module. The doc file will always be saved in the current directory. """ name = path if string.find(path, os.sep) > -1: name = os.path.splitext(os.path.basename(path))[0] else: package = __import__(name) name = path path = os.path.dirname(package.__file__) cwd = os.getcwd() builder.beginPackage(name) os.path.walk(path, _packageWalkCallback, builder) builder.endPackage(name) os.chdir(cwd)
package = __import__(name) name = path
package = __import__(pathOrName) if '.' in pathOrName: subname = 'package' + pathOrName[string.find(pathOrName, '.'):] package = eval(subname) name = pathOrName
def documentPackage0(path, builder=DocBuilder0()): """Generate documentation for one Python package in some format. Rigiht now, 'path' must be a filesystem path, later it will also be a package name whose path will be resolved by importing the top-level module. The doc file will always be saved in the current directory. """ name = path if string.find(path, os.sep) > -1: name = os.path.splitext(os.path.basename(path))[0] else: package = __import__(name) name = path path = os.path.dirname(package.__file__) cwd = os.getcwd() builder.beginPackage(name) os.path.walk(path, _packageWalkCallback, builder) builder.endPackage(name) os.chdir(cwd)
"Handle command-line options and trigger corresponding action."
def main(): """Handle command-line options and trigger corresponding action. """ opts, args = getopt.getopt(sys.argv[1:], 'hf:m:p:') # On -h print usage and exit immediately. for o, a in opts: if o == '-h': print printUsage.__doc__ #printUsage() sys.exit(0) # On -f set the DocBuilder to use or a default one. builder = DocBuilder0() for o, a in opts: if o == '-f': builder = eval("%sDocBuilder0()" % a) break # Now call the real documentation functions. for o, a in opts: if o == '-m': builder.begin() documentModule0(a, builder) builder.end() sys.exit(0) elif o == '-p': builder.begin() documentPackage0(a, builder) builder.end() sys.exit(0)
builder = DocBuilder0()
builder = PdfDocBuilder0()
def main(): """Handle command-line options and trigger corresponding action. """ opts, args = getopt.getopt(sys.argv[1:], 'hf:m:p:') # On -h print usage and exit immediately. for o, a in opts: if o == '-h': print printUsage.__doc__ #printUsage() sys.exit(0) # On -f set the DocBuilder to use or a default one. builder = DocBuilder0() for o, a in opts: if o == '-f': builder = eval("%sDocBuilder0()" % a) break # Now call the real documentation functions. for o, a in opts: if o == '-m': builder.begin() documentModule0(a, builder) builder.end() sys.exit(0) elif o == '-p': builder.begin() documentPackage0(a, builder) builder.end() sys.exit(0)
print 'zlib not available'
warnOnce('zlib not available')
def cache_imagedata(self): image = self.image if not pdfutils.cachedImageExists(image): if not zlib: print 'zlib not available' return try: import Image except ImportError: print 'Python Imaging Library not available' return pdfutils.cacheImageFile(image)
print 'Python Imaging Library not available'
warnOnce('Python Imaging Library not available')
def cache_imagedata(self): image = self.image if not pdfutils.cachedImageExists(image): if not zlib: print 'zlib not available' return try: import Image except ImportError: print 'Python Imaging Library not available' return pdfutils.cacheImageFile(image)
if not zlib: print 'zlib not available' return
def PIL_imagedata(self): image = self.image if not zlib: print 'zlib not available' return myimage = image.convert('RGB') imgwidth, imgheight = myimage.size
imagedata.append('BI /W %d /H %d /BPC 8 /CS /RGB /F [/A85 /Fl] ID' % (imgwidth, imgheight))
imagedata=['BI /W %d /H %d /BPC 8 /CS /RGB /F [/A85 /Fl] ID' % (imgwidth, imgheight))]
def PIL_imagedata(self): image = self.image if not zlib: print 'zlib not available' return myimage = image.convert('RGB') imgwidth, imgheight = myimage.size
d = drawing
d = drawing or Drawing(400, 200)
def sample3(drawing=None): "Add sample swatches to a diagram." d = drawing swatches = Legend0() swatches.alignment = 'right' swatches.x = 80 swatches.y = 160 swatches.deltax = 60 swatches.dxTextSpace = 10 swatches.columnMaximum = 4 items = [(colors.red, 'before'), (colors.green, 'after')] swatches.colorNamePairs = items d.add(swatches, 'legend') return d
return tempfile.mktemp('','',get_rl_tempdir()) else: return os.path.join(get_rl_tempdir(),fn)
fn = tempfile.mktemp() return os.path.join(get_rl_tempdir(),fn)
def get_rl_tempfile(fn=None): if not fn: import tempfile return tempfile.mktemp('','',get_rl_tempdir()) else: return os.path.join(get_rl_tempdir(),fn)
if s<=1: return []
if s<=1: del self.blPara return []
def split(self,availWidth, availHeight): if len(self.frags)<=0: return []
if isFile and not hasSeek: filename = filename._filename
def multiBuild(self, story, filename=None, canvasmaker=canvas.Canvas, maxPasses = 10): """Makes multiple passes until all indexing flowables are happy.""" self._indexingFlowables = [] #scan the story and keep a copy for thing in story: if thing.isIndexing(): self._indexingFlowables.append(thing) #print 'scanned story, found these indexing flowables:\n' #print self._indexingFlowables
parentValue = getattr(self, key) if parentValue <> value:
if not hasattr(self,key) or getattr(self, key)<>value:
def getProperties(self,recur=1): # return any children which are defined and whatever # differs from the parent props = {}
if type(abf) not in (TupleType,ListType): i0 = i1 = valueStep*abf else: i0 = valueStep*abf[0] i1 = valueStep*abf[1]
i0 = valueStep*abf[0] i1 = valueStep*abf[1]
def _setRange(self, dataSeries): """Set minimum and maximum axis values.
if _n - T[0] < i0-fuzz: valueMin = valueMin - i0 if T[-1]-_x < i1-fuzz: valueMax = valueMax + i1
if abs(T[0])>fuzz and _n - T[0] < i0-fuzz: valueMin = valueMin - i0 if abs(T[-1])>fuzz and T[-1]-_x < i1-fuzz: valueMax = valueMax + i1
def _setRange(self, dataSeries): """Set minimum and maximum axis values.
name = md5.md5('%s%s' % (image, mask)).hexdigest()
name = _digester('%s%s' % (image, mask))
def drawImage(self, image, x, y, width=None, height=None, mask=None): """Draws the image (PIL Image object or filename) as specified.
name = md5.md5(rawdata).hexdigest()
name = _digester(rawdata)
def drawImage(self, image, x, y, width=None, height=None, mask=None): """Draws the image (PIL Image object or filename) as specified.
if self._code[-1][-3:]==' Td':
if len(self._code) and self._code[-1][-3:]==' Td':
def moveCursor(self, dx, dy): """Moves to a point dx, dy away from the start of the current line - NOT from the current point! So if you call it in mid-sentence, watch out.""" if self._code[-1][-3:]==' Td': L = string.split(self._code[-1]) if len(L)==3: del self._code[-1] else: self._code[-1] = string.join(L[:-4]) if dx<>0 or dy<>0: self._code.append('%s Td' % fp_str(dx, -dy))
from string import letters as LETTERS, whitespace as WHITESPACE, atoi
def Paragraph(text, style, bulletText=None, frags=None)
if text[0] in LETTERS:
from string import letters if text[0] in letters:
def readColor(text): """Read color names or tuples, RGB or CMYK, and return a Color object.""" if not text: return None from reportlab.lib import colors if text[0] in LETTERS: return colors.__dict__[text] tup = lengthSequence(text) msg = "Color tuple must have 3 (or 4) elements for RGB (or CMYC)." assert 3 <= len(tup) <= 4, msg msg = "Color tuple must have all elements <= 1.0." for i in range(len(tup)): assert tup[i] <= 1.0, msg if len(tup) == 3: colClass = colors.Color elif len(tup) == 4: colClass = colors.CMYKColor return apply(colClass, tup)
from string import whitespace
from string import whitespace, atoi, atoi_error
def handleSpecialCharacters(engine, text, program=None): from paraparser import greeks, symenc from string import whitespace standard={'lt':'<', 'gt':'>', 'amp':'&'} # add space prefix if space here if text[0:1] in whitespace: program.append(" ") #print "handling", repr(text) # shortcut if 0 and "&" not in text: result = [] for x in text.split(): result.append(x+" ") if result: last = result[-1] if text[-1:] not in whitespace: result[-1] = last.strip() program.extend(result) return program if program is None: program = [] amptext = text.split("&") first = 1 lastfrag = amptext[-1] for fragment in amptext: if not first: # check for special chars semi = fragment.find(";") if semi>0: name = fragment[:semi] if name[0]=='#': try: if name[1] == 'x': n = atoi(name[2:], 16) else: n = atoi(name[1:]) except atoi_error: n = -1 if 0<=n<=255: fragment = chr(n)+fragment[semi+1:] elif symenc.has_key(n): fragment = fragment[semi+1:] (f,b,i) = engine.shiftfont(program, face="symbol") program.append(symenc[n]) engine.shiftfont(program, face=f) if fragment and fragment[0] in WHITESPACE: program.append(" ") # follow with a space else: fragment = "&"+fragment elif standard.has_key(name): fragment = standard[name]+fragment[semi+1:] elif greeks.has_key(name): fragment = fragment[semi+1:] greeksub = greeks[name] (f,b,i) = engine.shiftfont(program, face="symbol") program.append(greeksub) engine.shiftfont(program, face=f) if fragment and fragment[0] in WHITESPACE: program.append(" ") # follow with a space else: # add back the & fragment = "&"+fragment else: # add back the & fragment = "&"+fragment # add white separated components of fragment followed by space sfragment = fragment.split() for w in sfragment[:-1]: program.append(w+" ") # does the last one need a space? if sfragment and fragment: # reader 3 used to go nuts if you don't special case the last frag, but it's fixed? if fragment[-1] in WHITESPACE: # or fragment==lastfrag: program.append( sfragment[-1]+" " ) else: last = sfragment[-1].strip() if last: #print "last is", repr(last) program.append( last ) first = 0 #print "HANDLED", program return program