bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def nolog(*allargs): """Dummy function, assigned to log when logging is disabled.""" pass
def nolog(*allargs): """Dummy function, assigned to log when logging is disabled.""" pass
11,500
def parse_multipart(fp, pdict): """Parse multipart input. Arguments: fp : input file pdict: dictionary containing other parameters of content-type header Returns a dictionary just like parse_qs(): keys are the field names, each value is a list of values for that field. This is easy to use but not much good if you are expecting megabytes to be uploaded -- in that case, use the FieldStorage class instead which is much more flexible. Note that content-type is the raw, unparsed contents of the content-type header. XXX This does not parse nested multipart parts -- use FieldStorage for that. XXX This should really be subsumed by FieldStorage altogether -- no point in having two implementations of the same parsing algorithm. """ boundary = "" if 'boundary' in pdict: boundary = pdict['boundary'] if not valid_boundary(boundary): raise ValueError, ('Invalid boundary in multipart form: %r' % (boundary,)) nextpart = "--" + boundary lastpart = "--" + boundary + "--" partdict = {} terminator = "" while terminator != lastpart: bytes = -1 data = None if terminator: # At start of next part. Read headers first. headers = _header_parser.parse(fp) clength = headers.getheader('content-length') if clength: try: bytes = int(clength) except ValueError: pass if bytes > 0: if maxlen and bytes > maxlen: raise ValueError, 'Maximum content length exceeded' data = fp.read(bytes) else: data = "" # Read lines until end of part. lines = [] while 1: line = fp.readline() if not line: terminator = lastpart # End outer loop break if line[:2] == "--": terminator = line.strip() if terminator in (nextpart, lastpart): break lines.append(line) # Done with part. if data is None: continue if bytes < 0: if lines: # Strip final line terminator line = lines[-1] if line[-2:] == "\r\n": line = line[:-2] elif line[-1:] == "\n": line = line[:-1] lines[-1] = line data = "".join(lines) line = headers['content-disposition'] if not line: continue key, params = parse_header(line) if key != 'form-data': continue if 'name' in params: name = params['name'] else: continue if name in partdict: partdict[name].append(data) else: partdict[name] = [data] return partdict
def parse_multipart(fp, pdict): """Parse multipart input. Arguments: fp : input file pdict: dictionary containing other parameters of content-type header Returns a dictionary just like parse_qs(): keys are the field names, each value is a list of values for that field. This is easy to use but not much good if you are expecting megabytes to be uploaded -- in that case, use the FieldStorage class instead which is much more flexible. Note that content-type is the raw, unparsed contents of the content-type header. XXX This does not parse nested multipart parts -- use FieldStorage for that. XXX This should really be subsumed by FieldStorage altogether -- no point in having two implementations of the same parsing algorithm. """ boundary = "" if 'boundary' in pdict: boundary = pdict['boundary'] if not valid_boundary(boundary): raise ValueError, ('Invalid boundary in multipart form: %r' % (boundary,)) nextpart = "--" + boundary lastpart = "--" + boundary + "--" partdict = {} terminator = "" while terminator != lastpart: bytes = -1 data = None if terminator: # At start of next part. Read headers first. headers = mimetools.Message(fp) clength = headers.getheader('content-length') if clength: try: bytes = int(clength) except ValueError: pass if bytes > 0: if maxlen and bytes > maxlen: raise ValueError, 'Maximum content length exceeded' data = fp.read(bytes) else: data = "" # Read lines until end of part. lines = [] while 1: line = fp.readline() if not line: terminator = lastpart # End outer loop break if line[:2] == "--": terminator = line.strip() if terminator in (nextpart, lastpart): break lines.append(line) # Done with part. if data is None: continue if bytes < 0: if lines: # Strip final line terminator line = lines[-1] if line[-2:] == "\r\n": line = line[:-2] elif line[-1:] == "\n": line = line[:-1] lines[-1] = line data = "".join(lines) line = headers['content-disposition'] if not line: continue key, params = parse_header(line) if key != 'form-data': continue if 'name' in params: name = params['name'] else: continue if name in partdict: partdict[name].append(data) else: partdict[name] = [data] return partdict
11,501
def __repr__(self): """Return printable representation.""" return "MiniFieldStorage(%r, %r)" % (self.name, self.value)
def __repr__(self): """Return printable representation.""" return "MiniFieldStorage(%r, %r)" % (self.name, self.value)
11,502
def read_multi(self, environ, keep_blank_values, strict_parsing): """Internal: read a part that is itself multipart.""" ib = self.innerboundary if not valid_boundary(ib): raise ValueError, 'Invalid boundary in multipart form: %r' % (ib,) self.list = [] klass = self.FieldStorageClass or self.__class__ part = klass(self.fp, {}, ib, environ, keep_blank_values, strict_parsing) # Throw first part away while not part.done: headers = _header_parser.parse(self.fp) part = klass(self.fp, headers, ib, environ, keep_blank_values, strict_parsing) self.list.append(part) self.skip_lines()
def read_multi(self, environ, keep_blank_values, strict_parsing): """Internal: read a part that is itself multipart.""" ib = self.innerboundary if not valid_boundary(ib): raise ValueError, 'Invalid boundary in multipart form: %r' % (ib,) self.list = [] klass = self.FieldStorageClass or self.__class__ part = klass(self.fp, {}, ib, environ, keep_blank_values, strict_parsing) # Throw first part away while not part.done: headers = rfc822.Message(self.fp) part = klass(self.fp, headers, ib, environ, keep_blank_values, strict_parsing) self.list.append(part) self.skip_lines()
11,503
def maybe(*choices): return apply(group, choices) + '?'
def maybe(*choices): return apply(group, choices) + '?'
11,504
def maybe(*choices): return apply(group, choices) + '?'
def maybe(*choices): return apply(group, choices) + '?'
11,505
def maybe(*choices): return apply(group, choices) + '?'
def maybe(*choices): return apply(group, choices) + '?'
11,506
def readlines(self, sizehint=None):
def readlines(self, sizehint=None):
11,507
def readlines(self, sizehint=None):
def readlines(self, sizehint=None):
11,508
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" file = getsourcefile(object) or getfile(object) module = getmodule(object, file) if module: lines = linecache.getlines(file, module.__dict__) else: lines = linecache.getlines(file) if not lines: raise IOError('could not get source code') if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ pat = re.compile(r'^\s*class\s*' + name + r'\b') for i in range(len(lines)): if pat.match(lines[i]): return lines, i else: raise IOError('could not find class definition') if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise IOError('could not find function definition') lnum = object.co_firstlineno - 1 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') while lnum > 0: if pat.match(lines[lnum]): break lnum = lnum - 1 return lines, lnum raise IOError('could not find code object')
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" file = getsourcefile(object) or getfile(object) module = getmodule(object, file) if module: lines = linecache.getlines(file, module.__dict__) else: lines = linecache.getlines(file) if not lines: raise IOError('could not get source code') if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ pat = re.compile(r'^(\s*)class\s*' + name + r'\b') candidates = [] for i in range(len(lines)): if pat.match(lines[i]): return lines, i else: raise IOError('could not find class definition') if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise IOError('could not find function definition') lnum = object.co_firstlineno - 1 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') while lnum > 0: if pat.match(lines[lnum]): break lnum = lnum - 1 return lines, lnum raise IOError('could not find code object')
11,509
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" file = getsourcefile(object) or getfile(object) module = getmodule(object, file) if module: lines = linecache.getlines(file, module.__dict__) else: lines = linecache.getlines(file) if not lines: raise IOError('could not get source code') if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ pat = re.compile(r'^\s*class\s*' + name + r'\b') for i in range(len(lines)): if pat.match(lines[i]): return lines, i else: raise IOError('could not find class definition') if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise IOError('could not find function definition') lnum = object.co_firstlineno - 1 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') while lnum > 0: if pat.match(lines[lnum]): break lnum = lnum - 1 return lines, lnum raise IOError('could not find code object')
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" file = getsourcefile(object) or getfile(object) module = getmodule(object, file) if module: lines = linecache.getlines(file, module.__dict__) else: lines = linecache.getlines(file) if not lines: raise IOError('could not get source code') if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ pat = re.compile(r'^\s*class\s*' + name + r'\b') for i in range(len(lines)): match = pat.match(lines[i]) if match: if lines[i][0] == 'c': return lines, i candidates.append((match.group(1), i)) if candidates: candidates.sort() return lines, candidates[0][1] else: raise IOError('could not find class definition') if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise IOError('could not find function definition') lnum = object.co_firstlineno - 1 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') while lnum > 0: if pat.match(lines[lnum]): break lnum = lnum - 1 return lines, lnum raise IOError('could not find code object')
11,510
def __init__(self): self.childNodes = [] self.parentNode = None if Node._debug: index = repr(id(self)) + repr(self.__class__) Node.allnodes[index] = repr(self.__dict__) if Node.debug is None: Node.debug = _get_StringIO() #open( "debug4.out", "w" ) Node.debug.write("create %s\n" % index)
def __init__(self): self.childNodes = [] self.parentNode = None if Node._debug: index = repr(id(self)) + repr(self.__class__) Node.allnodes[index] = repr(self.__dict__) if Node.debug is None: Node.debug = _get_StringIO() #open( "debug4.out", "w" ) Node.debug.write("create %s\n" % index)
11,511
def insertBefore(self, newChild, refChild): if newChild.nodeType not in self.childNodeTypes: raise HierarchyRequestErr, \ "%s cannot be child of %s" % (repr(newChild), repr(self) ) if newChild.parentNode is not None: newChild.parentNode.removeChild(newChild) if refChild is None: self.appendChild(newChild) else: index = self.childNodes.index(refChild) self.childNodes.insert(index, newChild) newChild.nextSibling = refChild refChild.previousSibling = newChild if index: node = self.childNodes[index-1] node.nextSibling = newChild newChild.previousSibling = node else: newChild.previousSibling = None if self._makeParentNodes: newChild.parentNode = self return newChild
def insertBefore(self, newChild, refChild): if newChild.nodeType not in self.childNodeTypes: raise HierarchyRequestErr, \ "%s cannot be child of %s" % (repr(newChild), repr(self)) if newChild.parentNode is not None: newChild.parentNode.removeChild(newChild) if refChild is None: self.appendChild(newChild) else: index = self.childNodes.index(refChild) self.childNodes.insert(index, newChild) newChild.nextSibling = refChild refChild.previousSibling = newChild if index: node = self.childNodes[index-1] node.nextSibling = newChild newChild.previousSibling = node else: newChild.previousSibling = None if self._makeParentNodes: newChild.parentNode = self return newChild
11,512
def appendChild(self, node): if node.nodeType not in self.childNodeTypes: raise HierarchyRequestErr, \ "%s cannot be child of %s" % (repr(node), repr(self) ) if node.parentNode is not None: node.parentNode.removeChild(node) if self.childNodes: last = self.lastChild node.previousSibling = last last.nextSibling = node else: node.previousSibling = None node.nextSibling = None self.childNodes.append(node) if self._makeParentNodes: node.parentNode = self return node
def appendChild(self, node): if node.nodeType not in self.childNodeTypes: raise HierarchyRequestErr, \ "%s cannot be child of %s" % (repr(node), repr(self)) if node.parentNode is not None: node.parentNode.removeChild(node) if self.childNodes: last = self.lastChild node.previousSibling = last last.nextSibling = node else: node.previousSibling = None node.nextSibling = None self.childNodes.append(node) if self._makeParentNodes: node.parentNode = self return node
11,513
def replaceChild(self, newChild, oldChild): if newChild.nodeType not in self.childNodeTypes: raise HierarchyRequestErr, \ "%s cannot be child of %s" % (repr(newChild), repr(self) ) if newChild.parentNode is not None: newChild.parentNode.removeChild(newChild) if newChild is oldChild: return index = self.childNodes.index(oldChild) self.childNodes[index] = newChild if self._makeParentNodes: newChild.parentNode = self oldChild.parentNode = None newChild.nextSibling = oldChild.nextSibling newChild.previousSibling = oldChild.previousSibling oldChild.nextSibling = None oldChild.previousSibling = None if newChild.previousSibling: newChild.previousSibling.nextSibling = newChild if newChild.nextSibling: newChild.nextSibling.previousSibling = newChild return oldChild
def replaceChild(self, newChild, oldChild): if newChild.nodeType not in self.childNodeTypes: raise HierarchyRequestErr, \ "%s cannot be child of %s" % (repr(newChild), repr(self)) if newChild.parentNode is not None: newChild.parentNode.removeChild(newChild) if newChild is oldChild: return index = self.childNodes.index(oldChild) self.childNodes[index] = newChild if self._makeParentNodes: newChild.parentNode = self oldChild.parentNode = None newChild.nextSibling = oldChild.nextSibling newChild.previousSibling = oldChild.previousSibling oldChild.nextSibling = None oldChild.previousSibling = None if newChild.previousSibling: newChild.previousSibling.nextSibling = newChild if newChild.nextSibling: newChild.nextSibling.previousSibling = newChild return oldChild
11,514
def getAttribute(self, attname): return self._attrs[attname].value
def getAttribute(self, attname): return self._attrs[attname].value
11,515
def getAttributeNS(self, namespaceURI, localName): return self._attrsNS[(namespaceURI, localName)].value
def getAttributeNS(self, namespaceURI, localName): return self._attrsNS[(namespaceURI, localName)].value
11,516
def getAttributeNodeNS(self, namespaceURI, localName): return self._attrsNS[(namespaceURI, localName)]
def getAttributeNodeNS(self, namespaceURI, localName): return self._attrsNS[(namespaceURI, localName)]
11,517
def createDocument(self, namespaceURI, qualifiedName, doctype): if doctype and doctype.parentNode is not None: raise xml.dom.WrongDocumentErr("doctype object owned by another DOM tree") doc = Document() if doctype is None: doctype = self.createDocumentType(qualifiedName, None, None) if qualifiedName: prefix, localname = _nssplit(qualifiedName) if prefix == "xml" \ and namespaceURI != "http://www.w3.org/XML/1998/namespace": raise xml.dom.NamespaceErr("illegal use of 'xml' prefix") if prefix and not namespaceURI: raise xml.dom.NamespaceErr("illegal use of prefix without namespaces") doctype.parentNode = doc doc.doctype = doctype doc.implementation = self return doc
def createDocument(self, namespaceURI, qualifiedName, doctype): if doctype and doctype.parentNode is not None: raise xml.dom.WrongDocumentErr( "doctype object owned by another DOM tree") doc = Document() if doctype is None: doctype = self.createDocumentType(qualifiedName, None, None) if qualifiedName: prefix, localname = _nssplit(qualifiedName) if prefix == "xml" \ and namespaceURI != "http://www.w3.org/XML/1998/namespace": raise xml.dom.NamespaceErr("illegal use of 'xml' prefix") if prefix and not namespaceURI: raise xml.dom.NamespaceErr("illegal use of prefix without namespaces") doctype.parentNode = doc doc.doctype = doctype doc.implementation = self return doc
11,518
def createDocument(self, namespaceURI, qualifiedName, doctype): if doctype and doctype.parentNode is not None: raise xml.dom.WrongDocumentErr("doctype object owned by another DOM tree") doc = Document() if doctype is None: doctype = self.createDocumentType(qualifiedName, None, None) if qualifiedName: prefix, localname = _nssplit(qualifiedName) if prefix == "xml" \ and namespaceURI != "http://www.w3.org/XML/1998/namespace": raise xml.dom.NamespaceErr("illegal use of 'xml' prefix") if prefix and not namespaceURI: raise xml.dom.NamespaceErr("illegal use of prefix without namespaces") doctype.parentNode = doc doc.doctype = doctype doc.implementation = self return doc
def createDocument(self, namespaceURI, qualifiedName, doctype): if doctype and doctype.parentNode is not None: raise xml.dom.WrongDocumentErr("doctype object owned by another DOM tree") doc = Document() if doctype is None: doctype = self.createDocumentType(qualifiedName, None, None) if qualifiedName: prefix, localname = _nssplit(qualifiedName) if prefix == "xml" \ and namespaceURI != "http://www.w3.org/XML/1998/namespace": raise xml.dom.NamespaceErr("illegal use of 'xml' prefix") if prefix and not namespaceURI: raise xml.dom.NamespaceErr( "illegal use of prefix without namespaces") element = doc.createElementNS(namespaceURI, qualifiedName) doc.appendChild(element) doctype.parentNode = doc doc.doctype = doctype doc.implementation = self return doc
11,519
def appendChild(self, node): if node.nodeType not in self.childNodeTypes: raise HierarchyRequestErr, \ "%s cannot be child of %s" % (repr(node), repr(self) ) if node.parentNode is not None: node.parentNode.removeChild(node)
def appendChild(self, node): if node.nodeType not in self.childNodeTypes: raise HierarchyRequestErr, \ "%s cannot be child of %s" % (repr(node), repr(self)) if node.parentNode is not None: node.parentNode.removeChild(node)
11,520
def appendChild(self, node): if node.nodeType not in self.childNodeTypes: raise HierarchyRequestErr, \ "%s cannot be child of %s" % (repr(node), repr(self) ) if node.parentNode is not None: node.parentNode.removeChild(node)
def appendChild(self, node): if node.nodeType not in self.childNodeTypes: raise HierarchyRequestErr, \ "%s cannot be child of %s" % (repr(node), repr(self) ) if node.parentNode is not None: node.parentNode.removeChild(node)
11,521
def _center(str, width): """Center a string in a field.""" n = width - len(str) if n <= 0: return str return ' '*((n+1)/2) + str + ' '*((n)/2)
def _center(str, width): """Center a string in a field.""" n = width - len(str) if n <= 0: return str return ' '*((n+1)/2) + str + ' '*((n)/2)
11,522
def week(theweek, width): """Returns a single week in a string (no newline).""" days = [] for day in theweek: if day == 0: s = '' else: s = '%2i' % day # right-align single-digit days days.append(_center(s, width)) return ' '.join(days)
def week(theweek, width): """Returns a single week in a string (no newline).""" days = [] for day in theweek: if day == 0: s = '' else: s = '%2i' % day # right-align single-digit days days.append(s.center(width)) return ' '.join(days)
11,523
def weekheader(width): """Return a header for a week.""" if width >= 9: names = day_name else: names = day_abbr days = [] for i in range(_firstweekday, _firstweekday + 7): days.append(_center(names[i%7][:width], width)) return ' '.join(days)
def weekheader(width): """Return a header for a week.""" if width >= 9: names = day_name else: names = day_abbr days = [] for i in range(_firstweekday, _firstweekday + 7): days.append(names[i%7][:width].center(width)) return ' '.join(days)
11,524
def month(theyear, themonth, w=0, l=0): """Return a month's calendar string (multi-line).""" w = max(2, w) l = max(1, l) s = (_center(month_name[themonth] + ' ' + `theyear`, 7 * (w + 1) - 1).rstrip() + '\n' * l + weekheader(w).rstrip() + '\n' * l) for aweek in monthcalendar(theyear, themonth): s = s + week(aweek, w).rstrip() + '\n' * l return s[:-l] + '\n'
def month(theyear, themonth, w=0, l=0): """Return a month's calendar string (multi-line).""" w = max(2, w) l = max(1, l) s = ((month_name[themonth] + ' ' + `theyear`).center( 7 * (w + 1) - 1).rstrip() + '\n' * l + weekheader(w).rstrip() + '\n' * l) for aweek in monthcalendar(theyear, themonth): s = s + week(aweek, w).rstrip() + '\n' * l return s[:-l] + '\n'
11,525
def format3cstring(a, b, c, colwidth=_colwidth, spacing=_spacing): """Returns a string formatted from 3 strings, centered within 3 columns.""" return (_center(a, colwidth) + ' ' * spacing + _center(b, colwidth) + ' ' * spacing + _center(c, colwidth))
def format3cstring(a, b, c, colwidth=_colwidth, spacing=_spacing): """Returns a string formatted from 3 strings, centered within 3 columns.""" return (a.center(colwidth) + ' ' * spacing + b.center(colwidth) + ' ' * spacing + c.center(colwidth))
11,526
def calendar(year, w=0, l=0, c=_spacing): """Returns a year's calendar as a multi-line string.""" w = max(2, w) l = max(1, l) c = max(2, c) colwidth = (w + 1) * 7 - 1 s = _center(`year`, colwidth * 3 + c * 2).rstrip() + '\n' * l header = weekheader(w) header = format3cstring(header, header, header, colwidth, c).rstrip() for q in range(January, January+12, 3): s = (s + '\n' * l + format3cstring(month_name[q], month_name[q+1], month_name[q+2], colwidth, c).rstrip() + '\n' * l + header + '\n' * l) data = [] height = 0 for amonth in range(q, q + 3): cal = monthcalendar(year, amonth) if len(cal) > height: height = len(cal) data.append(cal) for i in range(height): weeks = [] for cal in data: if i >= len(cal): weeks.append('') else: weeks.append(week(cal[i], w)) s = s + format3cstring(weeks[0], weeks[1], weeks[2], colwidth, c).rstrip() + '\n' * l return s[:-l] + '\n'
def calendar(year, w=0, l=0, c=_spacing): """Returns a year's calendar as a multi-line string.""" w = max(2, w) l = max(1, l) c = max(2, c) colwidth = (w + 1) * 7 - 1 s = `year`.center(colwidth * 3 + c * 2).rstrip() + '\n' * l header = weekheader(w) header = format3cstring(header, header, header, colwidth, c).rstrip() for q in range(January, January+12, 3): s = (s + '\n' * l + format3cstring(month_name[q], month_name[q+1], month_name[q+2], colwidth, c).rstrip() + '\n' * l + header + '\n' * l) data = [] height = 0 for amonth in range(q, q + 3): cal = monthcalendar(year, amonth) if len(cal) > height: height = len(cal) data.append(cal) for i in range(height): weeks = [] for cal in data: if i >= len(cal): weeks.append('') else: weeks.append(week(cal[i], w)) s = s + format3cstring(weeks[0], weeks[1], weeks[2], colwidth, c).rstrip() + '\n' * l return s[:-l] + '\n'
11,527
def connect(self, host, *args): if args: if args[1:]: raise TypeError, 'too many args' port = args[0] else: i = string.find(host, ':') if i >= 0: host, port = host[:i], host[i+1:] try: port = string.atoi(port) except string.atoi_error: port = None if not port: port = HTTP_PORT self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if self.debuglevel > 0: print 'connect:', (host, port) self.sock.connect(host, port)
def connect(self, host, *args): if args: if args[1:]: raise TypeError, 'too many args' port = args[0] else: i = string.find(host, ':') if i >= 0: host, port = host[:i], host[i+1:] try: port = string.atoi(port) except string.atoi_error: pass if not port: port = HTTP_PORT self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if self.debuglevel > 0: print 'connect:', (host, port) self.sock.connect(host, port)
11,528
def open_module(self, event=None): # XXX Shouldn't this be in IOBinding or in FileList? try: name = self.text.get("sel.first", "sel.last") except TclError: name = "" else: name = string.strip(name) if not name: name = tkSimpleDialog.askstring("Module", "Enter the name of a Python module\n" "to search on sys.path and open:", parent=self.text) if name: name = string.strip(name) if not name: return # XXX Ought to support package syntax # XXX Ought to insert current file's directory in front of path try: (f, file, (suffix, mode, type)) = imp.find_module(name) except (NameError, ImportError), msg: tkMessageBox.showerror("Import error", str(msg), parent=self.text) return if type != imp.PY_SOURCE: tkMessageBox.showerror("Unsupported type", "%s is not a source module" % name, parent=self.text) return if f: f.close() if self.flist: self.flist.open(file) else: self.io.loadfile(file)
defopen_module(self,event=None):#XXXShouldn'tthisbeinIOBindingorinFileList?try:name=self.text.get("sel.first","sel.last")exceptTclError:name=""else:name=string.strip(name)ifnotname:name=tkSimpleDialog.askstring("Module","EnterthenameofaPythonmodule\n""tosearchonsys.pathandopen:",parent=self.text)ifname:name=string.strip(name)ifnotname:return#XXXOughttosupportpackagesyntax#XXXOughttoinsertcurrentfile'sdirectoryinfrontofpathtry:(f,file,(suffix,mode,type))=imp.find_module(name)except(NameError,ImportError),msg:tkMessageBox.showerror("Importerror",str(msg),parent=self.text)returniftype!=imp.PY_SOURCE:tkMessageBox.showerror("Unsupportedtype","%sisnotasourcemodule"%name,parent=self.text)returniff:f.close()ifself.flist:self.flist.open(file)else:self.io.loadfile(file)
11,529
def open_module(self, event=None): # XXX Shouldn't this be in IOBinding or in FileList? try: name = self.text.get("sel.first", "sel.last") except TclError: name = "" else: name = string.strip(name) if not name: name = tkSimpleDialog.askstring("Module", "Enter the name of a Python module\n" "to search on sys.path and open:", parent=self.text) if name: name = string.strip(name) if not name: return # XXX Ought to support package syntax # XXX Ought to insert current file's directory in front of path try: (f, file, (suffix, mode, type)) = imp.find_module(name) except (NameError, ImportError), msg: tkMessageBox.showerror("Import error", str(msg), parent=self.text) return if type != imp.PY_SOURCE: tkMessageBox.showerror("Unsupported type", "%s is not a source module" % name, parent=self.text) return if f: f.close() if self.flist: self.flist.open(file) else: self.io.loadfile(file)
def open_module(self, event=None): # XXX Shouldn't this be in IOBinding or in FileList? try: name = self.text.get("sel.first", "sel.last") except TclError: name = "" else: name = string.strip(name) if not name: name = tkSimpleDialog.askstring("Module", "Enter the name of a Python module\n" "to search on sys.path and open:", parent=self.text) if name: name = string.strip(name) if not name: return # XXX Ought to support package syntax # XXX Ought to insert current file's directory in front of path try: (f, file, (suffix, mode, type)) = _find_module(name) except (NameError, ImportError), msg: tkMessageBox.showerror("Import error", str(msg), parent=self.text) return if type != imp.PY_SOURCE: tkMessageBox.showerror("Unsupported type", "%s is not a source module" % name, parent=self.text) return if f: f.close() if self.flist: self.flist.open(file) else: self.io.loadfile(file)
11,530
def python_compiler(): """ Returns a string identifying the compiler used for compiling Python. """ return _sys_version()[3]
def python_compiler(): """ Returns a string identifying the compiler used for compiling Python. """ return _sys_version()[3]
11,531
def platform(aliased=0, terse=0): """ Returns a single string identifying the underlying platform with as much useful information as possible (but no more :). The output is intended to be human readable rather than machine parseable. It may look different on different platforms and this is intended. If "aliased" is true, the function will use aliases for various platforms that report system names which differ from their common names, e.g. SunOS will be reported as Solaris. The system_alias() function is used to implement this. Setting terse to true causes the function to return only the absolute minimum information needed to identify the platform. """ global _platform_cache,_platform_aliased_cache if not aliased and (_platform_cache[bool(terse)] is not None): return _platform_cache[bool(terse)] elif _platform_aliased_cache[bool(terse)] is not None: return _platform_aliased_cache[bool(terse)] # Get uname information and then apply platform specific cosmetics # to it... system,node,release,version,machine,processor = uname() if machine == processor: processor = '' if aliased: system,release,version = system_alias(system,release,version) if system == 'Windows': # MS platforms rel,vers,csd,ptype = win32_ver(version) if terse: platform = _platform(system,release) else: platform = _platform(system,release,version,csd) elif system in ('Linux',): # Linux based systems distname,distversion,distid = dist('') if distname and not terse: platform = _platform(system,release,machine,processor, 'with', distname,distversion,distid) else: # If the distribution name is unknown check for libc vs. glibc libcname,libcversion = libc_ver(sys.executable) platform = _platform(system,release,machine,processor, 'with', libcname+libcversion) elif system == 'Java': # Java platforms r,v,vminfo,(os_name,os_version,os_arch) = java_ver() if terse: platform = _platform(system,release,version) else: platform = _platform(system,release,version, 'on', os_name,os_version,os_arch) elif system == 'MacOS': # MacOS platforms if terse: platform = _platform(system,release) else: platform = _platform(system,release,machine) else: # Generic handler if terse: platform = _platform(system,release) else: bits,linkage = architecture(sys.executable) platform = _platform(system,release,machine,processor,bits,linkage) if aliased: _platform_aliased_cache[bool(terse)] = platform elif terse: pass else: _platform_cache[bool(terse)] = platform return platform
def platform(aliased=0, terse=0): """ Returns a single string identifying the underlying platform with as much useful information as possible (but no more :). The output is intended to be human readable rather than machine parseable. It may look different on different platforms and this is intended. If "aliased" is true, the function will use aliases for various platforms that report system names which differ from their common names, e.g. SunOS will be reported as Solaris. The system_alias() function is used to implement this. Setting terse to true causes the function to return only the absolute minimum information needed to identify the platform. """ global _platform_cache_terse, _platform_cache_not_terse global _platform_aliased_cache_terse, _platform_aliased_cache_not_terse if not aliased and terse and (_platform_cache_terse is not None): return _platform_cache_terse elif not aliased and not terse and (_platform_cache_not_terse is not None): return _platform_cache_not_terse elif terse and _platform_aliased_cache_terse is not None: return _platform_aliased_cache_terse elif not terse and _platform_aliased_cache_not_terse is not None: return _platform_aliased_cache_not_terse # Get uname information and then apply platform specific cosmetics # to it... system,node,release,version,machine,processor = uname() if machine == processor: processor = '' if aliased: system,release,version = system_alias(system,release,version) if system == 'Windows': # MS platforms rel,vers,csd,ptype = win32_ver(version) if terse: platform = _platform(system,release) else: platform = _platform(system,release,version,csd) elif system in ('Linux',): # Linux based systems distname,distversion,distid = dist('') if distname and not terse: platform = _platform(system,release,machine,processor, 'with', distname,distversion,distid) else: # If the distribution name is unknown check for libc vs. glibc libcname,libcversion = libc_ver(sys.executable) platform = _platform(system,release,machine,processor, 'with', libcname+libcversion) elif system == 'Java': # Java platforms r,v,vminfo,(os_name,os_version,os_arch) = java_ver() if terse: platform = _platform(system,release,version) else: platform = _platform(system,release,version, 'on', os_name,os_version,os_arch) elif system == 'MacOS': # MacOS platforms if terse: platform = _platform(system,release) else: platform = _platform(system,release,machine) else: # Generic handler if terse: platform = _platform(system,release) else: bits,linkage = architecture(sys.executable) platform = _platform(system,release,machine,processor,bits,linkage) if aliased: _platform_aliased_cache[bool(terse)] = platform elif terse: pass else: _platform_cache[bool(terse)] = platform return platform
11,532
def platform(aliased=0, terse=0): """ Returns a single string identifying the underlying platform with as much useful information as possible (but no more :). The output is intended to be human readable rather than machine parseable. It may look different on different platforms and this is intended. If "aliased" is true, the function will use aliases for various platforms that report system names which differ from their common names, e.g. SunOS will be reported as Solaris. The system_alias() function is used to implement this. Setting terse to true causes the function to return only the absolute minimum information needed to identify the platform. """ global _platform_cache,_platform_aliased_cache if not aliased and (_platform_cache[bool(terse)] is not None): return _platform_cache[bool(terse)] elif _platform_aliased_cache[bool(terse)] is not None: return _platform_aliased_cache[bool(terse)] # Get uname information and then apply platform specific cosmetics # to it... system,node,release,version,machine,processor = uname() if machine == processor: processor = '' if aliased: system,release,version = system_alias(system,release,version) if system == 'Windows': # MS platforms rel,vers,csd,ptype = win32_ver(version) if terse: platform = _platform(system,release) else: platform = _platform(system,release,version,csd) elif system in ('Linux',): # Linux based systems distname,distversion,distid = dist('') if distname and not terse: platform = _platform(system,release,machine,processor, 'with', distname,distversion,distid) else: # If the distribution name is unknown check for libc vs. glibc libcname,libcversion = libc_ver(sys.executable) platform = _platform(system,release,machine,processor, 'with', libcname+libcversion) elif system == 'Java': # Java platforms r,v,vminfo,(os_name,os_version,os_arch) = java_ver() if terse: platform = _platform(system,release,version) else: platform = _platform(system,release,version, 'on', os_name,os_version,os_arch) elif system == 'MacOS': # MacOS platforms if terse: platform = _platform(system,release) else: platform = _platform(system,release,machine) else: # Generic handler if terse: platform = _platform(system,release) else: bits,linkage = architecture(sys.executable) platform = _platform(system,release,machine,processor,bits,linkage) if aliased: _platform_aliased_cache[bool(terse)] = platform elif terse: pass else: _platform_cache[bool(terse)] = platform return platform
def platform(aliased=0, terse=0): """ Returns a single string identifying the underlying platform with as much useful information as possible (but no more :). The output is intended to be human readable rather than machine parseable. It may look different on different platforms and this is intended. If "aliased" is true, the function will use aliases for various platforms that report system names which differ from their common names, e.g. SunOS will be reported as Solaris. The system_alias() function is used to implement this. Setting terse to true causes the function to return only the absolute minimum information needed to identify the platform. """ global _platform_cache,_platform_aliased_cache if not aliased and (_platform_cache[bool(terse)] is not None): return _platform_cache[bool(terse)] elif _platform_aliased_cache[bool(terse)] is not None: return _platform_aliased_cache[bool(terse)] # Get uname information and then apply platform specific cosmetics # to it... system,node,release,version,machine,processor = uname() if machine == processor: processor = '' if aliased: system,release,version = system_alias(system,release,version) if system == 'Windows': # MS platforms rel,vers,csd,ptype = win32_ver(version) if terse: platform = _platform(system,release) else: platform = _platform(system,release,version,csd) elif system in ('Linux',): # Linux based systems distname,distversion,distid = dist('') if distname and not terse: platform = _platform(system,release,machine,processor, 'with', distname,distversion,distid) else: # If the distribution name is unknown check for libc vs. glibc libcname,libcversion = libc_ver(sys.executable) platform = _platform(system,release,machine,processor, 'with', libcname+libcversion) elif system == 'Java': # Java platforms r,v,vminfo,(os_name,os_version,os_arch) = java_ver() if terse: platform = _platform(system,release,version) else: platform = _platform(system,release,version, 'on', os_name,os_version,os_arch) elif system == 'MacOS': # MacOS platforms if terse: platform = _platform(system,release) else: platform = _platform(system,release,machine) else: # Generic handler if terse: platform = _platform(system,release) else: bits,linkage = architecture(sys.executable) platform = _platform(system,release,machine,processor,bits,linkage) if aliased and terse: _platform_aliased_cache_terse = platform elif aliased and not terse: _platform_aliased_cache_not_terse = platform elif terse: pass else: _platform_cache[bool(terse)] = platform return platform
11,533
def platform(aliased=0, terse=0): """ Returns a single string identifying the underlying platform with as much useful information as possible (but no more :). The output is intended to be human readable rather than machine parseable. It may look different on different platforms and this is intended. If "aliased" is true, the function will use aliases for various platforms that report system names which differ from their common names, e.g. SunOS will be reported as Solaris. The system_alias() function is used to implement this. Setting terse to true causes the function to return only the absolute minimum information needed to identify the platform. """ global _platform_cache,_platform_aliased_cache if not aliased and (_platform_cache[bool(terse)] is not None): return _platform_cache[bool(terse)] elif _platform_aliased_cache[bool(terse)] is not None: return _platform_aliased_cache[bool(terse)] # Get uname information and then apply platform specific cosmetics # to it... system,node,release,version,machine,processor = uname() if machine == processor: processor = '' if aliased: system,release,version = system_alias(system,release,version) if system == 'Windows': # MS platforms rel,vers,csd,ptype = win32_ver(version) if terse: platform = _platform(system,release) else: platform = _platform(system,release,version,csd) elif system in ('Linux',): # Linux based systems distname,distversion,distid = dist('') if distname and not terse: platform = _platform(system,release,machine,processor, 'with', distname,distversion,distid) else: # If the distribution name is unknown check for libc vs. glibc libcname,libcversion = libc_ver(sys.executable) platform = _platform(system,release,machine,processor, 'with', libcname+libcversion) elif system == 'Java': # Java platforms r,v,vminfo,(os_name,os_version,os_arch) = java_ver() if terse: platform = _platform(system,release,version) else: platform = _platform(system,release,version, 'on', os_name,os_version,os_arch) elif system == 'MacOS': # MacOS platforms if terse: platform = _platform(system,release) else: platform = _platform(system,release,machine) else: # Generic handler if terse: platform = _platform(system,release) else: bits,linkage = architecture(sys.executable) platform = _platform(system,release,machine,processor,bits,linkage) if aliased: _platform_aliased_cache[bool(terse)] = platform elif terse: pass else: _platform_cache[bool(terse)] = platform return platform
def platform(aliased=0, terse=0): """ Returns a single string identifying the underlying platform with as much useful information as possible (but no more :). The output is intended to be human readable rather than machine parseable. It may look different on different platforms and this is intended. If "aliased" is true, the function will use aliases for various platforms that report system names which differ from their common names, e.g. SunOS will be reported as Solaris. The system_alias() function is used to implement this. Setting terse to true causes the function to return only the absolute minimum information needed to identify the platform. """ global _platform_cache,_platform_aliased_cache if not aliased and (_platform_cache[bool(terse)] is not None): return _platform_cache[bool(terse)] elif _platform_aliased_cache[bool(terse)] is not None: return _platform_aliased_cache[bool(terse)] # Get uname information and then apply platform specific cosmetics # to it... system,node,release,version,machine,processor = uname() if machine == processor: processor = '' if aliased: system,release,version = system_alias(system,release,version) if system == 'Windows': # MS platforms rel,vers,csd,ptype = win32_ver(version) if terse: platform = _platform(system,release) else: platform = _platform(system,release,version,csd) elif system in ('Linux',): # Linux based systems distname,distversion,distid = dist('') if distname and not terse: platform = _platform(system,release,machine,processor, 'with', distname,distversion,distid) else: # If the distribution name is unknown check for libc vs. glibc libcname,libcversion = libc_ver(sys.executable) platform = _platform(system,release,machine,processor, 'with', libcname+libcversion) elif system == 'Java': # Java platforms r,v,vminfo,(os_name,os_version,os_arch) = java_ver() if terse: platform = _platform(system,release,version) else: platform = _platform(system,release,version, 'on', os_name,os_version,os_arch) elif system == 'MacOS': # MacOS platforms if terse: platform = _platform(system,release) else: platform = _platform(system,release,machine) else: # Generic handler if terse: platform = _platform(system,release) else: bits,linkage = architecture(sys.executable) platform = _platform(system,release,machine,processor,bits,linkage) if aliased: _platform_aliased_cache[bool(terse)] = platform elif terse: pass else: if terse: _platform_cache_terse = platform else: _platform_cache_not_terse = platform return platform
11,534
def outputCheckConvertArg(self): Out(""" if (v == Py_None) { *p_itself = NULL; return 1; } if (PyString_Check(v)) { char *cStr = PyString_AsString(v); *p_itself = CFStringCreateWithCString((CFAllocatorRef)NULL, cStr, 0); return 1; } if (PyUnicode_Check(v)) { /* We use the CF types here, if Python was configured differently that will give an error */ CFIndex size = PyUnicode_GetSize(v); UniChar *unichars = PyUnicode_AsUnicode(v); if (!unichars) return 0; *p_itself = CFStringCreateWithCharacters((CFAllocatorRef)NULL, unichars, size); return 1; } """)
def outputCheckConvertArg(self): Out(""" if (v == Py_None) { *p_itself = NULL; return 1; } if (PyString_Check(v)) { char *cStr; if (!PyArg_Parse(v, "et", "ascii", &cStr)) return NULL; *p_itself = CFStringCreateWithCString((CFAllocatorRef)NULL, cStr, kCFStringEncodingASCII); return 1; } if (PyUnicode_Check(v)) { /* We use the CF types here, if Python was configured differently that will give an error */ CFIndex size = PyUnicode_GetSize(v); UniChar *unichars = PyUnicode_AsUnicode(v); if (!unichars) return 0; *p_itself = CFStringCreateWithCharacters((CFAllocatorRef)NULL, unichars, size); return 1; } """)
11,535
def wait(self): """Wait for and return the exit status of the child process.""" pid, sts = os.waitpid(self.pid, 0) if pid == self.pid: self.sts = sts _active.remove(self) return self.sts
def wait(self): """Wait for and return the exit status of the child process.""" pid, sts = os.waitpid(self.pid, 0) if pid == self.pid: self.sts = sts _active.remove(self) return self.sts
11,536
def popen2(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin) are returned.""" if type(mode) is type(0) and bufsize == -1: bufsize = mode mode = 't' assert mode in ('t', 'b') _cleanup() inst = Popen3(cmd, 0, bufsize) return inst.fromchild, inst.tochild
def popen2(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin) are returned.""" if type(mode) is type(0) and bufsize == -1: bufsize = mode mode = 't' assert mode in ('t', 'b') _cleanup() inst = Popen3(cmd, 0, bufsize) return inst.fromchild, inst.tochild
11,537
def popen3(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin, child_stderr) are returned.""" if type(mode) is type(0) and bufsize == -1: bufsize = mode mode = 't' assert mode in ('t', 'b') _cleanup() inst = Popen3(cmd, 1, bufsize) return inst.fromchild, inst.tochild, inst.childerr
def popen3(cmd, mode='t', bufsize=-1): """Execute the shell command 'cmd' in a sub-process. If 'bufsize' is specified, it sets the buffer size for the I/O pipes. The file objects (child_stdout, child_stdin, child_stderr) are returned.""" if type(mode) is type(0) and bufsize == -1: bufsize = mode mode = 't' assert mode in ('t', 'b') _cleanup() inst = Popen3(cmd, 1, bufsize) return inst.fromchild, inst.tochild, inst.childerr
11,538
def split(p): d, p = splitdrive(p) slashes = '' while p and p[-1:] in '/\\': slashes = slashes + p[-1] p = p[:-1] if p == '': p = p + slashes head, tail = '', '' for c in p: tail = tail + c if c in '/\\': head, tail = head + tail, '' slashes = '' while head and head[-1:] in '/\\': slashes = slashes + head[-1] head = head[:-1] if head == '': head = head + slashes return d + head, tail
def split(p): d, p = splitdrive(p) slashes = '' while p and p[-1:] in '/\\': slashes = slashes + p[-1] p = p[:-1] if p == '': p = p + slashes head, tail = '', '' for c in p: tail = tail + c if c in '/\\': head, tail = head + tail, '' slashes = '' while head and head[-1:] in '/\\': slashes = slashes + head[-1] head = head[:-1] if head == '': head = head + slashes return d + head, tail
11,539
def splitext(p): root, ext = '', '' for c in p: if c in '/\\': root, ext = root + ext + c, '' elif c == '.' or ext: ext = ext + c else: root = root + c return root, ext
def splitext(p): root, ext = '', '' for c in p: if c in ['/','\\']: root, ext = root + ext + c, '' elif c == '.' or ext: ext = ext + c else: root = root + c return root, ext
11,540
def splitext(p): root, ext = '', '' for c in p: if c in '/\\': root, ext = root + ext + c, '' elif c == '.' or ext: ext = ext + c else: root = root + c return root, ext
def splitext(p): root, ext = '', '' for c in p: if c in '/\\': root, ext = root + ext + c, '' elif c == '.': if ext: root, ext = root + ext, c else: ext = c elif ext: ext = ext + c else: root = root + c return root, ext
11,541
def formatmonthname(self, theyear, themonth, width): """ Return a formatted month name. """ s = "%s %r" % (month_name[themonth], theyear) return s.center(width)
def formatmonthname(self, theyear, themonth, width, withyear=True): """ Return a formatted month name. """ s = "%s %r" % (month_name[themonth], theyear) return s.center(width)
11,542
def formatmonthname(self, theyear, themonth, width): """ Return a formatted month name. """ s = "%s %r" % (month_name[themonth], theyear) return s.center(width)
def formatmonthname(self, theyear, themonth, width): """ Return a formatted month name. """ s = month_name[themonth] if withyear: s = "%s %r" % (s, theyear) return s.center(width)
11,543
def formatyear(self, theyear, w=2, l=1, c=6, m=3): """ Returns a year's calendar as a multi-line string. """ w = max(2, w) l = max(1, l) c = max(2, c) colwidth = (w + 1) * 7 - 1 v = [] a = v.append a(repr(theyear).center(colwidth*m+c*(m-1)).rstrip()) a('\n'*l) header = self.formatweekheader(w) for (i, row) in enumerate(self.yeardays2calendar(theyear, m)): # months in this row months = xrange(m*i+1, min(m*(i+1)+1, 13)) a('\n'*l) a(formatstring((month_name[k] for k in months), colwidth, c).rstrip()) a('\n'*l) a(formatstring((header for k in months), colwidth, c).rstrip()) a('\n'*l) # max number of weeks for this row height = max(len(cal) for cal in row) for j in xrange(height): weeks = [] for cal in row: if j >= len(cal): weeks.append('') else: weeks.append(self.formatweek(cal[j], w)) a(formatstring(weeks, colwidth, c).rstrip()) a('\n' * l) return ''.join(v)
def formatyear(self, theyear, w=2, l=1, c=6, m=3): """ Returns a year's calendar as a multi-line string. """ w = max(2, w) l = max(1, l) c = max(2, c) colwidth = (w + 1) * 7 - 1 v = [] a = v.append a(repr(theyear).center(colwidth*m+c*(m-1)).rstrip()) a('\n'*l) header = self.formatweekheader(w) for (i, row) in enumerate(self.yeardays2calendar(theyear, m)): # months in this row months = xrange(m*i+1, min(m*(i+1)+1, 13)) a('\n'*l) names = (self.formatmonthname(theyear, k, colwidth, False) for k in months) a(formatstring(names, colwidth, c).rstrip()) a('\n'*l) a(formatstring((header for k in months), colwidth, c).rstrip()) a('\n'*l) # max number of weeks for this row height = max(len(cal) for cal in row) for j in xrange(height): weeks = [] for cal in row: if j >= len(cal): weeks.append('') else: weeks.append(self.formatweek(cal[j], w)) a(formatstring(weeks, colwidth, c).rstrip()) a('\n' * l) return ''.join(v)
11,544
def formatyear(self, theyear, w=2, l=1, c=6, m=3): """ Returns a year's calendar as a multi-line string. """ w = max(2, w) l = max(1, l) c = max(2, c) colwidth = (w + 1) * 7 - 1 v = [] a = v.append a(repr(theyear).center(colwidth*m+c*(m-1)).rstrip()) a('\n'*l) header = self.formatweekheader(w) for (i, row) in enumerate(self.yeardays2calendar(theyear, m)): # months in this row months = xrange(m*i+1, min(m*(i+1)+1, 13)) a('\n'*l) a(formatstring((month_name[k] for k in months), colwidth, c).rstrip()) a('\n'*l) a(formatstring((header for k in months), colwidth, c).rstrip()) a('\n'*l) # max number of weeks for this row height = max(len(cal) for cal in row) for j in xrange(height): weeks = [] for cal in row: if j >= len(cal): weeks.append('') else: weeks.append(self.formatweek(cal[j], w)) a(formatstring(weeks, colwidth, c).rstrip()) a('\n' * l) return ''.join(v)
def formatyear(self, theyear, w=2, l=1, c=6, m=3): """ Returns a year's calendar as a multi-line string. """ w = max(2, w) l = max(1, l) c = max(2, c) colwidth = (w + 1) * 7 - 1 v = [] a = v.append a(repr(theyear).center(colwidth*m+c*(m-1)).rstrip()) a('\n'*l) header = self.formatweekheader(w) for (i, row) in enumerate(self.yeardays2calendar(theyear, m)): # months in this row months = xrange(m*i+1, min(m*(i+1)+1, 13)) a('\n'*l) a(formatstring((month_name[k] for k in months), colwidth, c).rstrip()) a('\n'*l) headers = (header for k in months) a(formatstring(headers, colwidth, c).rstrip()) a('\n'*l) # max number of weeks for this row height = max(len(cal) for cal in row) for j in xrange(height): weeks = [] for cal in row: if j >= len(cal): weeks.append('') else: weeks.append(self.formatweek(cal[j], w)) a(formatstring(weeks, colwidth, c).rstrip()) a('\n' * l) return ''.join(v)
11,545
def formatyearpage(self, theyear, width=3, css='calendar.css', encoding=None): """ Return a formatted year as a complete HTML page. """ if encoding is None: encoding = sys.getdefaultencoding() v = [] a = v.append a('<?xml version="1.0" encoding="%s"?>\n' % encoding) a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n') a('<html>\n') a('<head>\n') a('<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' % encoding) if css is not None: a('<link rel="stylesheet" type="text/css" href="%s" />\n' % css) a('<title>Calendar for %d</title\n' % theyear) a('</head>\n') a('<body>\n') a(self.formatyear(theyear, width)) a('</body>\n') a('</html>\n') return ''.join(v).encode(encoding)
def formatyearpage(self, theyear, width=3, css='calendar.css', encoding=None): """ Return a formatted year as a complete HTML page. """ if encoding is None: encoding = sys.getdefaultencoding() v = [] a = v.append a('<?xml version="1.0" encoding="%s"?>\n' % encoding) a('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n') a('<html>\n') a('<head>\n') a('<meta http-equiv="Content-Type" content="text/html; charset=%s" />\n' % encoding) if css is not None: a('<link rel="stylesheet" type="text/css" href="%s" />\n' % css) a('<title>Calendar for %d</title\n' % theyear) a('</head>\n') a('<body>\n') a(self.formatyear(theyear, width)) a('</body>\n') a('</html>\n') return ''.join(v).encode(encoding)
11,546
def main(args): import optparse parser = optparse.OptionParser(usage="usage: %prog [options] [year] [month]") parser.add_option("-w", "--width", dest="width", type="int", default=2, help="width of date column (default 2, text only)") parser.add_option("-l", "--lines", dest="lines", type="int", default=1, help="number of lines for each week (default 1, text only)") parser.add_option("-s", "--spacing", dest="spacing", type="int", default=6, help="spacing between months (default 6, text only)") parser.add_option("-m", "--months", dest="months", type="int", default=3, help="months per row (default 3, text only)") parser.add_option("-c", "--css", dest="css", default="calendar.css", help="CSS to use for page (html only)") parser.add_option("-e", "--encoding", dest="encoding", default=None, help="Encoding to use for CSS output (html only)") parser.add_option("-t", "--type", dest="type", default="text", choices=("text", "html"), help="output type (text or html)") (options, args) = parser.parse_args(args) if options.type == "html": cal = HTMLCalendar() encoding = options.encoding if encoding is None: encoding = sys.getdefaultencoding() optdict = dict(encoding=encoding, css=options.css) if len(args) == 1: print cal.formatyearpage(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyearpage(int(args[1]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1) else: cal = TextCalendar() optdict = dict(w=options.width, l=options.lines) if len(args) != 3: optdict["c"] = options.spacing optdict["m"] = options.months if len(args) == 1: print cal.formatyear(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyear(int(args[1]), **optdict) elif len(args) == 3: print cal.formatmonth(int(args[1]), int(args[2]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1)
def main(args): import optparse parser = optparse.OptionParser(usage="usage: %prog [options] [year [month]]") parser.add_option( "-w", "--width", dest="width", type="int", default=2, help="width of date column (default 2, text only)" ) parser.add_option( "-l", "--lines", dest="lines", type="int", default=1, help="number of lines for each week (default 1, text only)" ) parser.add_option( "-s", "--spacing", dest="spacing", type="int", default=6, help="spacing between months (default 6, text only)" ) parser.add_option( "-m", "--months", dest="months", type="int", default=3, help="months per row (default 3, text only)" ) parser.add_option( "-c", "--css", dest="css", default="calendar.css", help="CSS to use for page (html only)" ) parser.add_option( "-L", "--locale", dest="locale", default=None, help="locale to be used from month and weekday names" ) parser.add_option( "-e", "--encoding", dest="encoding", default=None, help="Encoding to use for output" ) parser.add_option( "-t", "--type", dest="type", default="text", choices=("text", "html"), help="output type (text or html)" ) (options, args) = parser.parse_args(args) if options.type == "html": cal = HTMLCalendar() encoding = options.encoding if encoding is None: encoding = sys.getdefaultencoding() optdict = dict(encoding=encoding, css=options.css) if len(args) == 1: print cal.formatyearpage(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyearpage(int(args[1]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1) else: cal = TextCalendar() optdict = dict(w=options.width, l=options.lines) if len(args) != 3: optdict["c"] = options.spacing optdict["m"] = options.months if len(args) == 1: print cal.formatyear(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyear(int(args[1]), **optdict) elif len(args) == 3: print cal.formatmonth(int(args[1]), int(args[2]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1)
11,547
def main(args): import optparse parser = optparse.OptionParser(usage="usage: %prog [options] [year] [month]") parser.add_option("-w", "--width", dest="width", type="int", default=2, help="width of date column (default 2, text only)") parser.add_option("-l", "--lines", dest="lines", type="int", default=1, help="number of lines for each week (default 1, text only)") parser.add_option("-s", "--spacing", dest="spacing", type="int", default=6, help="spacing between months (default 6, text only)") parser.add_option("-m", "--months", dest="months", type="int", default=3, help="months per row (default 3, text only)") parser.add_option("-c", "--css", dest="css", default="calendar.css", help="CSS to use for page (html only)") parser.add_option("-e", "--encoding", dest="encoding", default=None, help="Encoding to use for CSS output (html only)") parser.add_option("-t", "--type", dest="type", default="text", choices=("text", "html"), help="output type (text or html)") (options, args) = parser.parse_args(args) if options.type == "html": cal = HTMLCalendar() encoding = options.encoding if encoding is None: encoding = sys.getdefaultencoding() optdict = dict(encoding=encoding, css=options.css) if len(args) == 1: print cal.formatyearpage(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyearpage(int(args[1]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1) else: cal = TextCalendar() optdict = dict(w=options.width, l=options.lines) if len(args) != 3: optdict["c"] = options.spacing optdict["m"] = options.months if len(args) == 1: print cal.formatyear(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyear(int(args[1]), **optdict) elif len(args) == 3: print cal.formatmonth(int(args[1]), int(args[2]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1)
def main(args): import optparse parser = optparse.OptionParser(usage="usage: %prog [options] [year] [month]") parser.add_option("-w", "--width", dest="width", type="int", default=2, help="width of date column (default 2, text only)") parser.add_option("-l", "--lines", dest="lines", type="int", default=1, help="number of lines for each week (default 1, text only)") parser.add_option("-s", "--spacing", dest="spacing", type="int", default=6, help="spacing between months (default 6, text only)") parser.add_option("-m", "--months", dest="months", type="int", default=3, help="months per row (default 3, text only)") parser.add_option("-c", "--css", dest="css", default="calendar.css", help="CSS to use for page (html only)") parser.add_option("-e", "--encoding", dest="encoding", default=None, help="Encoding to use for CSS output (html only)") parser.add_option("-t", "--type", dest="type", default="text", choices=("text", "html"), help="output type (text or html)") (options, args) = parser.parse_args(args) if options.type == "html": if options.locale: cal = LocaleHTMLCalendar(locale=options.locale) else: cal = HTMLCalendar() encoding = options.encoding if encoding is None: encoding = sys.getdefaultencoding() optdict = dict(encoding=encoding, css=options.css) if len(args) == 1: print cal.formatyearpage(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyearpage(int(args[1]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1) else: cal = TextCalendar() optdict = dict(w=options.width, l=options.lines) if len(args) != 3: optdict["c"] = options.spacing optdict["m"] = options.months if len(args) == 1: print cal.formatyear(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyear(int(args[1]), **optdict) elif len(args) == 3: print cal.formatmonth(int(args[1]), int(args[2]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1)
11,548
def main(args): import optparse parser = optparse.OptionParser(usage="usage: %prog [options] [year] [month]") parser.add_option("-w", "--width", dest="width", type="int", default=2, help="width of date column (default 2, text only)") parser.add_option("-l", "--lines", dest="lines", type="int", default=1, help="number of lines for each week (default 1, text only)") parser.add_option("-s", "--spacing", dest="spacing", type="int", default=6, help="spacing between months (default 6, text only)") parser.add_option("-m", "--months", dest="months", type="int", default=3, help="months per row (default 3, text only)") parser.add_option("-c", "--css", dest="css", default="calendar.css", help="CSS to use for page (html only)") parser.add_option("-e", "--encoding", dest="encoding", default=None, help="Encoding to use for CSS output (html only)") parser.add_option("-t", "--type", dest="type", default="text", choices=("text", "html"), help="output type (text or html)") (options, args) = parser.parse_args(args) if options.type == "html": cal = HTMLCalendar() encoding = options.encoding if encoding is None: encoding = sys.getdefaultencoding() optdict = dict(encoding=encoding, css=options.css) if len(args) == 1: print cal.formatyearpage(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyearpage(int(args[1]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1) else: cal = TextCalendar() optdict = dict(w=options.width, l=options.lines) if len(args) != 3: optdict["c"] = options.spacing optdict["m"] = options.months if len(args) == 1: print cal.formatyear(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyear(int(args[1]), **optdict) elif len(args) == 3: print cal.formatmonth(int(args[1]), int(args[2]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1)
def main(args): import optparse parser = optparse.OptionParser(usage="usage: %prog [options] [year] [month]") parser.add_option("-w", "--width", dest="width", type="int", default=2, help="width of date column (default 2, text only)") parser.add_option("-l", "--lines", dest="lines", type="int", default=1, help="number of lines for each week (default 1, text only)") parser.add_option("-s", "--spacing", dest="spacing", type="int", default=6, help="spacing between months (default 6, text only)") parser.add_option("-m", "--months", dest="months", type="int", default=3, help="months per row (default 3, text only)") parser.add_option("-c", "--css", dest="css", default="calendar.css", help="CSS to use for page (html only)") parser.add_option("-e", "--encoding", dest="encoding", default=None, help="Encoding to use for CSS output (html only)") parser.add_option("-t", "--type", dest="type", default="text", choices=("text", "html"), help="output type (text or html)") (options, args) = parser.parse_args(args) if options.type == "html": cal = HTMLCalendar() encoding = options.encoding if encoding is None: encoding = sys.getdefaultencoding() optdict = dict(encoding=encoding, css=options.css) if len(args) == 1: print cal.formatyearpage(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyearpage(int(args[1]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1) else: if options.locale: cal = LocaleTextCalendar(locale=options.locale) else: cal = TextCalendar() optdict = dict(w=options.width, l=options.lines) if len(args) != 3: optdict["c"] = options.spacing optdict["m"] = options.months if len(args) == 1: print cal.formatyear(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyear(int(args[1]), **optdict) elif len(args) == 3: print cal.formatmonth(int(args[1]), int(args[2]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1)
11,549
def main(args): import optparse parser = optparse.OptionParser(usage="usage: %prog [options] [year] [month]") parser.add_option("-w", "--width", dest="width", type="int", default=2, help="width of date column (default 2, text only)") parser.add_option("-l", "--lines", dest="lines", type="int", default=1, help="number of lines for each week (default 1, text only)") parser.add_option("-s", "--spacing", dest="spacing", type="int", default=6, help="spacing between months (default 6, text only)") parser.add_option("-m", "--months", dest="months", type="int", default=3, help="months per row (default 3, text only)") parser.add_option("-c", "--css", dest="css", default="calendar.css", help="CSS to use for page (html only)") parser.add_option("-e", "--encoding", dest="encoding", default=None, help="Encoding to use for CSS output (html only)") parser.add_option("-t", "--type", dest="type", default="text", choices=("text", "html"), help="output type (text or html)") (options, args) = parser.parse_args(args) if options.type == "html": cal = HTMLCalendar() encoding = options.encoding if encoding is None: encoding = sys.getdefaultencoding() optdict = dict(encoding=encoding, css=options.css) if len(args) == 1: print cal.formatyearpage(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyearpage(int(args[1]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1) else: cal = TextCalendar() optdict = dict(w=options.width, l=options.lines) if len(args) != 3: optdict["c"] = options.spacing optdict["m"] = options.months if len(args) == 1: print cal.formatyear(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyear(int(args[1]), **optdict) elif len(args) == 3: print cal.formatmonth(int(args[1]), int(args[2]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1)
def main(args): import optparse parser = optparse.OptionParser(usage="usage: %prog [options] [year] [month]") parser.add_option("-w", "--width", dest="width", type="int", default=2, help="width of date column (default 2, text only)") parser.add_option("-l", "--lines", dest="lines", type="int", default=1, help="number of lines for each week (default 1, text only)") parser.add_option("-s", "--spacing", dest="spacing", type="int", default=6, help="spacing between months (default 6, text only)") parser.add_option("-m", "--months", dest="months", type="int", default=3, help="months per row (default 3, text only)") parser.add_option("-c", "--css", dest="css", default="calendar.css", help="CSS to use for page (html only)") parser.add_option("-e", "--encoding", dest="encoding", default=None, help="Encoding to use for CSS output (html only)") parser.add_option("-t", "--type", dest="type", default="text", choices=("text", "html"), help="output type (text or html)") (options, args) = parser.parse_args(args) if options.type == "html": cal = HTMLCalendar() encoding = options.encoding if encoding is None: encoding = sys.getdefaultencoding() optdict = dict(encoding=encoding, css=options.css) if len(args) == 1: print cal.formatyearpage(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyearpage(int(args[1]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1) else: cal = TextCalendar() optdict = dict(w=options.width, l=options.lines) if len(args) != 3: optdict["c"] = options.spacing optdict["m"] = options.months if len(args) == 1: result = cal.formatyear(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyear(int(args[1]), **optdict) elif len(args) == 3: print cal.formatmonth(int(args[1]), int(args[2]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1)
11,550
def main(args): import optparse parser = optparse.OptionParser(usage="usage: %prog [options] [year] [month]") parser.add_option("-w", "--width", dest="width", type="int", default=2, help="width of date column (default 2, text only)") parser.add_option("-l", "--lines", dest="lines", type="int", default=1, help="number of lines for each week (default 1, text only)") parser.add_option("-s", "--spacing", dest="spacing", type="int", default=6, help="spacing between months (default 6, text only)") parser.add_option("-m", "--months", dest="months", type="int", default=3, help="months per row (default 3, text only)") parser.add_option("-c", "--css", dest="css", default="calendar.css", help="CSS to use for page (html only)") parser.add_option("-e", "--encoding", dest="encoding", default=None, help="Encoding to use for CSS output (html only)") parser.add_option("-t", "--type", dest="type", default="text", choices=("text", "html"), help="output type (text or html)") (options, args) = parser.parse_args(args) if options.type == "html": cal = HTMLCalendar() encoding = options.encoding if encoding is None: encoding = sys.getdefaultencoding() optdict = dict(encoding=encoding, css=options.css) if len(args) == 1: print cal.formatyearpage(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyearpage(int(args[1]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1) else: cal = TextCalendar() optdict = dict(w=options.width, l=options.lines) if len(args) != 3: optdict["c"] = options.spacing optdict["m"] = options.months if len(args) == 1: print cal.formatyear(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyear(int(args[1]), **optdict) elif len(args) == 3: print cal.formatmonth(int(args[1]), int(args[2]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1)
def main(args): import optparse parser = optparse.OptionParser(usage="usage: %prog [options] [year] [month]") parser.add_option("-w", "--width", dest="width", type="int", default=2, help="width of date column (default 2, text only)") parser.add_option("-l", "--lines", dest="lines", type="int", default=1, help="number of lines for each week (default 1, text only)") parser.add_option("-s", "--spacing", dest="spacing", type="int", default=6, help="spacing between months (default 6, text only)") parser.add_option("-m", "--months", dest="months", type="int", default=3, help="months per row (default 3, text only)") parser.add_option("-c", "--css", dest="css", default="calendar.css", help="CSS to use for page (html only)") parser.add_option("-e", "--encoding", dest="encoding", default=None, help="Encoding to use for CSS output (html only)") parser.add_option("-t", "--type", dest="type", default="text", choices=("text", "html"), help="output type (text or html)") (options, args) = parser.parse_args(args) if options.type == "html": cal = HTMLCalendar() encoding = options.encoding if encoding is None: encoding = sys.getdefaultencoding() optdict = dict(encoding=encoding, css=options.css) if len(args) == 1: print cal.formatyearpage(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyearpage(int(args[1]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1) else: cal = TextCalendar() optdict = dict(w=options.width, l=options.lines) if len(args) != 3: optdict["c"] = options.spacing optdict["m"] = options.months if len(args) == 1: print cal.formatyear(datetime.date.today().year, **optdict) elif len(args) == 2: result = cal.formatyear(int(args[1]), **optdict) elif len(args) == 3: print cal.formatmonth(int(args[1]), int(args[2]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1)
11,551
def main(args): import optparse parser = optparse.OptionParser(usage="usage: %prog [options] [year] [month]") parser.add_option("-w", "--width", dest="width", type="int", default=2, help="width of date column (default 2, text only)") parser.add_option("-l", "--lines", dest="lines", type="int", default=1, help="number of lines for each week (default 1, text only)") parser.add_option("-s", "--spacing", dest="spacing", type="int", default=6, help="spacing between months (default 6, text only)") parser.add_option("-m", "--months", dest="months", type="int", default=3, help="months per row (default 3, text only)") parser.add_option("-c", "--css", dest="css", default="calendar.css", help="CSS to use for page (html only)") parser.add_option("-e", "--encoding", dest="encoding", default=None, help="Encoding to use for CSS output (html only)") parser.add_option("-t", "--type", dest="type", default="text", choices=("text", "html"), help="output type (text or html)") (options, args) = parser.parse_args(args) if options.type == "html": cal = HTMLCalendar() encoding = options.encoding if encoding is None: encoding = sys.getdefaultencoding() optdict = dict(encoding=encoding, css=options.css) if len(args) == 1: print cal.formatyearpage(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyearpage(int(args[1]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1) else: cal = TextCalendar() optdict = dict(w=options.width, l=options.lines) if len(args) != 3: optdict["c"] = options.spacing optdict["m"] = options.months if len(args) == 1: print cal.formatyear(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyear(int(args[1]), **optdict) elif len(args) == 3: print cal.formatmonth(int(args[1]), int(args[2]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1)
def main(args): import optparse parser = optparse.OptionParser(usage="usage: %prog [options] [year] [month]") parser.add_option("-w", "--width", dest="width", type="int", default=2, help="width of date column (default 2, text only)") parser.add_option("-l", "--lines", dest="lines", type="int", default=1, help="number of lines for each week (default 1, text only)") parser.add_option("-s", "--spacing", dest="spacing", type="int", default=6, help="spacing between months (default 6, text only)") parser.add_option("-m", "--months", dest="months", type="int", default=3, help="months per row (default 3, text only)") parser.add_option("-c", "--css", dest="css", default="calendar.css", help="CSS to use for page (html only)") parser.add_option("-e", "--encoding", dest="encoding", default=None, help="Encoding to use for CSS output (html only)") parser.add_option("-t", "--type", dest="type", default="text", choices=("text", "html"), help="output type (text or html)") (options, args) = parser.parse_args(args) if options.type == "html": cal = HTMLCalendar() encoding = options.encoding if encoding is None: encoding = sys.getdefaultencoding() optdict = dict(encoding=encoding, css=options.css) if len(args) == 1: print cal.formatyearpage(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyearpage(int(args[1]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1) else: cal = TextCalendar() optdict = dict(w=options.width, l=options.lines) if len(args) != 3: optdict["c"] = options.spacing optdict["m"] = options.months if len(args) == 1: print cal.formatyear(datetime.date.today().year, **optdict) elif len(args) == 2: print cal.formatyear(int(args[1]), **optdict) elif len(args) == 3: result = cal.formatmonth(int(args[1]), int(args[2]), **optdict) else: parser.error("incorrect number of arguments") sys.exit(1)
11,552
def expandvars(p): """ Expand environment variables using OS_GSTrans. """ l= 512 b= swi.block(l) return b.tostring(0, swi.swi('OS_GSTrans', 'sbi;..i', p, b, l))
def expandvars(p): """ Expand environment variables using OS_GSTrans. """ l= 512 b= swi.block(l) return b.tostring(0, swi.swi('OS_GSTrans', 'sbi;..i', p, b, l))
11,553
def getopt(args, options): list = [] while args and args[0][0] == '-' and args[0] <> '-': if args[0] == '--': args = args[1:] break optstring, args = args[0][1:], args[1:] while optstring <> '': opt, optstring = optstring[0], optstring[1:] if classify(opt, options): # May raise exception as well if optstring == '': if not args: raise error, 'option -' + opt + ' requires argument' optstring, args = args[0], args[1:] optarg, optstring = optstring, '' else: optarg = '' list.append('-' + opt, optarg) return list, args
def getopt(args, options): list = [] while args and args[0][:1] == '-' and args[0] <> '-': if args[0] == '--': args = args[1:] break optstring, args = args[0][1:], args[1:] while optstring <> '': opt, optstring = optstring[0], optstring[1:] if classify(opt, options): # May raise exception as well if optstring == '': if not args: raise error, 'option -' + opt + ' requires argument' optstring, args = args[0], args[1:] optarg, optstring = optstring, '' else: optarg = '' list.append('-' + opt, optarg) return list, args
11,554
def finalize_options (self): self.set_undefined_options('build', ('build_lib', 'build_lib'), ('force', 'force'))
def finalize_options (self): self.set_undefined_options('build', ('build_lib', 'build_lib'), ('force', 'force'))
11,555
def scan_dragto(self, x, y): """Adjust the view of the canvas to 10 times the difference between X and Y and the coordinates given in scan_mark.""" self.tk.call(self._w, 'scan', 'dragto', x, y)
def scan_dragto(self, x, y, gain=10): """Adjust the view of the canvas to GAIN times the difference between X and Y and the coordinates given in scan_mark.""" self.tk.call(self._w, 'scan', 'dragto', x, y)
11,556
def scan_dragto(self, x, y): """Adjust the view of the canvas to 10 times the difference between X and Y and the coordinates given in scan_mark.""" self.tk.call(self._w, 'scan', 'dragto', x, y)
def scan_dragto(self, x, y): """Adjust the view of the canvas to 10 times the difference between X and Y and the coordinates given in scan_mark.""" self.tk.call(self._w, 'scan', 'dragto', x, y)
11,557
def circle(self, radius, extent=None): """ Draw a circle with given radius. The center is radius units left of the turtle; extent determines which part of the circle is drawn. If not given, the entire circle is drawn.
def circle(self, radius, extent = None): """ Draw a circle with given radius. The center is radius units left of the turtle; extent determines which part of the circle is drawn. If not given, the entire circle is drawn.
11,558
def circle(self, radius, extent=None): """ Draw a circle with given radius. The center is radius units left of the turtle; extent determines which part of the circle is drawn. If not given, the entire circle is drawn.
def circle(self, radius, extent=None): """ Draw a circle with given radius. The center is radius units left of the turtle; extent determines which part of the circle is drawn. If not given, the entire circle is drawn.
11,559
def __deepcopy__(self, memo): if type(self) == Decimal: return self # My components are also immutable return self.__class__(str(self))
def __deepcopy__(self, memo): if type(self) == Decimal: return self # My components are also immutable return self.__class__(str(self))
11,560
def __init__(self, prec=None, rounding=None, trap_enablers=None, flags=None, _rounding_decision=None, Emin=None, Emax=None, capitals=1, _clamp=0, _ignored_flags=[]): if flags is None: flags = dict.fromkeys(Signals, 0) self.DefaultLock.acquire() for name, val in locals().items(): if val is None: setattr(self, name, copy.copy(getattr(DefaultContext, name))) else: setattr(self, name, val) self.DefaultLock.release() del self.self
def __init__(self, prec=None, rounding=None, trap_enablers=None, flags=None, _rounding_decision=None, Emin=None, Emax=None, capitals=None, _clamp=0, _ignored_flags=[]): if flags is None: flags = dict.fromkeys(Signals, 0) self.DefaultLock.acquire() for name, val in locals().items(): if val is None: setattr(self, name, copy.copy(getattr(DefaultContext, name))) else: setattr(self, name, val) self.DefaultLock.release() del self.self
11,561
def Etop(self): """Returns maximum exponent (= Emin - prec + 1)""" return int(self.Emax - self.prec + 1)
def Etop(self): """Returns maximum exponent (= Emax - prec + 1)""" return int(self.Emax - self.prec + 1)
11,562
def normalize(self, a): """normalize reduces its operand to its simplest form.
def normalize(self, a): """normalize reduces its operand to its simplest form.
11,563
def _isnan(num): """Determines whether a string or float is NaN (1, sign, diagnostic info as string) => NaN (2, sign, diagnostic info as string) => sNaN 0 => not a NaN """ num = str(num).lower() if not num: return 0 #get the sign, get rid of trailing [+-] sign = 0 if num[0] == '+': num = num[1:] elif num[0] == '-': #elif avoids '+-nan' num = num[1:] sign = 1 if num.startswith('nan'): if len(num) > 3 and not num[3:].isdigit(): #diagnostic info return 0 return (1, sign, num[3:].lstrip('0')) if num.startswith('snan'): if len(num) > 4 and not num[4:].isdigit(): return 0 return (2, sign, num[4:].lstrip('0')) return 0
def _isnan(num): """Determines whether a string or float is NaN (1, sign, diagnostic info as string) => NaN (2, sign, diagnostic info as string) => sNaN 0 => not a NaN """ num = str(num).lower() if not num: return 0 #get the sign, get rid of trailing [+-] sign = 0 if num[0] == '+': num = num[1:] elif num[0] == '-': #elif avoids '+-nan' num = num[1:] sign = 1 if num.startswith('nan'): if len(num) > 3 and not num[3:].isdigit(): #diagnostic info return 0 return (1, sign, num[3:].lstrip('0')) if num.startswith('snan'): if len(num) > 4 and not num[4:].isdigit(): return 0 return (2, sign, num[4:].lstrip('0')) return 0
11,564
def defaultFile(self): """Produce a reasonable default.""" filename = self.curframe.f_code.co_filename if filename == '<string>' and mainpyfile: filename = mainpyfile return filename
def defaultFile(self): """Produce a reasonable default.""" filename = self.curframe.f_code.co_filename if filename == '<string>' and self.mainpyfile: filename = self.mainpyfile return filename
11,565
def lookupmodule(self, filename): """Helper function for break/clear parsing -- may be overridden.""" root, ext = os.path.splitext(filename) if ext == '': filename = filename + '.py' if os.path.isabs(filename): return filename for dirname in sys.path: while os.path.islink(dirname): dirname = os.readlink(dirname) fullname = os.path.join(dirname, filename) if os.path.exists(fullname): return fullname return None
def lookupmodule(self, filename): """Helper function for break/clear parsing -- may be overridden. lookupmodule() translates (possibly incomplete) file or module name into an absolute file name. """ if os.path.isabs(filename) and os.path.exists(filename): return filename f = os.path.join(sys.path[0], filename) if os.path.exists(f) and self.canonic(f) == self.mainpyfile: return f root, ext = os.path.splitext(filename) if ext == '': filename = filename + '.py' if os.path.isabs(filename): return filename for dirname in sys.path: while os.path.islink(dirname): dirname = os.readlink(dirname) fullname = os.path.join(dirname, filename) if os.path.exists(fullname): return fullname return None
11,566
def help(): for dirname in sys.path: fullname = os.path.join(dirname, 'pdb.doc') if os.path.exists(fullname): sts = os.system('${PAGER-more} '+fullname) if sts: print '*** Pager exit status:', sts break else: print 'Sorry, can\'t find the help file "pdb.doc"', print 'along the Python search path'
def help(): for dirname in sys.path: fullname = os.path.join(dirname, 'pdb.doc') if os.path.exists(fullname): sts = os.system('${PAGER-more} '+fullname) if sts: print '*** Pager exit status:', sts break else: print 'Sorry, can\'t find the help file "pdb.doc"', print 'along the Python search path'
11,567
def help(): for dirname in sys.path: fullname = os.path.join(dirname, 'pdb.doc') if os.path.exists(fullname): sts = os.system('${PAGER-more} '+fullname) if sts: print '*** Pager exit status:', sts break else: print 'Sorry, can\'t find the help file "pdb.doc"', print 'along the Python search path'
def help(): for dirname in sys.path: fullname = os.path.join(dirname, 'pdb.doc') if os.path.exists(fullname): sts = os.system('${PAGER-more} '+fullname) if sts: print '*** Pager exit status:', sts break else: print 'Sorry, can\'t find the help file "pdb.doc"', print 'along the Python search path'
11,568
def help(): for dirname in sys.path: fullname = os.path.join(dirname, 'pdb.doc') if os.path.exists(fullname): sts = os.system('${PAGER-more} '+fullname) if sts: print '*** Pager exit status:', sts break else: print 'Sorry, can\'t find the help file "pdb.doc"', print 'along the Python search path'
def help(): for dirname in sys.path: fullname = os.path.join(dirname, 'pdb.doc') if os.path.exists(fullname): sts = os.system('${PAGER-more} '+fullname) if sts: print '*** Pager exit status:', sts break else: print 'Sorry, can\'t find the help file "pdb.doc"', print 'along the Python search path'
11,569
def help(): for dirname in sys.path: fullname = os.path.join(dirname, 'pdb.doc') if os.path.exists(fullname): sts = os.system('${PAGER-more} '+fullname) if sts: print '*** Pager exit status:', sts break else: print 'Sorry, can\'t find the help file "pdb.doc"', print 'along the Python search path'
def help(): for dirname in sys.path: fullname = os.path.join(dirname, 'pdb.doc') if os.path.exists(fullname): sts = os.system('${PAGER-more} '+fullname) if sts: print '*** Pager exit status:', sts break else: print 'Sorry, can\'t find the help file "pdb.doc"', print 'along the Python search path'
11,570
def retrfile(self, file, type): import ftplib self.endtransfer() if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1 else: cmd = 'TYPE ' + type; isdir = 0 try: self.ftp.voidcmd(cmd) except ftplib.all_errors: self.init() self.ftp.voidcmd(cmd) conn = None if file and not isdir: # Use nlst to see if the file exists at all try: self.ftp.nlst(file) except ftplib.error_perm, reason: raise IOError, ('ftp error', reason), sys.exc_info()[2] # Restore the transfer mode! self.ftp.voidcmd(cmd) # Try to retrieve as a file try: cmd = 'RETR ' + file conn = self.ftp.ntransfercmd(cmd) except ftplib.error_perm, reason: if str(reason)[:3] != '550': raise IOError, ('ftp error', reason), sys.exc_info()[2] if not conn: # Set transfer mode to ASCII! self.ftp.voidcmd('TYPE A') # Try a directory listing if file: cmd = 'LIST ' + file else: cmd = 'LIST' conn = self.ftp.ntransfercmd(cmd) self.busy = 1 # Pass back both a suitably decorated object and a retrieval length return (addclosehook(conn[0].makefile('rb'), self.endtransfer), conn[1])
def retrfile(self, file, type): import ftplib self.endtransfer() if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1 else: cmd = 'TYPE ' + type; isdir = 0 try: self.ftp.voidcmd(cmd) except ftplib.all_errors: self.init() self.ftp.voidcmd(cmd) conn = None if file and not isdir: # Use nlst to see if the file exists at all try: self.ftp.nlst(file) except ftplib.error_perm, reason: raise IOError, ('ftp error', reason), sys.exc_info()[2] # Restore the transfer mode! self.ftp.voidcmd(cmd) # Try to retrieve as a file try: cmd = 'RETR ' + file conn = self.ftp.ntransfercmd(cmd) except ftplib.error_perm, reason: if str(reason)[:3] != '550': raise IOError, ('ftp error', reason), sys.exc_info()[2] if not conn: # Set transfer mode to ASCII! self.ftp.voidcmd('TYPE A') # Try a directory listing if file: cmd = 'LIST ' + file else: cmd = 'LIST' conn = self.ftp.ntransfercmd(cmd) self.busy = 1 # Pass back both a suitably decorated object and a retrieval length return (addclosehook(conn[0].makefile('rb'), self.endtransfer), conn[1])
11,571
def urlopen(url, data=None): """urlopen(url [, data]) -> open file-like object""" global _urlopener if not _urlopener: _urlopener = FancyURLopener() if data is None: return _urlopener.open(url) else: return _urlopener.open(url, data)
def urlopen(url, data=None, proxies=None): """urlopen(url [, data]) -> open file-like object""" global _urlopener if not _urlopener: _urlopener = FancyURLopener() if data is None: return _urlopener.open(url) else: return _urlopener.open(url, data)
11,572
def urlopen(url, data=None): """urlopen(url [, data]) -> open file-like object""" global _urlopener if not _urlopener: _urlopener = FancyURLopener() if data is None: return _urlopener.open(url) else: return _urlopener.open(url, data)
def urlopen(url, data=None): """urlopen(url [, data]) -> open file-like object""" global _urlopener if proxies is not None: opener = FancyURLopener(proxies=proxies) elif not _urlopener: opener = FancyURLopener() _urlopener = opener else: opener = _urlopener if data is None: return _urlopener.open(url) else: return _urlopener.open(url, data)
11,573
def urlopen(url, data=None): """urlopen(url [, data]) -> open file-like object""" global _urlopener if not _urlopener: _urlopener = FancyURLopener() if data is None: return _urlopener.open(url) else: return _urlopener.open(url, data)
def urlopen(url, data=None): """urlopen(url [, data]) -> open file-like object""" global _urlopener if not _urlopener: _urlopener = FancyURLopener() if data is None: return opener.open(url) else: return _urlopener.open(url, data)
11,574
def urlopen(url, data=None): """urlopen(url [, data]) -> open file-like object""" global _urlopener if not _urlopener: _urlopener = FancyURLopener() if data is None: return _urlopener.open(url) else: return _urlopener.open(url, data)
def urlopen(url, data=None): """urlopen(url [, data]) -> open file-like object""" global _urlopener if not _urlopener: _urlopener = FancyURLopener() if data is None: return _urlopener.open(url) else: return _urlopener.open(url, data)
11,575
... def foo(cls, y):
... def foo(cls, y):
11,576
... def foo(cls, y):
... def foo(cls, y):
11,577
... def foo(cls, y):
... def foo(cls, y):
11,578
... def foo(cls, y):
... def foo(cls, y):
11,579
... def foo(cls, y): # override C.foo
... def foo(cls, y): # override C.foo
11,580
... def foo(cls, y): # override C.foo
... def foo(cls, y): # override C.foo
11,581
... def setx(self, x):
... def setx(self, x):
11,582
... def save(self):
... def save(self):
11,583
def handle_read (self):
def handle_read (self):
11,584
def mime_decode(line): '''Decode a single line of quoted-printable text to 8bit.''' newline = '' while 1: res = mime_code.search(line) if res is None: break newline = newline + line[:res.start(0)] + \ chr(string.atoi(res.group(1), 16)) line = line[res.end(0):] return newline + line
def mime_decode(line): '''Decode a single line of quoted-printable text to 8bit.''' newline = '' pos = 0 while 1: res = mime_code.search(line, pos) if res is None: break newline = newline + line[:res.start(0)] + \ chr(string.atoi(res.group(1), 16)) line = line[res.end(0):] return newline + line
11,585
def mime_decode(line): '''Decode a single line of quoted-printable text to 8bit.''' newline = '' while 1: res = mime_code.search(line) if res is None: break newline = newline + line[:res.start(0)] + \ chr(string.atoi(res.group(1), 16)) line = line[res.end(0):] return newline + line
def mime_decode(line): '''Decode a single line of quoted-printable text to 8bit.''' newline = '' while 1: res = mime_code.search(line) if res is None: break newline = newline + line[pos:res.start(0)] + \ chr(string.atoi(res.group(1), 16)) line = line[res.end(0):] return newline + line
11,586
def mime_decode(line): '''Decode a single line of quoted-printable text to 8bit.''' newline = '' while 1: res = mime_code.search(line) if res is None: break newline = newline + line[:res.start(0)] + \ chr(string.atoi(res.group(1), 16)) line = line[res.end(0):] return newline + line
def mime_decode(line): '''Decode a single line of quoted-printable text to 8bit.''' newline = '' while 1: res = mime_code.search(line) if res is None: break newline = newline + line[:res.start(0)] + \ chr(string.atoi(res.group(1), 16)) pos = res.end(0) return newline + line[pos:]
11,587
def mime_decode_header(line): '''Decode a header line to 8bit.''' newline = '' while 1: res = mime_head.search(line) if res is None: break match = res.group(1) # convert underscores to spaces (before =XX conversion!) match = string.join(string.split(match, '_'), ' ') newline = newline + line[:res.start(0)] + mime_decode(match) line = line[res.end(0):] return newline + line
def mime_decode_header(line): '''Decode a header line to 8bit.''' newline = '' pos = 0 while 1: res = mime_head.search(line, pos) if res is None: break match = res.group(1) # convert underscores to spaces (before =XX conversion!) match = string.join(string.split(match, '_'), ' ') newline = newline + line[:res.start(0)] + mime_decode(match) line = line[res.end(0):] return newline + line
11,588
def mime_decode_header(line): '''Decode a header line to 8bit.''' newline = '' while 1: res = mime_head.search(line) if res is None: break match = res.group(1) # convert underscores to spaces (before =XX conversion!) match = string.join(string.split(match, '_'), ' ') newline = newline + line[:res.start(0)] + mime_decode(match) line = line[res.end(0):] return newline + line
def mime_decode_header(line): '''Decode a header line to 8bit.''' newline = '' while 1: res = mime_head.search(line) if res is None: break match = res.group(1) # convert underscores to spaces (before =XX conversion!) match = string.join(string.split(match, '_'), ' ') newline = newline + line[pos:res.start(0)] + mime_decode(match) pos = res.end(0) return newline + line[pos:]
11,589
def mime_encode(line, header): '''Code a single line as quoted-printable. If header is set, quote some extra characters.''' if header: reg = mime_header_char else: reg = mime_char newline = '' if len(line) >= 5 and line[:5] == 'From ': # quote 'From ' at the start of a line for stupid mailers newline = string.upper('=%02x' % ord('F')) line = line[1:] while 1: res = reg.search(line) if res is None: break newline = newline + line[:res.start(0)] + \ string.upper('=%02x' % ord(line[res.group(0)])) line = line[res.end(0):] line = newline + line newline = '' while len(line) >= 75: i = 73 while line[i] == '=' or line[i-1] == '=': i = i - 1 i = i + 1 newline = newline + line[:i] + '=\n' line = line[i:] return newline + line
def mime_encode(line, header): '''Code a single line as quoted-printable. If header is set, quote some extra characters.''' if header: reg = mime_header_char else: reg = mime_char newline = '' if len(line) >= 5 and line[:5] == 'From ': # quote 'From ' at the start of a line for stupid mailers newline = string.upper('=%02x' % ord('F')) pos = 1 while 1: res = reg.search(line, pos) if res is None: break newline = newline + line[:res.start(0)] + \ string.upper('=%02x' % ord(line[res.group(0)])) line = line[res.end(0):] line = newline + line newline = '' while len(line) >= 75: i = 73 while line[i] == '=' or line[i-1] == '=': i = i - 1 i = i + 1 newline = newline + line[:i] + '=\n' line = line[i:] return newline + line
11,590
def mime_encode(line, header): '''Code a single line as quoted-printable. If header is set, quote some extra characters.''' if header: reg = mime_header_char else: reg = mime_char newline = '' if len(line) >= 5 and line[:5] == 'From ': # quote 'From ' at the start of a line for stupid mailers newline = string.upper('=%02x' % ord('F')) line = line[1:] while 1: res = reg.search(line) if res is None: break newline = newline + line[:res.start(0)] + \ string.upper('=%02x' % ord(line[res.group(0)])) line = line[res.end(0):] line = newline + line newline = '' while len(line) >= 75: i = 73 while line[i] == '=' or line[i-1] == '=': i = i - 1 i = i + 1 newline = newline + line[:i] + '=\n' line = line[i:] return newline + line
def mime_encode(line, header): '''Code a single line as quoted-printable. If header is set, quote some extra characters.''' if header: reg = mime_header_char else: reg = mime_char newline = '' if len(line) >= 5 and line[:5] == 'From ': # quote 'From ' at the start of a line for stupid mailers newline = string.upper('=%02x' % ord('F')) line = line[1:] while 1: res = reg.search(line) if res is None: break newline = newline + line[pos:res.start(0)] + \ string.upper('=%02x' % ord(res.group(0))) pos = res.end(0) line = newline + line[pos:] newline = '' while len(line) >= 75: i = 73 while line[i] == '=' or line[i-1] == '=': i = i - 1 i = i + 1 newline = newline + line[:i] + '=\n' line = line[i:] return newline + line
11,591
def mime_encode_header(line): '''Code a single header line as quoted-printable.''' newline = '' while 1: res = mime_header.search(line) if res is None: break newline = newline + line[:res.start(0)] + res.group(1) + \ '=?' + CHARSET + '?Q?' + \ mime_encode(res.group(2), 1) + \ '?=' + res.group(3) line = line[res.end(0):] return newline + line
def mime_encode_header(line): '''Code a single header line as quoted-printable.''' newline = '' pos = 0 while 1: res = mime_header.search(line, pos) if res is None: break newline = newline + line[:res.start(0)] + res.group(1) + \ '=?' + CHARSET + '?Q?' + \ mime_encode(res.group(2), 1) + \ '?=' + res.group(3) line = line[res.end(0):] return newline + line
11,592
def mime_encode_header(line): '''Code a single header line as quoted-printable.''' newline = '' while 1: res = mime_header.search(line) if res is None: break newline = newline + line[:res.start(0)] + res.group(1) + \ '=?' + CHARSET + '?Q?' + \ mime_encode(res.group(2), 1) + \ '?=' + res.group(3) line = line[res.end(0):] return newline + line
def mime_encode_header(line): '''Code a single header line as quoted-printable.''' newline = '' while 1: res = mime_header.search(line) if res is None: break newline = '%s%s%s=?%s?Q?%s?=%s' % \ (newline, line[pos:res.start(0)], res.group(1), CHARSET, mime_encode(res.group(2), 1), res.group(3)) pos = res.end(0) return newline + line[pos:]
11,593
def mimify_part(ifile, ofile, is_mime): '''Convert an 8bit part of a MIME mail message to quoted-printable.''' has_cte = is_qp = is_base64 = 0 multipart = None must_quote_body = must_quote_header = has_iso_chars = 0 header = [] header_end = '' message = [] message_end = '' # read header hfile = HeaderFile(ifile) while 1: line = hfile.readline() if not line: break if not must_quote_header and iso_char.search(line): must_quote_header = 1 if mv.match(line): is_mime = 1 if cte.match(line): has_cte = 1 if qp.match(line): is_qp = 1 elif base64_re.match(line): is_base64 = 1 mp_res = mp.match(line) if mp_res: multipart = '--' + mp_res.group(1) if he.match(line): header_end = line break header.append(line) # read body while 1: line = ifile.readline() if not line: break if multipart: if line == multipart + '--\n': message_end = line break if line == multipart + '\n': message_end = line break if is_base64: message.append(line) continue if is_qp: while line[-2:] == '=\n': line = line[:-2] newline = ifile.readline() if newline[:len(QUOTE)] == QUOTE: newline = newline[len(QUOTE):] line = line + newline line = mime_decode(line) message.append(line) if not has_iso_chars: if iso_char.search(line): has_iso_chars = must_quote_body = 1 if not must_quote_body: if len(line) > MAXLEN: must_quote_body = 1 # convert and output header and body for line in header: if must_quote_header: line = mime_encode_header(line) chrset_res = chrset.match(line) if chrset_res: if has_iso_chars: # change us-ascii into iso-8859-1 if string.lower(chrset_res.group(2)) == 'us-ascii': line = chrset_res.group(1) + \ CHARSET + chrset_res.group(3) else: # change iso-8859-* into us-ascii line = chrset_res.group(1) + 'us-ascii' + chrset_res.group(3) if has_cte and cte.match(line): line = 'Content-Transfer-Encoding: ' if is_base64: line = line + 'base64\n' elif must_quote_body: line = line + 'quoted-printable\n' else: line = line + '7bit\n' ofile.write(line) if (must_quote_header or must_quote_body) and not is_mime: ofile.write('Mime-Version: 1.0\n') ofile.write('Content-Type: text/plain; ') if has_iso_chars: ofile.write('charset="%s"\n' % CHARSET) else: ofile.write('charset="us-ascii"\n') if must_quote_body and not has_cte: ofile.write('Content-Transfer-Encoding: quoted-printable\n') ofile.write(header_end) for line in message: if must_quote_body: line = mime_encode(line, 0) ofile.write(line) ofile.write(message_end) line = message_end while multipart: if line == multipart + '--\n': # read bit after the end of the last part while 1: line = ifile.readline() if not line: return if must_quote_body: line = mime_encode(line, 0) ofile.write(line) if line == multipart + '\n': nifile = File(ifile, multipart) mimify_part(nifile, ofile, 1) line = nifile.peek ofile.write(line) continue
def mimify_part(ifile, ofile, is_mime): '''Convert an 8bit part of a MIME mail message to quoted-printable.''' has_cte = is_qp = is_base64 = 0 multipart = None must_quote_body = must_quote_header = has_iso_chars = 0 header = [] header_end = '' message = [] message_end = '' # read header hfile = HeaderFile(ifile) while 1: line = hfile.readline() if not line: break if not must_quote_header and iso_char.search(line): must_quote_header = 1 if mv.match(line): is_mime = 1 if cte.match(line): has_cte = 1 if qp.match(line): is_qp = 1 elif base64_re.match(line): is_base64 = 1 mp_res = mp.match(line) if mp_res: multipart = '--' + mp_res.group(1) if he.match(line): header_end = line break header.append(line) # read body while 1: line = ifile.readline() if not line: break if multipart: if line == multipart + '--\n': message_end = line break if line == multipart + '\n': message_end = line break if is_base64: message.append(line) continue if is_qp: while line[-2:] == '=\n': line = line[:-2] newline = ifile.readline() if newline[:len(QUOTE)] == QUOTE: newline = newline[len(QUOTE):] line = line + newline line = mime_decode(line) message.append(line) if not has_iso_chars: if iso_char.search(line): has_iso_chars = must_quote_body = 1 if not must_quote_body: if len(line) > MAXLEN: must_quote_body = 1 # convert and output header and body for line in header: if must_quote_header: line = mime_encode_header(line) chrset_res = chrset.match(line) if chrset_res: if has_iso_chars: # change us-ascii into iso-8859-1 if string.lower(chrset_res.group(2)) == 'us-ascii': line = '%s%s%s' % (chrset_res.group(1), CHARSET, chrset_res.group(3)) else: # change iso-8859-* into us-ascii line = chrset_res.group(1) + 'us-ascii' + chrset_res.group(3) if has_cte and cte.match(line): line = 'Content-Transfer-Encoding: ' if is_base64: line = line + 'base64\n' elif must_quote_body: line = line + 'quoted-printable\n' else: line = line + '7bit\n' ofile.write(line) if (must_quote_header or must_quote_body) and not is_mime: ofile.write('Mime-Version: 1.0\n') ofile.write('Content-Type: text/plain; ') if has_iso_chars: ofile.write('charset="%s"\n' % CHARSET) else: ofile.write('charset="us-ascii"\n') if must_quote_body and not has_cte: ofile.write('Content-Transfer-Encoding: quoted-printable\n') ofile.write(header_end) for line in message: if must_quote_body: line = mime_encode(line, 0) ofile.write(line) ofile.write(message_end) line = message_end while multipart: if line == multipart + '--\n': # read bit after the end of the last part while 1: line = ifile.readline() if not line: return if must_quote_body: line = mime_encode(line, 0) ofile.write(line) if line == multipart + '\n': nifile = File(ifile, multipart) mimify_part(nifile, ofile, 1) line = nifile.peek ofile.write(line) continue
11,594
def mimify_part(ifile, ofile, is_mime): '''Convert an 8bit part of a MIME mail message to quoted-printable.''' has_cte = is_qp = is_base64 = 0 multipart = None must_quote_body = must_quote_header = has_iso_chars = 0 header = [] header_end = '' message = [] message_end = '' # read header hfile = HeaderFile(ifile) while 1: line = hfile.readline() if not line: break if not must_quote_header and iso_char.search(line): must_quote_header = 1 if mv.match(line): is_mime = 1 if cte.match(line): has_cte = 1 if qp.match(line): is_qp = 1 elif base64_re.match(line): is_base64 = 1 mp_res = mp.match(line) if mp_res: multipart = '--' + mp_res.group(1) if he.match(line): header_end = line break header.append(line) # read body while 1: line = ifile.readline() if not line: break if multipart: if line == multipart + '--\n': message_end = line break if line == multipart + '\n': message_end = line break if is_base64: message.append(line) continue if is_qp: while line[-2:] == '=\n': line = line[:-2] newline = ifile.readline() if newline[:len(QUOTE)] == QUOTE: newline = newline[len(QUOTE):] line = line + newline line = mime_decode(line) message.append(line) if not has_iso_chars: if iso_char.search(line): has_iso_chars = must_quote_body = 1 if not must_quote_body: if len(line) > MAXLEN: must_quote_body = 1 # convert and output header and body for line in header: if must_quote_header: line = mime_encode_header(line) chrset_res = chrset.match(line) if chrset_res: if has_iso_chars: # change us-ascii into iso-8859-1 if string.lower(chrset_res.group(2)) == 'us-ascii': line = chrset_res.group(1) + \ CHARSET + chrset_res.group(3) else: # change iso-8859-* into us-ascii line = chrset_res.group(1) + 'us-ascii' + chrset_res.group(3) if has_cte and cte.match(line): line = 'Content-Transfer-Encoding: ' if is_base64: line = line + 'base64\n' elif must_quote_body: line = line + 'quoted-printable\n' else: line = line + '7bit\n' ofile.write(line) if (must_quote_header or must_quote_body) and not is_mime: ofile.write('Mime-Version: 1.0\n') ofile.write('Content-Type: text/plain; ') if has_iso_chars: ofile.write('charset="%s"\n' % CHARSET) else: ofile.write('charset="us-ascii"\n') if must_quote_body and not has_cte: ofile.write('Content-Transfer-Encoding: quoted-printable\n') ofile.write(header_end) for line in message: if must_quote_body: line = mime_encode(line, 0) ofile.write(line) ofile.write(message_end) line = message_end while multipart: if line == multipart + '--\n': # read bit after the end of the last part while 1: line = ifile.readline() if not line: return if must_quote_body: line = mime_encode(line, 0) ofile.write(line) if line == multipart + '\n': nifile = File(ifile, multipart) mimify_part(nifile, ofile, 1) line = nifile.peek ofile.write(line) continue
def mimify_part(ifile, ofile, is_mime): '''Convert an 8bit part of a MIME mail message to quoted-printable.''' has_cte = is_qp = is_base64 = 0 multipart = None must_quote_body = must_quote_header = has_iso_chars = 0 header = [] header_end = '' message = [] message_end = '' # read header hfile = HeaderFile(ifile) while 1: line = hfile.readline() if not line: break if not must_quote_header and iso_char.search(line): must_quote_header = 1 if mv.match(line): is_mime = 1 if cte.match(line): has_cte = 1 if qp.match(line): is_qp = 1 elif base64_re.match(line): is_base64 = 1 mp_res = mp.match(line) if mp_res: multipart = '--' + mp_res.group(1) if he.match(line): header_end = line break header.append(line) # read body while 1: line = ifile.readline() if not line: break if multipart: if line == multipart + '--\n': message_end = line break if line == multipart + '\n': message_end = line break if is_base64: message.append(line) continue if is_qp: while line[-2:] == '=\n': line = line[:-2] newline = ifile.readline() if newline[:len(QUOTE)] == QUOTE: newline = newline[len(QUOTE):] line = line + newline line = mime_decode(line) message.append(line) if not has_iso_chars: if iso_char.search(line): has_iso_chars = must_quote_body = 1 if not must_quote_body: if len(line) > MAXLEN: must_quote_body = 1 # convert and output header and body for line in header: if must_quote_header: line = mime_encode_header(line) chrset_res = chrset.match(line) if chrset_res: if has_iso_chars: # change us-ascii into iso-8859-1 if string.lower(chrset_res.group(2)) == 'us-ascii': line = chrset_res.group(1) + \ CHARSET + chrset_res.group(3) else: # change iso-8859-* into us-ascii line = '%sus-ascii%s' % chrset_res.group(1, 3) if has_cte and cte.match(line): line = 'Content-Transfer-Encoding: ' if is_base64: line = line + 'base64\n' elif must_quote_body: line = line + 'quoted-printable\n' else: line = line + '7bit\n' ofile.write(line) if (must_quote_header or must_quote_body) and not is_mime: ofile.write('Mime-Version: 1.0\n') ofile.write('Content-Type: text/plain; ') if has_iso_chars: ofile.write('charset="%s"\n' % CHARSET) else: ofile.write('charset="us-ascii"\n') if must_quote_body and not has_cte: ofile.write('Content-Transfer-Encoding: quoted-printable\n') ofile.write(header_end) for line in message: if must_quote_body: line = mime_encode(line, 0) ofile.write(line) ofile.write(message_end) line = message_end while multipart: if line == multipart + '--\n': # read bit after the end of the last part while 1: line = ifile.readline() if not line: return if must_quote_body: line = mime_encode(line, 0) ofile.write(line) if line == multipart + '\n': nifile = File(ifile, multipart) mimify_part(nifile, ofile, 1) line = nifile.peek ofile.write(line) continue
11,595
def test(HandlerClass = SimpleHTTPRequestHandler, ServerClass = SocketServer.TCPServer): BaseHTTPServer.test(HandlerClass, ServerClass)
def test(HandlerClass = SimpleHTTPRequestHandler, ServerClass = BaseHTTPServer.HTTPServer): BaseHTTPServer.test(HandlerClass, ServerClass)
11,596
def __init__ (self, verbose=0, dry_run=0, force=0):
def __init__ (self, verbose=0, dry_run=0, force=0):
11,597
def makefile(self, mode, bufsize=None): """Return a readable file-like object with data from socket.
def makefile(self, mode, bufsize=None): """Return a readable file-like object with data from socket.
11,598
def log_request(self, code='-', size='-'): """Log an accepted request.
def log_request(self, code='-', size='-'): """Log an accepted request.
11,599