def setStrokeColor(self, aColor, alpha=None): """Takes a color object, allowing colors to be referred to by name""" if self._enforceColorSpace: aColor = self._enforceColorSpace(aColor) if isinstance(aColor, CMYKColor): d = aColor.density c,m,y,k = (d*aColor.cyan, d*aColor.magenta, d*aColor.yellow, d*aColor.black) self._strokeColorObj = aColor name = self._checkSeparation(aColor) if name: self._code.append('/%s CS %s SCN' % (name,fp_str(d))) else: self._code.append('%s K' % fp_str(c, m, y, k)) elif isinstance(aColor, Color): rgb = (aColor.red, aColor.green, aColor.blue) self._strokeColorObj = aColor self._code.append('%s RG' % fp_str(rgb) ) elif isinstance(aColor,(tuple,list)): l = len(aColor) if l==3: self._strokeColorObj = aColor self._code.append('%s RG' % fp_str(aColor) ) elif l==4: self._fillColorObj = aColor self._code.append('%s K' % fp_str(aColor)) else: raise ValueError('Unknown color %r' % aColor) elif isStrType(aColor): self.setStrokeColor(toColor(aColor)) else: raise ValueError('Unknown color %r' % aColor) if alpha is not None: self.setStrokeAlpha(alpha) elif getattr(aColor, 'alpha', None) is not None: self.setStrokeAlpha(aColor.alpha)
def drawIndexEntryEnd(canvas, kind, label): """Callback to draw dots and page numbers after each entry.""" if not isStrType(label): label = label.decoce("utf-8") style = self.getLevelStyle(leveloffset) pages = decode_label(label) drawPageNumbers(canvas, style, pages, availWidth, availHeight, self.dot)
def drawIndexEntryEnd(canvas, kind, label): '''Callback to draw dots and page numbers after each entry.''' if not isStrType(label): label = label.decoce('utf-8') style = self.getLevelStyle(leveloffset) pages = decode_label(label) drawPageNumbers(canvas, style, pages, availWidth, availHeight, self.dot)
def setNormalDate(self, normalDate): """ accepts date as scalar string/integer (yyyymmdd) or tuple (year, month, day, ...)""" if isinstance(normalDate, int): self.normalDate = normalDate elif isStrType(normalDate): try: self.normalDate = int(normalDate) except: m = _iso_re.match(normalDate) if m: self.setNormalDate(m.group(1) + m.group(2) + m.group(3)) else: raise NormalDateException("unable to setNormalDate(%s)" % repr(normalDate)) elif isinstance(normalDate, _DateSeqTypes): self.normalDate = int("%04d%02d%02d" % normalDate[:3]) elif isinstance(normalDate, NormalDate): self.normalDate = normalDate.normalDate elif isinstance(normalDate, (datetime.datetime, datetime.date)): self.normalDate = (normalDate.year * 100 + normalDate.month) * 100 + normalDate.day if not self._isValidNormalDate(self.normalDate): raise NormalDateException("unable to setNormalDate(%s)" % repr(normalDate))
def getImageData(self,preserveAspectRatio=False): "Gets data, height, width - whatever type of image" image = self.image if isStrType(image): self.filename = image if os.path.splitext(image)[1] in ['.jpg', '.JPG', '.jpeg', '.JPEG']: try: imagedata, imgwidth, imgheight = self.jpg_imagedata() except: imagedata, imgwidth, imgheight = self.non_jpg_imagedata(image) #try for normal kind of image else: imagedata, imgwidth, imgheight = self.non_jpg_imagedata(image) else: import sys if sys.platform[0:4] == 'java': #jython, PIL not available imagedata, imgwidth, imgheight = self.JAVA_imagedata() else: imagedata, imgwidth, imgheight = self.PIL_imagedata() self.imageData = imagedata self.imgwidth = imgwidth self.imgheight = imgheight self.width = self.width or imgwidth self.height = self.height or imgheight
def __call__(self, arg, default=None): '''try to map an arbitrary arg to a color instance ''' if isinstance(arg, Color): return arg if isinstance(arg, (tuple, list)): assert 3 <= len( arg) <= 4, 'Can only convert 3 and 4 sequences to color' assert 0 <= min(arg) and max(arg) <= 1 return len(arg) == 3 and Color(arg[0], arg[1], arg[2]) or CMYKColor( arg[0], arg[1], arg[2], arg[3]) elif isStrType(arg): C = cssParse(arg) if C: return C if arg in self.extraColorsNS: return self.extraColorsNS[arg] C = getAllNamedColors() s = arg.lower() if s in C: return C[s] try: return toColor(eval(arg)) except: pass try: return HexColor(arg) except: if default is None: raise ValueError('Invalid color value %r' % arg) return default
def __call__(self,arg,default=None): '''try to map an arbitrary arg to a color instance ''' if isinstance(arg,Color): return arg if isinstance(arg,(tuple,list)): assert 3<=len(arg)<=4, 'Can only convert 3 and 4 sequences to color' assert 0<=min(arg) and max(arg)<=1 return len(arg)==3 and Color(arg[0],arg[1],arg[2]) or CMYKColor(arg[0],arg[1],arg[2],arg[3]) elif isStrType(arg): C = cssParse(arg) if C: return C if arg in self.extraColorsNS: return self.extraColorsNS[arg] C = getAllNamedColors() s = arg.lower() if s in C: return C[s] try: return toColor(eval(arg)) except: pass try: return HexColor(arg) except: if default is None: raise ValueError('Invalid color value %r' % arg) return default
def getImageData(self, preserveAspectRatio=False): "Gets data, height, width - whatever type of image" image = self.image if isStrType(image): self.filename = image if os.path.splitext(image)[1] in [ '.jpg', '.JPG', '.jpeg', '.JPEG' ]: try: imagedata, imgwidth, imgheight = self.jpg_imagedata() except: imagedata, imgwidth, imgheight = self.non_jpg_imagedata( image) #try for normal kind of image else: imagedata, imgwidth, imgheight = self.non_jpg_imagedata(image) else: import sys if sys.platform[0:4] == 'java': #jython, PIL not available imagedata, imgwidth, imgheight = self.JAVA_imagedata() else: imagedata, imgwidth, imgheight = self.PIL_imagedata() self.imageData = imagedata self.imgwidth = imgwidth self.imgheight = imgheight self.width = self.width or imgwidth self.height = self.height or imgheight
def _innerDrawLabel(self, rowNo, colNo, x, y): "Draw a label for a given item in the list." labelFmt = self.lineLabelFormat labelValue = self.data[rowNo][colNo][1] ### if labelFmt is None: labelText = None elif isStrType(labelFmt): if labelFmt == 'values': labelText = self.lineLabelArray[rowNo][colNo] else: labelText = labelFmt % labelValue elif hasattr(labelFmt,'__call__'): if not hasattr(labelFmt,'__labelFmtEX__'): labelText = labelFmt(labelValue) else: labelText = labelFmt(self,rowNo,colNo,x,y) else: raise ValueError("Unknown formatter type %s, expected string or function"%labelFmt) if labelText: label = self.lineLabels[(rowNo, colNo)] if not label.visible: return #hack to make sure labels are outside the bar if y > 0: label.setOrigin(x, y + self.lineLabelNudge) else: label.setOrigin(x, y - self.lineLabelNudge) label.setText(labelText) else: label = None return label
def HexColor(val, htmlOnly=False, alpha=False): """This function converts a hex string, or an actual integer number, into the corresponding color. E.g., in "#AABBCC" or 0xAABBCC, AA is the red, BB is the green, and CC is the blue (00-FF). An alpha value can also be given in the form #AABBCCDD or 0xAABBCCDD where DD is the alpha value. For completeness I assume that #aabbcc or 0xaabbcc are hex numbers otherwise a pure integer is converted as decimal rgb. If htmlOnly is true, only the #aabbcc form is allowed. >>> HexColor('#ffffff') Color(1,1,1,1) >>> HexColor('#FFFFFF') Color(1,1,1,1) >>> HexColor('0xffffff') Color(1,1,1,1) >>> HexColor('16777215') Color(1,1,1,1) An '0x' or '#' prefix is required for hex (as opposed to decimal): >>> HexColor('ffffff') Traceback (most recent call last): ValueError: invalid literal for int() with base 10: 'ffffff' >>> HexColor('#FFFFFF', htmlOnly=True) Color(1,1,1,1) >>> HexColor('0xffffff', htmlOnly=True) Traceback (most recent call last): ValueError: not a hex string >>> HexColor('16777215', htmlOnly=True) Traceback (most recent call last): ValueError: not a hex string """ #" for emacs if isStrType(val): b = 10 if val[:1] == '#': val = val[1:] b = 16 if len(val) == 8: alpha = True else: if htmlOnly: raise ValueError('not a hex string') if val[:2].lower() == '0x': b = 16 val = val[2:] if len(val) == 8: alpha = True val = int(val, b) if alpha: return Color((val >> 24) & 0xFF / 255.0, ((val >> 16) & 0xFF) / 255.0, ((val >> 8) & 0xFF) / 255.0, (val & 0xFF) / 255.0) return Color(((val >> 16) & 0xFF) / 255.0, ((val >> 8) & 0xFF) / 255.0, (val & 0xFF) / 255.0)
def test(self, x): if not isStrType(x): return False try: a, b, c, d = codecs.lookup(x) return True except LookupError: return False
def HexColor(val, htmlOnly=False, alpha=False): """This function converts a hex string, or an actual integer number, into the corresponding color. E.g., in "#AABBCC" or 0xAABBCC, AA is the red, BB is the green, and CC is the blue (00-FF). An alpha value can also be given in the form #AABBCCDD or 0xAABBCCDD where DD is the alpha value. For completeness I assume that #aabbcc or 0xaabbcc are hex numbers otherwise a pure integer is converted as decimal rgb. If htmlOnly is true, only the #aabbcc form is allowed. >>> HexColor('#ffffff') Color(1,1,1,1) >>> HexColor('#FFFFFF') Color(1,1,1,1) >>> HexColor('0xffffff') Color(1,1,1,1) >>> HexColor('16777215') Color(1,1,1,1) An '0x' or '#' prefix is required for hex (as opposed to decimal): >>> HexColor('ffffff') Traceback (most recent call last): ValueError: invalid literal for int() with base 10: 'ffffff' >>> HexColor('#FFFFFF', htmlOnly=True) Color(1,1,1,1) >>> HexColor('0xffffff', htmlOnly=True) Traceback (most recent call last): ValueError: not a hex string >>> HexColor('16777215', htmlOnly=True) Traceback (most recent call last): ValueError: not a hex string """ #" for emacs if isStrType(val): b = 10 if val[:1] == '#': val = val[1:] b = 16 if len(val) == 8: alpha = True else: if htmlOnly: raise ValueError('not a hex string') if val[:2].lower() == '0x': b = 16 val = val[2:] if len(val) == 8: alpha = True val = int(val,b) if alpha: return Color((val>>24)&0xFF/255.0,((val>>16)&0xFF)/255.0,((val>>8)&0xFF)/255.0,(val&0xFF)/255.0) return Color(((val>>16)&0xFF)/255.0,((val>>8)&0xFF)/255.0,(val&0xFF)/255.0)
def drawPageNumbers(canvas, style, pages, availWidth, availHeight, dot=' . '): ''' Draws pagestr on the canvas using the given style. If dot is None, pagestr is drawn at the current position in the canvas. If dot is a string, pagestr is drawn right-aligned. If the string is not empty, the gap is filled with it. ''' pages.sort() pagestr = ', '.join([str(p) for p, _ in pages]) x, y = canvas._curr_tx_info['cur_x'], canvas._curr_tx_info['cur_y'] fontSize = style.fontSize pagestrw = stringWidth(pagestr, style.fontName, fontSize) #if it's too long to fit, we need to shrink to fit in 10% increments. #it would be very hard to output multiline entries. #however, we impose a minimum size of 1 point as we don't want an #infinite loop. Ultimately we should allow a TOC entry to spill #over onto a second line if needed. freeWidth = availWidth - x while pagestrw > freeWidth and fontSize >= 1.0: fontSize = 0.9 * fontSize pagestrw = stringWidth(pagestr, style.fontName, fontSize) if isStrType(dot): if dot: dotw = stringWidth(dot, style.fontName, fontSize) dotsn = int((availWidth - x - pagestrw) / dotw) else: dotsn = dotw = 0 text = '%s%s' % (dotsn * dot, pagestr) newx = availWidth - dotsn * dotw - pagestrw pagex = availWidth - pagestrw elif dot is None: text = ', ' + pagestr newx = x pagex = newx else: raise TypeError( 'Argument dot should either be None or an instance of string.') tx = canvas.beginText(newx, y) tx.setFont(style.fontName, fontSize) tx.setFillColor(style.textColor) tx.textLine(text) canvas.drawText(tx) commaw = stringWidth(', ', style.fontName, fontSize) for p, key in pages: if not key: continue w = stringWidth(str(p), style.fontName, fontSize) canvas.linkRect('', key, (pagex, y, pagex + w, y + style.leading), relative=1) pagex += w + commaw
def save(self, fn=None): if isStrType(fn): f = open(fn, 'wb' if sys.version_info[0] == 3 else 'w') else: f = fn f.write(self.doc.toprettyxml(indent=" ",encoding=self.encoding)) if f is not fn: f.close()
def save(self, fn=None): if isStrType(fn): f = open(fn, 'wb' if sys.version_info[0] == 3 else 'w') else: f = fn f.write(self.doc.toprettyxml(indent=" ", encoding=self.encoding)) if f is not fn: f.close()
def drawPageNumbers(canvas, style, pages, availWidth, availHeight, dot=" . "): """ Draws pagestr on the canvas using the given style. If dot is None, pagestr is drawn at the current position in the canvas. If dot is a string, pagestr is drawn right-aligned. If the string is not empty, the gap is filled with it. """ pages.sort() pagestr = ", ".join([str(p) for p, _ in pages]) x, y = canvas._curr_tx_info["cur_x"], canvas._curr_tx_info["cur_y"] fontSize = style.fontSize pagestrw = stringWidth(pagestr, style.fontName, fontSize) # if it's too long to fit, we need to shrink to fit in 10% increments. # it would be very hard to output multiline entries. # however, we impose a minimum size of 1 point as we don't want an # infinite loop. Ultimately we should allow a TOC entry to spill # over onto a second line if needed. freeWidth = availWidth - x while pagestrw > freeWidth and fontSize >= 1.0: fontSize = 0.9 * fontSize pagestrw = stringWidth(pagestr, style.fontName, fontSize) if isStrType(dot): if dot: dotw = stringWidth(dot, style.fontName, fontSize) dotsn = int((availWidth - x - pagestrw) / dotw) else: dotsn = dotw = 0 text = "%s%s" % (dotsn * dot, pagestr) newx = availWidth - dotsn * dotw - pagestrw pagex = availWidth - pagestrw elif dot is None: text = ", " + pagestr newx = x pagex = newx else: raise TypeError("Argument dot should either be None or an instance of string.") tx = canvas.beginText(newx, y) tx.setFont(style.fontName, fontSize) tx.setFillColor(style.textColor) tx.textLine(text) canvas.drawText(tx) commaw = stringWidth(", ", style.fontName, fontSize) for p, key in pages: if not key: continue w = stringWidth(str(p), style.fontName, fontSize) canvas.linkRect("", key, (pagex, y, pagex + w, y + style.leading), relative=1) pagex += w + commaw
def _AsciiHexDecode(input): """Decodes input using ASCII-Hex coding. Not used except to provide a test of the inverse function.""" #strip out all whitespace if not isStrType(input): input = input.decode('utf-8') stripped = ''.join(input.split()) 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' return ''.join([chr(int(stripped[i:i+2],16)) for i in range(0,len(stripped),2)])
def _AsciiHexDecode(input): """Decodes input using ASCII-Hex coding. Not used except to provide a test of the inverse function.""" #strip out all whitespace if not isStrType(input): input = input.decode('utf-8') stripped = ''.join(input.split()) 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' return ''.join( [chr(int(stripped[i:i + 2], 16)) for i in range(0, len(stripped), 2)])
def _chooseEnforceColorSpace(enforceColorSpace): if enforceColorSpace is not None and not callable(enforceColorSpace): if isStrType(enforceColorSpace): enforceColorSpace=enforceColorSpace.upper() if enforceColorSpace=='CMYK': enforceColorSpace = _enforceCMYK elif enforceColorSpace=='RGB': enforceColorSpace = _enforceRGB elif enforceColorSpace=='SEP': enforceColorSpace = _enforceSEP elif enforceColorSpace=='SEP_BLACK': enforceColorSpace = _enforceSEP_BLACK elif enforceColorSpace=='SEP_CMYK': enforceColorSpace = _enforceSEP_CMYK else: raise ValueError('Invalid value for Canvas argument enforceColorSpace=%r' % enforceColorSpace) return enforceColorSpace
def textLines(self, stuff, trim=1): """prints multi-line or newlined strings, moving down. One comon use is to quote a multi-line block in your Python code; since this may be indented, by default it trims whitespace off each line and from the beginning; set trim=0 to preserve whitespace.""" if isStrType(stuff): lines = '\n'.split(stuff.strip()) if trim == 1: lines = [s.strip() for s in lines] elif isinstance(stuff, (tuple, list)): lines = stuff else: assert 1 == 0, "argument to textlines must be string,, list or tuple" # Output each line one at a time. This used to be a long-hand # copy of the textLine code, now called as a method. for line in lines: self.textLine(line)
def _chooseEnforceColorSpace(enforceColorSpace): if enforceColorSpace is not None and not callable(enforceColorSpace): if isStrType(enforceColorSpace): enforceColorSpace = enforceColorSpace.upper() if enforceColorSpace == 'CMYK': enforceColorSpace = _enforceCMYK elif enforceColorSpace == 'RGB': enforceColorSpace = _enforceRGB elif enforceColorSpace == 'SEP': enforceColorSpace = _enforceSEP elif enforceColorSpace == 'SEP_BLACK': enforceColorSpace = _enforceSEP_BLACK elif enforceColorSpace == 'SEP_CMYK': enforceColorSpace = _enforceSEP_CMYK else: raise ValueError( 'Invalid value for Canvas argument enforceColorSpace=%r' % enforceColorSpace) return enforceColorSpace
def textLines(self, stuff, trim=1): """prints multi-line or newlined strings, moving down. One comon use is to quote a multi-line block in your Python code; since this may be indented, by default it trims whitespace off each line and from the beginning; set trim=0 to preserve whitespace.""" if isStrType(stuff): lines = '\n'.split(stuff.strip()) if trim==1: lines = [s.strip() for s in lines] elif isinstance(stuff,(tuple,list)): lines = stuff else: assert 1==0, "argument to textlines must be string,, list or tuple" # Output each line one at a time. This used to be a long-hand # copy of the textLine code, now called as a method. for line in lines: self.textLine(line)
def handle_data(self,data): "Creates an intermediate representation of string segments." frag = copy.copy(self._stack[-1]) if hasattr(frag,'cbDefn'): kind = frag.cbDefn.kind if data: self._syntax_error('Only empty <%s> tag allowed' % kind) elif hasattr(frag,'_selfClosingTag'): if data!='': self._syntax_error('No content allowed in %s tag' % frag._selfClosingTag) return else: # if sub and super are both on they will cancel each other out if frag.sub == 1 and frag.super == 1: frag.sub = 0 frag.super = 0 if frag.sub: frag.rise = -frag.fontSize*subFraction frag.fontSize = max(frag.fontSize-sizeDelta,3) elif frag.super: frag.rise = frag.fontSize*superFraction frag.fontSize = max(frag.fontSize-sizeDelta,3) if frag.greek: frag.fontName = 'symbol' data = _greekConvert(data) # bold, italic, and underline frag.fontName = tt2ps(frag.fontName,frag.bold,frag.italic) #save our data if not isStrType(data): data = data.decode('utf-8') frag.text = data if hasattr(frag,'isBullet'): delattr(frag,'isBullet') self.bFragList.append(frag) else: self.fragList.append(frag)
def __init__(self, name, base=None): self.name = name self.frozen = 0 if name in standardEncodings: assert base is None, "Can't have a base encoding for a standard encoding" self.baseEncodingName = name self.vector = _fontdata.encodings[name] elif base == None: # assume based on the usual one self.baseEncodingName = defaultEncoding self.vector = _fontdata.encodings[defaultEncoding] elif isStrType(base): baseEnc = getEncoding(base) self.baseEncodingName = baseEnc.name self.vector = baseEnc.vector[:] elif isSeqType(base): self.baseEncodingName = defaultEncoding self.vector = base[:] elif isinstance(base, Encoding): # accept a vector self.baseEncodingName = base.name self.vector = base.vector[:]
def setNormalDate(self, normalDate): """ accepts date as scalar string/integer (yyyymmdd) or tuple (year, month, day, ...)""" if isinstance(normalDate,int): self.normalDate = normalDate elif isStrType(normalDate): try: self.normalDate = int(normalDate) except: m = _iso_re.match(normalDate) if m: self.setNormalDate(m.group(1)+m.group(2)+m.group(3)) else: raise NormalDateException("unable to setNormalDate(%s)" % repr(normalDate)) elif isinstance(normalDate,_DateSeqTypes): self.normalDate = int("%04d%02d%02d" % normalDate[:3]) elif isinstance(normalDate,NormalDate): self.normalDate = normalDate.normalDate elif isinstance(normalDate,(datetime.datetime,datetime.date)): self.normalDate = (normalDate.year*100+normalDate.month)*100+normalDate.day if not self._isValidNormalDate(self.normalDate): raise NormalDateException("unable to setNormalDate(%s)" % repr(normalDate))
def setStrokeColor(self, aColor, alpha=None): """Takes a color object, allowing colors to be referred to by name""" if self._enforceColorSpace: aColor = self._enforceColorSpace(aColor) if isinstance(aColor, CMYKColor): d = aColor.density c, m, y, k = (d * aColor.cyan, d * aColor.magenta, d * aColor.yellow, d * aColor.black) self._strokeColorObj = aColor name = self._checkSeparation(aColor) if name: self._code.append('/%s CS %s SCN' % (name, fp_str(d))) else: self._code.append('%s K' % fp_str(c, m, y, k)) elif isinstance(aColor, Color): rgb = (aColor.red, aColor.green, aColor.blue) self._strokeColorObj = aColor self._code.append('%s RG' % fp_str(rgb)) elif isinstance(aColor, (tuple, list)): l = len(aColor) if l == 3: self._strokeColorObj = aColor self._code.append('%s RG' % fp_str(aColor)) elif l == 4: self._fillColorObj = aColor self._code.append('%s K' % fp_str(aColor)) else: raise ValueError('Unknown color %r' % aColor) elif isStrType(aColor): self.setStrokeColor(toColor(aColor)) else: raise ValueError('Unknown color %r' % aColor) if alpha is not None: self.setStrokeAlpha(alpha) elif getattr(aColor, 'alpha', None) is not None: self.setStrokeAlpha(aColor.alpha)
def handle_nextPageTemplate(self,pt): '''On endPage change to the page template with name or index pt''' if isStrType(pt): if hasattr(self, '_nextPageTemplateCycle'): del self._nextPageTemplateCycle for t in self.pageTemplates: if t.id == pt: self._nextPageTemplateIndex = self.pageTemplates.index(t) return raise ValueError("can't find template('%s')"%pt) elif type(pt) is int: if hasattr(self, '_nextPageTemplateCycle'): del self._nextPageTemplateCycle self._nextPageTemplateIndex = pt elif isSeqType(pt): #used for alternating left/right pages #collect the refs to the template objects, complain if any are bad c = PTCycle() for ptn in pt: found = 0 if ptn=='*': #special case name used to short circuit the iteration c._restart = len(c) continue for t in self.pageTemplates: if t.id == ptn: c.append(t) found = 1 if not found: raise ValueError("Cannot find page template called %s" % ptn) if not c: raise ValueError("No valid page templates in cycle") elif c._restart>len(c): raise ValueError("Invalid cycle restart position") #ensure we start on the first one self._nextPageTemplateCycle = c.cyclicIterator() else: raise TypeError("argument pt should be string or integer or list")
def test(self, x): if not (isStrType(x) or type(x) is int): return False return self.normalizeTest(x)
def __init__(self, template, wild_card_marker=None, single_char_marker=None, **marker_to_regex_dict): self.template = template self.wild_card = wild_card_marker self.char = single_char_marker # determine the set of markers for this template markers = list(marker_to_regex_dict.keys()) if wild_card_marker: markers.append(wild_card_marker) if single_char_marker: for ch in single_char_marker: # allow multiple scm's markers.append(ch) self.char = single_char_primary = single_char_marker[0] self.markers = markers for mark in markers: if len(mark)>1: raise ValueError("Marks must be single characters: "+repr(mark)) # compile the regular expressions if needed self.marker_dict = marker_dict = {} for (mark, rgex) in marker_to_regex_dict.items(): if isStrType(rgex): rgex = re.compile(rgex) marker_dict[mark] = rgex # determine the parse sequence parse_seq = [] # dummy last char lastchar = None index = 0 last = len(template) # count the number of directives encountered ndirectives = 0 while index<last: start = index thischar = template[index] # is it a wildcard? if thischar == wild_card_marker: if lastchar == wild_card_marker: raise ValueError("two wild cards in sequence is not allowed") parse_seq.append( (wild_card_marker, None) ) index = index+1 ndirectives = ndirectives+1 # is it a sequence of single character markers? elif single_char_marker and thischar in single_char_marker: if lastchar == wild_card_marker: raise ValueError("wild card cannot precede single char marker") while index<last and template[index] == thischar: index = index+1 parse_seq.append( (single_char_primary, index-start) ) ndirectives = ndirectives+1 # is it a literal sequence? elif not thischar in markers: while index<last and not template[index] in markers: index = index+1 parse_seq.append( (None, template[start:index]) ) # otherwise it must be a re marker else: rgex = marker_dict[thischar] parse_seq.append( (thischar, rgex) ) ndirectives = ndirectives+1 index = index+1 lastchar = template[index-1] self.parse_seq = parse_seq self.ndirectives = ndirectives
def test(self, x): return isStrType(x)
def _AsciiBase85EncodePYTHON(input): """Encodes input using ASCII-Base85 coding. This is a compact encoding used for binary data within a PDF file. Four bytes of binary data become five bytes of ASCII. This is the default method used for encoding images.""" # special rules apply if not a multiple of four bytes. whole_word_count, remainder_size = divmod(len(input), 4) cut = 4 * whole_word_count body, lastbit = input[0:cut], input[cut:] if sys.version_info[0] == 3 and isStrType(lastbit): lastbit = lastbit.encode('utf-8') out = [].append for i in range(whole_word_count): offset = i * 4 b1 = body[offset] b2 = body[offset + 1] b3 = body[offset + 2] b4 = body[offset + 3] if isStrType(b1): b1 = ord(b1) if isStrType(b2): b2 = ord(b2) if isStrType(b3): b3 = ord(b3) if isStrType(b4): b4 = ord(b4) if b1 < 128: num = (((((b1 << 8) | b2) << 8) | b3) << 8) | b4 else: num = 16777216 * b1 + 65536 * b2 + 256 * b3 + b4 if num == 0: #special case out('z') else: #solve for five base-85 numbers temp, c5 = divmod(num, 85) temp, c4 = divmod(temp, 85) temp, c3 = divmod(temp, 85) c1, c2 = divmod(temp, 85) assert ((85**4) * c1) + ((85**3) * c2) + ( (85**2) * c3) + (85 * c4) + c5 == num, 'dodgy code!' out(chr(c1 + 33)) out(chr(c2 + 33)) out(chr(c3 + 33)) out(chr(c4 + 33)) out(chr(c5 + 33)) # now we do the final bit at the end. I repeated this separately as # the loop above is the time-critical part of a script, whereas this # happens only once at the end. #encode however many bytes we have as usual if remainder_size > 0: while len(lastbit) < 4: lastbit = lastbit + b'\000' b1 = lastbit[0] b2 = lastbit[1] b3 = lastbit[2] b4 = lastbit[3] if isStrType(b1): b1 = ord(b1) if isStrType(b2): b2 = ord(b2) if isStrType(b3): b3 = ord(b3) if isStrType(b4): b4 = ord(b4) num = 16777216 * b1 + 65536 * b2 + 256 * b3 + b4 #solve for c1..c5 temp, c5 = divmod(num, 85) temp, c4 = divmod(temp, 85) temp, c3 = divmod(temp, 85) c1, c2 = divmod(temp, 85) #print 'encoding: %d %d %d %d -> %d -> %d %d %d %d %d' % ( # b1,b2,b3,b4,num,c1,c2,c3,c4,c5) lastword = chr(c1 + 33) + chr(c2 + 33) + chr(c3 + 33) + chr( c4 + 33) + chr(c5 + 33) #write out most of the bytes. out(lastword[0:remainder_size + 1]) #terminator code for ascii 85 out('~>') return ''.join(out.__self__)
def _AsciiBase85EncodePYTHON(input): """Encodes input using ASCII-Base85 coding. This is a compact encoding used for binary data within a PDF file. Four bytes of binary data become five bytes of ASCII. This is the default method used for encoding images.""" # special rules apply if not a multiple of four bytes. whole_word_count, remainder_size = divmod(len(input), 4) cut = 4 * whole_word_count body, lastbit = input[0:cut], input[cut:] if sys.version_info[0] == 3 and isStrType(lastbit): lastbit = lastbit.encode('utf-8') out = [].append for i in range(whole_word_count): offset = i*4 b1 = body[offset] b2 = body[offset+1] b3 = body[offset+2] b4 = body[offset+3] if isStrType(b1): b1 = ord(b1) if isStrType(b2): b2 = ord(b2) if isStrType(b3): b3 = ord(b3) if isStrType(b4): b4 = ord(b4) if b1<128: num = (((((b1<<8)|b2)<<8)|b3)<<8)|b4 else: num = 16777216 * b1 + 65536 * b2 + 256 * b3 + b4 if num == 0: #special case out('z') else: #solve for five base-85 numbers temp, c5 = divmod(num, 85) temp, c4 = divmod(temp, 85) temp, c3 = divmod(temp, 85) c1, c2 = divmod(temp, 85) assert ((85**4) * c1) + ((85**3) * c2) + ((85**2) * c3) + (85*c4) + c5 == num, 'dodgy code!' out(chr(c1+33)) out(chr(c2+33)) out(chr(c3+33)) out(chr(c4+33)) out(chr(c5+33)) # now we do the final bit at the end. I repeated this separately as # the loop above is the time-critical part of a script, whereas this # happens only once at the end. #encode however many bytes we have as usual if remainder_size > 0: while len(lastbit) < 4: lastbit = lastbit + b'\000' b1 = lastbit[0] b2 = lastbit[1] b3 = lastbit[2] b4 = lastbit[3] if isStrType(b1): b1 = ord(b1) if isStrType(b2): b2 = ord(b2) if isStrType(b3): b3 = ord(b3) if isStrType(b4): b4 = ord(b4) num = 16777216 * b1 + 65536 * b2 + 256 * b3 + b4 #solve for c1..c5 temp, c5 = divmod(num, 85) temp, c4 = divmod(temp, 85) temp, c3 = divmod(temp, 85) c1, c2 = divmod(temp, 85) #print 'encoding: %d %d %d %d -> %d -> %d %d %d %d %d' % ( # b1,b2,b3,b4,num,c1,c2,c3,c4,c5) lastword = chr(c1+33) + chr(c2+33) + chr(c3+33) + chr(c4+33) + chr(c5+33) #write out most of the bytes. out(lastword[0:remainder_size + 1]) #terminator code for ascii 85 out('~>') return ''.join(out.__self__)
def __init__(self, template, wild_card_marker=None, single_char_marker=None, **marker_to_regex_dict): self.template = template self.wild_card = wild_card_marker self.char = single_char_marker # determine the set of markers for this template markers = list(marker_to_regex_dict.keys()) if wild_card_marker: markers.append(wild_card_marker) if single_char_marker: for ch in single_char_marker: # allow multiple scm's markers.append(ch) self.char = single_char_primary = single_char_marker[0] self.markers = markers for mark in markers: if len(mark) > 1: raise ValueError("Marks must be single characters: " + repr(mark)) # compile the regular expressions if needed self.marker_dict = marker_dict = {} for (mark, rgex) in marker_to_regex_dict.items(): if isStrType(rgex): rgex = re.compile(rgex) marker_dict[mark] = rgex # determine the parse sequence parse_seq = [] # dummy last char lastchar = None index = 0 last = len(template) # count the number of directives encountered ndirectives = 0 while index < last: start = index thischar = template[index] # is it a wildcard? if thischar == wild_card_marker: if lastchar == wild_card_marker: raise ValueError( "two wild cards in sequence is not allowed") parse_seq.append((wild_card_marker, None)) index = index + 1 ndirectives = ndirectives + 1 # is it a sequence of single character markers? elif single_char_marker and thischar in single_char_marker: if lastchar == wild_card_marker: raise ValueError( "wild card cannot precede single char marker") while index < last and template[index] == thischar: index = index + 1 parse_seq.append((single_char_primary, index - start)) ndirectives = ndirectives + 1 # is it a literal sequence? elif not thischar in markers: while index < last and not template[index] in markers: index = index + 1 parse_seq.append((None, template[start:index])) # otherwise it must be a re marker else: rgex = marker_dict[thischar] parse_seq.append((thischar, rgex)) ndirectives = ndirectives + 1 index = index + 1 lastchar = template[index - 1] self.parse_seq = parse_seq self.ndirectives = ndirectives
def docAssign(self,var,expr,lifetime): if not isStrType(expr): expr=str(expr) expr=expr.strip() var=var.strip() self.docExec('%s=(%s)'%(var.strip(),expr.strip()),lifetime)
canvas.rect(xx,yy,ddW,ddH, fill=1, stroke=1) canvas.setFillGray(0) canvas.drawString(xx+dd/2.0,yy+dd/2.0, "flowable %s" %(157-i)) yy = yy+ddH+dd canvas.drawCentredString(3*Wd+2*W+W/2, Hd+H/2.0, "First Flowable") canvas.setFont("Times-BoldItalic", 8) canvas.setFillGray(0) canvas.drawCentredString(mx+mW/2.0, my+mH+3*dd, "Chapter 6: Lubricants") canvas.setFont("Times-BoldItalic", 10) canvas.drawCentredString(3*Wd+2*W+W/2, Hd+H-H/4, "College Life") # D = dir() g = globals() Dprime = {} for (a,b) in list(g.items()): if a[:4]=="test" and isStrType(b): b = b.strip() exec(b+'\n') platypussetup = """ from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer from reportlab.lib.styles import getSampleStyleSheet from reportlab.rl_config import defaultPageSize from reportlab.lib.units import inch PAGE_HEIGHT=defaultPageSize[1]; PAGE_WIDTH=defaultPageSize[0] styles = getSampleStyleSheet() """ platypusfirstpage = """ Title = "Hello world" pageinfo = "platypus example" def myFirstPage(canvas, doc):