rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
srpms = glob.glob(os.path.join(rpm_dir['SRPMS'], "*.rpm")) rpms = glob.glob(os.path.join(rpm_dir['RPMS'], "*/*.rpm")) assert len(srpms) == 1, \ "unexpected number of SRPM files found: %s" % srpms assert len(rpms) == 1, \ "unexpected number of RPM files found: %s" % rpms self.move_file(srpms[0], self.dist_dir) self.move...
if not self.binary_only: srpms = glob.glob(os.path.join(rpm_dir['SRPMS'], "*.rpm")) assert len(srpms) == 1, \ "unexpected number of SRPM files found: %s" % srpms self.move_file(srpms[0], self.dist_dir) if not self.source_only: rpms = glob.glob(os.path.join(rpm_dir['RPMS'], "*/*.rpm")) assert len(rpms) == 1, \ "unexpec...
def run (self):
def wm_iconbitmap(self, bitmap=None):
def wm_iconbitmap(self, bitmap=None, default=None):
def wm_iconbitmap(self, bitmap=None): """Set bitmap for the iconified widget to BITMAP. Return the bitmap if None is given.""" return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
the bitmap if None is given.""" return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
the bitmap if None is given. Under Windows, the DEFAULT parameter can be used to set the icon for the widget and any descendents that don't have an icon set explicitely. DEFAULT can be the relative path to a .ico file (example: root.iconbitmap(default='myicon.ico') ). See Tk documentation for more information.""" if...
def wm_iconbitmap(self, bitmap=None): """Set bitmap for the iconified widget to BITMAP. Return the bitmap if None is given.""" return self.tk.call('wm', 'iconbitmap', self._w, bitmap)
import pdb ; pdb.set_trace()
def buildcopy(top, dummy, list): import macostools for src, dst in list: src = os.path.join(top, src) dst = os.path.join(top, dst) import pdb ; pdb.set_trace() macostools.copy(src, dst)
FInfo = OpaqueByValueStructType("FInfo", "PyMac_BuildFInfo", "PyMac_GetFInfo") FInfo_ptr = OpaqueType("FInfo", "PyMac_BuildFInfo", "PyMac_GetFInfo")
FInfo = OpaqueType("FInfo", "FInfo") FInfo_ptr = OpaqueType("FInfo", "FInfo")
def declare(self, name): Output("%s %s__buf__;", self.typeName, name) Output("%s *%s = &%s__buf__;", self.typeName, name, name)
extern PyObject *FSRef_New(FSRef *itself); extern PyObject *FSSpec_New(FSSpec *itself); extern PyObject *Alias_New(AliasHandle itself); extern int FSRef_Convert(PyObject *v, FSRef *p_itself); extern int FSSpec_Convert(PyObject *v, FSSpec *p_itself); extern int Alias_Convert(PyObject *v, AliasHandle *p_itself); static i...
static PyObject *FInfo_New(FInfo *itself); static PyObject *FSRef_New(FSRef *itself); static PyObject *FSSpec_New(FSSpec *itself); static PyObject *Alias_New(AliasHandle itself); static int FInfo_Convert(PyObject *v, FInfo *p_itself); static int Alias_Convert(PyObject *v, AliasHandle *p_itself);
#ifdef WITHOUT_FRAMEWORKS
return myPyMac_GetFSSpec(v, *spec);
return PyMac_GetFSSpec(v, *spec);
#ifdef WITHOUT_FRAMEWORKS
return myPyMac_GetFSRef(v, *ref);
return PyMac_GetFSRef(v, *ref);
#ifdef WITHOUT_FRAMEWORKS
/* ** Parse/generate objsect */ static PyObject * PyMac_BuildFInfo(FInfo *itself) { return Py_BuildValue("O&O&HO&h", PyMac_BuildOSType, itself->fdType, PyMac_BuildOSType, itself->fdCreator, itself->fdFlags, PyMac_BuildPoint, &itself->fdLocation, itself->fdFldr); } static int PyMac_GetFInfo(PyObject *v, FInfo *itself)...
#ifdef WITHOUT_FRAMEWORKS
static int myPyMac_GetFSSpec(PyObject *v, FSSpec *spec)
int PyMac_GetFSSpec(PyObject *v, FSSpec *spec)
#ifdef WITHOUT_FRAMEWORKS
if ( myPyMac_GetFSRef(v, &fsr) ) {
if ( PyMac_GetFSRef(v, &fsr) ) {
#ifdef WITHOUT_FRAMEWORKS
static int myPyMac_GetFSRef(PyObject *v, FSRef *fsr)
int PyMac_GetFSRef(PyObject *v, FSRef *fsr)
#ifdef WITHOUT_FRAMEWORKS
class FSSpecDefinition(PEP253Mixin, GlobalObjectDefinition):
class FInfoDefinition(PEP253Mixin, ObjectDefinition): getsetlist = [ ("Type", "return Py_BuildValue(\"O&\", PyMac_BuildOSType, self->ob_itself.fdType);", "return PyArg_Parse(v, \"O&\", PyMac_GetOSType, &self->ob_itself.fdType)-1;", "4-char file type" ), ("Creator", "return Py_BuildValue(\"O&\", PyMac_BuildOSType, self-...
#ifdef WITHOUT_FRAMEWORKS
GlobalObjectDefinition.__init__(self, name, prefix, itselftype)
ObjectDefinition.__init__(self, name, prefix, itselftype)
def __init__(self, name, prefix, itselftype): GlobalObjectDefinition.__init__(self, name, prefix, itselftype) self.argref = "*" # Store FSSpecs, but pass them by address
self.objecttype, self.objecttype)
self.objecttype, self.itselftype)
def output_tp_newBody(self): Output("PyObject *self;"); Output() Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;") Output("memset(&((%s *)self)->ob_itself, 0, sizeof(%s));", self.objecttype, self.objecttype) Output("return self;")
Output("if (myPyMac_GetFSSpec(v, &((%s *)self)->ob_itself)) return 0;", self.objecttype)
Output("if (PyMac_GetFSSpec(v, &((%s *)self)->ob_itself)) return 0;", self.objecttype)
def output_tp_initBody(self): Output("PyObject *v = NULL;") Output("char *rawdata = NULL;") Output("int rawdatalen = 0;") Output("char *kw[] = {\"itself\", \"rawdata\", 0};") Output() Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|Os#\", kw, &v, &rawdata, &rawdatalen))") Output("return -1;") Output("if (v && r...
class FSRefDefinition(PEP253Mixin, GlobalObjectDefinition):
class FSRefDefinition(PEP253Mixin, ObjectDefinition):
def outputRepr(self): Output() Output("static PyObject * %s_repr(%s *self)", self.prefix, self.objecttype) OutLbrace() Output("char buf[512];") Output("""PyOS_snprintf(buf, sizeof(buf), \"%%s((%%d, %%ld, '%%.*s'))\", self->ob_type->tp_name, self->ob_itself.vRefNum, self->ob_itself.parID, self->ob_itself.name[0], self->...
GlobalObjectDefinition.__init__(self, name, prefix, itselftype)
ObjectDefinition.__init__(self, name, prefix, itselftype)
def __init__(self, name, prefix, itselftype): GlobalObjectDefinition.__init__(self, name, prefix, itselftype) self.argref = "*" # Store FSRefs, but pass them by address
Output("if (myPyMac_GetFSRef(v, &((%s *)self)->ob_itself)) return 0;", self.objecttype)
Output("if (PyMac_GetFSRef(v, &((%s *)self)->ob_itself)) return 0;", self.objecttype)
def output_tp_initBody(self): Output("PyObject *v = NULL;") Output("char *rawdata = NULL;") Output("int rawdatalen = 0;") Output("char *kw[] = {\"itself\", \"rawdata\", 0};") Output() Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|Os#\", kw, &v, &rawdata, &rawdatalen))") Output("return -1;") Output("if (v && r...
class AliasDefinition(PEP253Mixin, GlobalObjectDefinition):
class AliasDefinition(PEP253Mixin, ObjectDefinition):
def output_tp_initBody(self): Output("PyObject *v = NULL;") Output("char *rawdata = NULL;") Output("int rawdatalen = 0;") Output("char *kw[] = {\"itself\", \"rawdata\", 0};") Output() Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|Os#\", kw, &v, &rawdata, &rawdatalen))") Output("return -1;") Output("if (v && r...
GlobalObjectDefinition.outputStructMembers(self)
ObjectDefinition.outputStructMembers(self)
def outputStructMembers(self): GlobalObjectDefinition.outputStructMembers(self) Output("void (*ob_freeit)(%s ptr);", self.itselftype)
GlobalObjectDefinition.outputInitStructMembers(self)
ObjectDefinition.outputInitStructMembers(self)
def outputInitStructMembers(self): GlobalObjectDefinition.outputInitStructMembers(self) Output("it->ob_freeit = NULL;")
for pat in ("*upgrade", "*install"):
for pat in ("*upgrade", "*install", "*flight"):
def _addResources(self): "Add Welcome/ReadMe/License files, .lproj folders and scripts."
elif f in ["pre-upgrade", "pre-install", "post-upgrade", "post-install"]: files.append((f, self.packageInfo["Title"]+"."+f)) elif f[-8:] == "-upgrade":
elif basename(f) in ["pre_upgrade", "pre_install", "post_upgrade", "post_install"]: files.append((f, packageName+"."+basename(f))) elif basename(f) in ["preflight", "postflight"]: files.append((f, f)) elif f[-8:] == "_upgrade":
def _addResources(self): "Add Welcome/ReadMe/License files, .lproj folders and scripts."
elif f[-8:] == "-install":
elif f[-8:] == "_install":
def _addResources(self): "Add Welcome/ReadMe/License files, .lproj folders and scripts."
prog = prog + self.compiler.exe_extension
if self.compiler.exe_extension is not None: prog = prog + self.compiler.exe_extension
def _link (self, body, headers, include_dirs, libraries, library_dirs, lang): (src, obj) = self._compile(body, headers, include_dirs, lang) prog = os.path.splitext(os.path.basename(src))[0] self.compiler.link_executable([obj], prog, libraries=libraries, library_dirs=library_dirs, target_lang=lang)
_header_parser = email.Parser.HeaderParser()
def nolog(*allargs): """Dummy function, assigned to log when logging is disabled.""" pass
headers = _header_parser.parse(fp)
headers = mimetools.Message(fp)
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 ...
headers: a dictionary(-like) object (sometimes email.Message.Message or a subclass thereof) containing *all* headers
headers: a dictionary(-like) object (sometimes rfc822.Message or a subclass thereof) containing *all* headers
def __repr__(self): """Return printable representation.""" return "MiniFieldStorage(%r, %r)" % (self.name, self.value)
headers = _header_parser.parse(self.fp)
headers = rfc822.Message(self.fp)
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....
Single = any(r"[^'\\]", r'\\.') + "'" Double = any(r'[^"\\]', r'\\.') + '"' Single3 = any(r"[^'\\]",r'\\.',r"'[^'\\]",r"'\\.",r"''[^'\\]",r"''\\.") + "'''" Double3 = any(r'[^"\\]',r'\\.',r'"[^"\\]',r'"\\.',r'""[^"\\]',r'""\\.') + '"""'
Single = r"[^'\\]*(?:\\.[^'\\]*)*'" Double = r'[^"\\]*(?:\\.[^"\\]*)*"' Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''" Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
def maybe(*choices): return apply(group, choices) + '?'
String = group("[rR]?'" + any(r"[^\n'\\]", r'\\.') + "'", '[rR]?"' + any(r'[^\n"\\]', r'\\.') + '"') Operator = group('\+=', '\-=', '\*=', '%=', '/=', '\*\*=', '&=', '\|=', '\^=', '>>=', '<<=', '\+', '\-', '\*\*', '\*', '\^', '~', '/', '%', '&', '\|', '<<', '>>', '==', '<=', '<>', '!=', '>=', '=', '<', '>')
String = group(r"[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*'", r'[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*"') Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=", r"[+\-*/%&|^=<>]=?", r"~")
def maybe(*choices): return apply(group, choices) + '?'
ContStr = group("[rR]?'" + any(r'\\.', r"[^\n'\\]") + group("'", r'\\\r?\n'), '[rR]?"' + any(r'\\.', r'[^\n"\\]') + group('"', r'\\\r?\n'))
ContStr = group(r"[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*" + group("'", r'\\\r?\n'), r'[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*' + group('"', r'\\\r?\n'))
def maybe(*choices): return apply(group, choices) + '?'
sizehint, if given, is passed as size argument to the stream's .read() method. """ if sizehint is None: data = self.stream.read() else: data = self.stream.read(sizehint)
sizehint, if given, is ignored since there is no efficient way to finding the true end-of-line. """ data = self.stream.read()
def readlines(self, sizehint=None):
if sizehint is None: data = self.reader.read() else: data = self.reader.read(sizehint)
data = self.reader.read()
def readlines(self, sizehint=None):
return self._attrs[attname].value
try: return self._attrs[attname].value except KeyError: return ""
def getAttribute(self, attname): return self._attrs[attname].value
return self._attrsNS[(namespaceURI, localName)].value
try: return self._attrsNS[(namespaceURI, localName)].value except KeyError: return ""
def getAttributeNS(self, namespaceURI, localName): return self._attrsNS[(namespaceURI, localName)].value
return self._attrsNS[(namespaceURI, localName)]
return self._attrsNS.get((namespaceURI, localName))
def getAttributeNodeNS(self, namespaceURI, localName): return self._attrsNS[(namespaceURI, localName)]
raise xml.dom.NamespaceErr("illegal use of prefix without namespaces")
raise xml.dom.NamespaceErr( "illegal use of prefix without namespaces") element = doc.createElementNS(namespaceURI, qualifiedName) doc.appendChild(element)
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 ...
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)
days.append(_center(s, width))
days.append(s.center(width))
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)
days.append(_center(names[i%7][:width], width))
days.append(names[i%7][:width].center(width))
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)
s = (_center(month_name[themonth] + ' ' + `theyear`,
s = ((month_name[themonth] + ' ' + `theyear`).center(
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).rs...
return (_center(a, colwidth) + ' ' * spacing + _center(b, colwidth) + ' ' * spacing + _center(c, colwidth))
return (a.center(colwidth) + ' ' * spacing + b.center(colwidth) + ' ' * spacing + c.center(colwidth))
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))
s = _center(`year`, colwidth * 3 + c * 2).rstrip() + '\n' * l
s = `year`.center(colwidth * 3 + c * 2).rstrip() + '\n' * l
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(...
except string.atoi_error: port = None
except string.atoi_error: pass
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, ...
(f, file, (suffix, mode, type)) = imp.find_module(name)
(f, file, (suffix, mode, type)) = _find_module(name)
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 op...
_platform_cache = {True:None, False:None} _platform_aliased_cache = {True:None, False:None}
_platform_cache_terse = None _platform_cache_not_terse = None _platform_aliased_cache_terse = None _platform_aliased_cache_not_terse = None
def python_compiler(): """ Returns a string identifying the compiler used for compiling Python. """ return _sys_version()[3]
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)]
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_cac...
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 ...
if aliased: _platform_aliased_cache[bool(terse)] = platform
if aliased and terse: _platform_aliased_cache_terse = platform elif aliased and not terse: _platform_aliased_cache_not_terse = 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 ...
_platform_cache[bool(terse)] = platform
if terse: _platform_cache_terse = platform else: _platform_cache_not_terse = 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 ...
char *cStr = PyString_AsString(v); *p_itself = CFStringCreateWithCString((CFAllocatorRef)NULL, cStr, 0);
char *cStr; if (!PyArg_Parse(v, "et", "ascii", &cStr)) return NULL; *p_itself = CFStringCreateWithCString((CFAllocatorRef)NULL, cStr, kCFStringEncodingASCII);
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 differe...
try: from os import popen2 except NameError:
if hasattr(os, "popen2"): 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.""" w, r = os.popen2(cmd, mode, bufsize) return r, w else:
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
try: from os import popen3 except NameError:
if hasattr(os, "popen3"): 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.""" w, r, e = os.popen3(cmd, mode, bufsize) return r, w, e...
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'...
try: from os import popen4 except NameError: pass
if hasattr(os, "popen4"): def popen4(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_stderr, child_stdin) are returned.""" w, r = os.popen4(cmd, mode, bufsize) return r, w else: pass
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 mod...
if c in '/\\':
if c in ['/','\\']:
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
elif c == '.' or ext:
elif c == '.': if ext: root, ext = root + ext, c else: ext = c elif 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
def formatmonthname(self, theyear, themonth, width):
def formatmonthname(self, theyear, themonth, width, withyear=True):
def formatmonthname(self, theyear, themonth, width): """ Return a formatted month name. """ s = "%s %r" % (month_name[themonth], theyear) return s.center(width)
s = "%s %r" % (month_name[themonth], theyear)
s = month_name[themonth] if withyear: s = "%s %r" % (s, theyear)
def formatmonthname(self, theyear, themonth, width): """ Return a formatted month name. """ s = "%s %r" % (month_name[themonth], theyear) return s.center(width)
a(formatstring((month_name[k] for k in months), colwidth, c).rstrip())
names = (self.formatmonthname(theyear, k, colwidth, False) for k in months) a(formatstring(names, colwidth, c).rstrip())
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...
a(formatstring((header for k in months), colwidth, c).rstrip())
headers = (header for k in months) a(formatstring(headers, colwidth, c).rstrip())
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...
return ''.join(v).encode(encoding)
return ''.join(v).encode(encoding, "xmlcharrefreplace") class LocaleTextCalendar(TextCalendar): """ This class can be passed a locale name in the constructor and will return month and weekday names in the specified locale. If this locale includes an encoding all strings containing month and weekday names will be retu...
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 Stric...
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...
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 (defaul...
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 o...
cal = HTMLCalendar()
if options.locale: cal = LocaleHTMLCalendar(locale=options.locale) else: cal = HTMLCalendar()
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 o...
cal = TextCalendar()
if options.locale: cal = LocaleTextCalendar(locale=options.locale) else: cal = TextCalendar()
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 o...
print cal.formatyear(datetime.date.today().year, **optdict)
result = cal.formatyear(datetime.date.today().year, **optdict)
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 o...
print cal.formatyear(int(args[1]), **optdict)
result = cal.formatyear(int(args[1]), **optdict)
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 o...
print cal.formatmonth(int(args[1]), int(args[2]), **optdict)
result = cal.formatmonth(int(args[1]), int(args[2]), **optdict)
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 o...
def abspath(p): return normpath(join(os.getcwd(), p))
abspath = os.expand
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))
while args and args[0][0] == '-' and args[0] <> '-':
while args and args[0][:1] == '-' and args[0] <> '-':
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 ...
self.package_dir = self.distribution.package_dir
self.package_dir = {} if self.distribution.package_dir: for name, path in self.distribution.package_dir.items(): self.package_dir[name] = convert_path(path)
def finalize_options (self): self.set_undefined_options('build', ('build_lib', 'build_lib'), ('force', 'force'))
def scan_dragto(self, x, y): """Adjust the view of the canvas to 10 times the
def scan_dragto(self, x, y, gain=10): """Adjust the view of the canvas to GAIN times the
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)
self.tk.call(self._w, 'scan', 'dragto', x, y)
self.tk.call(self._w, 'scan', 'dragto', x, y, gain)
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)
extent = self._fullcircle x0, y0 = self._position xc = x0 - radius * sin(self._angle * self._invradian) yc = y0 - radius * cos(self._angle * self._invradian) if radius >= 0.0: start = self._angle - (self._fullcircle / 4.0) else: start = self._angle + (self._fullcircle / 4.0) extent = -extent if self._filling: if abs(ex...
extent = self._fullcircle frac = abs(extent)/self._fullcircle steps = 1+int(min(11+abs(radius)/6.0, 59.0)*frac) w = 1.0 * extent / steps w2 = 0.5 * w l = 2.0 * radius * sin(w2*self._invradian) if radius < 0: l, w, w2 = -l, -w, -w2 self.left(w2) for i in range(steps): self.forward(l) self.left(w) self.right(w2)
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.
(Defaults to 1) clamp - If 1, change exponents if too high (Default 0)
_clamp - If 1, change exponents if too high (Default 0)
def __deepcopy__(self, memo): if type(self) == Decimal: return self # My components are also immutable return self.__class__(str(self))
capitals=1, _clamp=0,
capitals=None, _clamp=0,
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...
"""normalize reduces its operand to its simplest form.
"""normalize reduces an operand to its simplest form.
def normalize(self, a): """normalize reduces its operand to its simplest form.
Emin=DEFAULT_MIN_EXPONENT
Emin=DEFAULT_MIN_EXPONENT, capitals=1
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] == '-': ...
if filename == '<string>' and mainpyfile: filename = mainpyfile
if filename == '<string>' and self.mainpyfile: filename = self.mainpyfile
def defaultFile(self): """Produce a reasonable default.""" filename = self.curframe.f_code.co_filename if filename == '<string>' and mainpyfile: filename = mainpyfile return filename
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
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) fullna...
mainmodule = '' mainpyfile = '' if __name__=='__main__':
def main():
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'
mainpyfile = filename = sys.argv[1] if not os.path.exists(filename): print 'Error:', repr(filename), 'does not exist'
mainpyfile = sys.argv[1] if not os.path.exists(mainpyfile): print 'Error:', mainpyfile, 'does not exist'
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'
mainmodule = os.path.basename(filename)
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'
sys.path.insert(0, os.path.dirname(filename)) run('execfile(%r)' % (filename,))
sys.path[0] = os.path.dirname(mainpyfile) pdb = Pdb() while 1: try: pdb._runscript(mainpyfile) if pdb._user_requested_quit: break print "The program finished and will be restarted" except SystemExit: print "The program exited via sys.exit(). Exit status: ", print sys.exc_info()[1] except: traceback.print_exc() p...
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'
try: self.ftp.nlst(file) except ftplib.error_perm, reason: raise IOError, ('ftp error', reason), sys.exc_info()[2] self.ftp.voidcmd(cmd)
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 tr...
def urlopen(url, data=None):
def urlopen(url, data=None, proxies=None):
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)
if not _urlopener: _urlopener = FancyURLopener()
if proxies is not None: opener = FancyURLopener(proxies=proxies) elif not _urlopener: opener = FancyURLopener() _urlopener = opener else: opener = _urlopener
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)
return _urlopener.open(url)
return opener.open(url)
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)
return _urlopener.open(url, data)
return opener.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)
classmethod test.test_descrtut.C 1
classmethod <class 'test.test_descrtut.C'> 1
... def foo(cls, y):
classmethod test.test_descrtut.D 1
classmethod <class 'test.test_descrtut.D'> 1
... def foo(cls, y):
classmethod test.test_descrtut.C 1
classmethod <class 'test.test_descrtut.C'> 1
... def foo(cls, y): # override C.foo
called A.save() >>> class A(object):
called C.save() >>> class A(object):
... def save(self):
index = ac_in_buffer.find (self.terminator)
index = self.ac_in_buffer.find(terminator)
def handle_read (self):
while 1: res = mime_code.search(line)
pos = 0 while 1: res = mime_code.search(line, pos)
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
newline = newline + line[:res.start(0)] + \
newline = newline + line[pos:res.start(0)] + \
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
line = line[res.end(0):] return newline + line
pos = res.end(0) return newline + line[pos:]
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
while 1: res = mime_head.search(line)
pos = 0 while 1: res = mime_head.search(line, pos)
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_decod...
newline = newline + line[:res.start(0)] + mime_decode(match) line = line[res.end(0):] return newline + line
newline = newline + line[pos:res.start(0)] + mime_decode(match) pos = res.end(0) return newline + line[pos:]
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_decod...
line = line[1:] while 1: res = reg.search(line)
pos = 1 while 1: res = reg.search(line, pos)
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('=%...