bugged
stringlengths 4
228k
| fixed
stringlengths 0
96.3M
| __index_level_0__
int64 0
481k
|
|---|---|---|
def _openDBEnv(cachesize): e = db.DBEnv() if cachesize is not None: if cachesize >= 20480: e.set_cachesize(0, cachesize) else: raise error, "cachesize must be >= 20480" e.open('.', db.DB_PRIVATE | db.DB_CREATE | db.DB_THREAD | db.DB_INIT_LOCK | db.DB_INIT_MPOOL) e.set_lk_detect(db.DB_LOCK_DEFAULT) return e
|
def _openDBEnv(cachesize): e = db.DBEnv() if cachesize is not None: if cachesize >= 20480: e.set_cachesize(0, cachesize) else: raise error, "cachesize must be >= 20480" e.open('.', db.DB_PRIVATE | db.DB_CREATE | db.DB_THREAD | db.DB_INIT_LOCK | db.DB_INIT_MPOOL) return e
| 13,300
|
def test_main(verbose=None): import sys from test import test_sets test_classes = ( TestSet, TestSetSubclass, TestFrozenSet, TestFrozenSetSubclass, TestSetOfSets, TestExceptionPropagation, TestBasicOpsEmpty, TestBasicOpsSingleton, TestBasicOpsTuple, TestBasicOpsTriple, TestBinaryOps, TestUpdateOps, TestMutate, TestSubsetEqualEmpty, TestSubsetEqualNonEmpty, TestSubsetEmptyNonEmpty, TestSubsetPartial, TestSubsetNonOverlap, TestOnlySetsNumeric, TestOnlySetsDict, TestOnlySetsOperator, TestOnlySetsTuple, TestOnlySetsString, TestOnlySetsGenerator, TestCopyingEmpty, TestCopyingSingleton, TestCopyingTriple, TestCopyingTuple, TestCopyingNested, TestIdentities, TestVariousIteratorArgs, ) test_support.run_unittest(*test_classes) # verify reference counting if verbose and hasattr(sys, "gettotalrefcount"): import gc counts = [None] * 5 for i in xrange(len(counts)): test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() print counts
|
def test_main(verbose=None): from test import test_sets test_classes = ( TestSet, TestSetSubclass, TestFrozenSet, TestFrozenSetSubclass, TestSetOfSets, TestExceptionPropagation, TestBasicOpsEmpty, TestBasicOpsSingleton, TestBasicOpsTuple, TestBasicOpsTriple, TestBinaryOps, TestUpdateOps, TestMutate, TestSubsetEqualEmpty, TestSubsetEqualNonEmpty, TestSubsetEmptyNonEmpty, TestSubsetPartial, TestSubsetNonOverlap, TestOnlySetsNumeric, TestOnlySetsDict, TestOnlySetsOperator, TestOnlySetsTuple, TestOnlySetsString, TestOnlySetsGenerator, TestCopyingEmpty, TestCopyingSingleton, TestCopyingTriple, TestCopyingTuple, TestCopyingNested, TestIdentities, TestVariousIteratorArgs, ) test_support.run_unittest(*test_classes) # verify reference counting if verbose and hasattr(sys, "gettotalrefcount"): import gc counts = [None] * 5 for i in xrange(len(counts)): test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() print counts
| 13,301
|
def get_file_list (self): """Figure out the list of files to include in the source distribution, and put it in 'self.files'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all depends on the user's options and the state of the filesystem. """ template_exists = os.path.isfile (self.template) if template_exists: template_newer = newer (self.template, self.manifest)
|
def get_file_list (self): """Figure out the list of files to include in the source distribution, and put it in 'self.files'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all depends on the user's options and the state of the filesystem. """ template_exists = os.path.isfile (self.template) if template_exists: template_newer = newer (self.template, self.manifest)
| 13,302
|
def view_readme(self, event=None): print>>sys.__stderr__, "** __file__: ", __file__ fn=os.path.join(os.path.abspath(os.path.dirname(__file__)),'README.txt') textView.TextViewer(self.top,'IDLEfork - README',fn)
|
def view_readme(self, event=None): fn=os.path.join(os.path.abspath(os.path.dirname(__file__)),'README.txt') textView.TextViewer(self.top,'IDLEfork - README',fn)
| 13,303
|
def append(self, cmd, kind): """t.append(cmd, kind) adds a new step at the end.""" if type(cmd) is not type(''): raise TypeError, \ 'Template.append: cmd must be a string' if kind not in stepkinds: raise ValueError, \ 'Template.append: bad kind ' + `kind` if kind == SOURCE: raise ValueError, \ 'Template.append: SOURCE can only be prepended' if self.steps and self.steps[-1][1] == SINK: raise ValueError, \ 'Template.append: already ends with SINK' if kind[0] == 'f' and not re.search('\$IN\b', cmd): raise ValueError, \ 'Template.append: missing $IN in cmd' if kind[1] == 'f' and not re.search('\$OUT\b', cmd): raise ValueError, \ 'Template.append: missing $OUT in cmd' self.steps.append((cmd, kind))
|
def append(self, cmd, kind): """t.append(cmd, kind) adds a new step at the end.""" if type(cmd) is not type(''): raise TypeError, \ 'Template.append: cmd must be a string' if kind not in stepkinds: raise ValueError, \ 'Template.append: bad kind ' + `kind` if kind == SOURCE: raise ValueError, \ 'Template.append: SOURCE can only be prepended' if self.steps and self.steps[-1][1] == SINK: raise ValueError, \ 'Template.append: already ends with SINK' if kind[0] == 'f' and not re.search(r'\$IN\b', cmd): raise ValueError, \ 'Template.append: missing $IN in cmd' if kind[1] == 'f' and not re.search('\$OUT\b', cmd): raise ValueError, \ 'Template.append: missing $OUT in cmd' self.steps.append((cmd, kind))
| 13,304
|
def append(self, cmd, kind): """t.append(cmd, kind) adds a new step at the end.""" if type(cmd) is not type(''): raise TypeError, \ 'Template.append: cmd must be a string' if kind not in stepkinds: raise ValueError, \ 'Template.append: bad kind ' + `kind` if kind == SOURCE: raise ValueError, \ 'Template.append: SOURCE can only be prepended' if self.steps and self.steps[-1][1] == SINK: raise ValueError, \ 'Template.append: already ends with SINK' if kind[0] == 'f' and not re.search('\$IN\b', cmd): raise ValueError, \ 'Template.append: missing $IN in cmd' if kind[1] == 'f' and not re.search('\$OUT\b', cmd): raise ValueError, \ 'Template.append: missing $OUT in cmd' self.steps.append((cmd, kind))
|
def append(self, cmd, kind): """t.append(cmd, kind) adds a new step at the end.""" if type(cmd) is not type(''): raise TypeError, \ 'Template.append: cmd must be a string' if kind not in stepkinds: raise ValueError, \ 'Template.append: bad kind ' + `kind` if kind == SOURCE: raise ValueError, \ 'Template.append: SOURCE can only be prepended' if self.steps and self.steps[-1][1] == SINK: raise ValueError, \ 'Template.append: already ends with SINK' if kind[0] == 'f' and not re.search('\$IN\b', cmd): raise ValueError, \ 'Template.append: missing $IN in cmd' if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd): raise ValueError, \ 'Template.append: missing $OUT in cmd' self.steps.append((cmd, kind))
| 13,305
|
def prepend(self, cmd, kind): """t.prepend(cmd, kind) adds a new step at the front.""" if type(cmd) is not type(''): raise TypeError, \ 'Template.prepend: cmd must be a string' if kind not in stepkinds: raise ValueError, \ 'Template.prepend: bad kind ' + `kind` if kind == SINK: raise ValueError, \ 'Template.prepend: SINK can only be appended' if self.steps and self.steps[0][1] == SOURCE: raise ValueError, \ 'Template.prepend: already begins with SOURCE' if kind[0] == 'f' and not re.search('\$IN\b', cmd): raise ValueError, \ 'Template.prepend: missing $IN in cmd' if kind[1] == 'f' and not re.search('\$OUT\b', cmd): raise ValueError, \ 'Template.prepend: missing $OUT in cmd' self.steps.insert(0, (cmd, kind))
|
def prepend(self, cmd, kind): """t.prepend(cmd, kind) adds a new step at the front.""" if type(cmd) is not type(''): raise TypeError, \ 'Template.prepend: cmd must be a string' if kind not in stepkinds: raise ValueError, \ 'Template.prepend: bad kind ' + `kind` if kind == SINK: raise ValueError, \ 'Template.prepend: SINK can only be appended' if self.steps and self.steps[0][1] == SOURCE: raise ValueError, \ 'Template.prepend: already begins with SOURCE' if kind[0] == 'f' and not re.search(r'\$IN\b', cmd): raise ValueError, \ 'Template.prepend: missing $IN in cmd' if kind[1] == 'f' and not re.search('\$OUT\b', cmd): raise ValueError, \ 'Template.prepend: missing $OUT in cmd' self.steps.insert(0, (cmd, kind))
| 13,306
|
def prepend(self, cmd, kind): """t.prepend(cmd, kind) adds a new step at the front.""" if type(cmd) is not type(''): raise TypeError, \ 'Template.prepend: cmd must be a string' if kind not in stepkinds: raise ValueError, \ 'Template.prepend: bad kind ' + `kind` if kind == SINK: raise ValueError, \ 'Template.prepend: SINK can only be appended' if self.steps and self.steps[0][1] == SOURCE: raise ValueError, \ 'Template.prepend: already begins with SOURCE' if kind[0] == 'f' and not re.search('\$IN\b', cmd): raise ValueError, \ 'Template.prepend: missing $IN in cmd' if kind[1] == 'f' and not re.search('\$OUT\b', cmd): raise ValueError, \ 'Template.prepend: missing $OUT in cmd' self.steps.insert(0, (cmd, kind))
|
def prepend(self, cmd, kind): """t.prepend(cmd, kind) adds a new step at the front.""" if type(cmd) is not type(''): raise TypeError, \ 'Template.prepend: cmd must be a string' if kind not in stepkinds: raise ValueError, \ 'Template.prepend: bad kind ' + `kind` if kind == SINK: raise ValueError, \ 'Template.prepend: SINK can only be appended' if self.steps and self.steps[0][1] == SOURCE: raise ValueError, \ 'Template.prepend: already begins with SOURCE' if kind[0] == 'f' and not re.search('\$IN\b', cmd): raise ValueError, \ 'Template.prepend: missing $IN in cmd' if kind[1] == 'f' and not re.search(r'\$OUT\b', cmd): raise ValueError, \ 'Template.prepend: missing $OUT in cmd' self.steps.insert(0, (cmd, kind))
| 13,307
|
def parse_request(self): """Parse a request (internal).
|
def parse_request(self): """Parse a request (internal).
| 13,308
|
def parse_request(self): """Parse a request (internal).
|
def parse_request(self): """Parse a request (internal).
| 13,309
|
def parse_request(self): """Parse a request (internal).
|
def parse_request(self): """Parse a request (internal).
| 13,310
|
def parse_request(self): """Parse a request (internal).
|
def parse_request(self): """Parse a request (internal).
| 13,311
|
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: match = self.interesting.search(rawdata, i) # < or & if match: j = match.start() else: j = n if i < j: self.handle_data(rawdata[i:j]) i = self.updatepos(i, j) if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): # < + letter k = self.parse_starttag(i) elif endtagopen.match(rawdata, i): # </ k = self.parse_endtag(i) if k >= 0: self.clear_cdata_mode() elif commentopen.match(rawdata, i): # <!-- k = self.parse_comment(i) elif piopen.match(rawdata, i): # <? k = self.parse_pi(i) elif declopen.match(rawdata, i): # <! k = self.parse_declaration(i) else: self.handle_data("<") k = i + 1 if k < 0: if end: raise HTMLParseError("EOF in middle of construct", self.getpos()) break i = self.updatepos(i, k) elif rawdata[i] == '&': match = charref.match(rawdata, i) if match: name = match.group()[2:-1] self.handle_charref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = entityref.match(rawdata, i) if match: name = match.group(1) self.handle_entityref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = incomplete.match(rawdata, i) if match: rest = rawdata[i:] if end and rest != "&" and match.group() == rest: raise HTMLParseError( "EOF in middle of entity or char ref", self.getpos()) return -1 # incomplete self.handle_data("&") i = self.updatepos(i, i + 1) else: assert 0, "interesting.search() lied" # end while if end and i < n: self.handle_data(rawdata[i:n]) i = self.updatepos(i, n) self.rawdata = rawdata[i:]
|
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: match = self.interesting.search(rawdata, i) # < or & if match: j = match.start() elif (i + 1) < n: j = n if i < j: self.handle_data(rawdata[i:j]) i = self.updatepos(i, j) if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): # < + letter k = self.parse_starttag(i) elif endtagopen.match(rawdata, i): # </ k = self.parse_endtag(i) if k >= 0: self.clear_cdata_mode() elif commentopen.match(rawdata, i): # <!-- k = self.parse_comment(i) elif piopen.match(rawdata, i): # <? k = self.parse_pi(i) elif declopen.match(rawdata, i): # <! k = self.parse_declaration(i) elif (i + 1) < n: self.handle_data("<") k = i + 1 if k < 0: if end: raise HTMLParseError("EOF in middle of construct", self.getpos()) break i = self.updatepos(i, k) elif rawdata[i] == '&': match = charref.match(rawdata, i) if match: name = match.group()[2:-1] self.handle_charref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = entityref.match(rawdata, i) if match: name = match.group(1) self.handle_entityref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = incomplete.match(rawdata, i) if match: rest = rawdata[i:] if end and rest != "&" and match.group() == rest: raise HTMLParseError( "EOF in middle of entity or char ref", self.getpos()) return -1 # incomplete self.handle_data("&") i = self.updatepos(i, i + 1) elif (i + 1) < n: assert 0, "interesting.search() lied" # end while if end and i < n: self.handle_data(rawdata[i:n]) i = self.updatepos(i, n) self.rawdata = rawdata[i:]
| 13,312
|
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: match = self.interesting.search(rawdata, i) # < or & if match: j = match.start() else: j = n if i < j: self.handle_data(rawdata[i:j]) i = self.updatepos(i, j) if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): # < + letter k = self.parse_starttag(i) elif endtagopen.match(rawdata, i): # </ k = self.parse_endtag(i) if k >= 0: self.clear_cdata_mode() elif commentopen.match(rawdata, i): # <!-- k = self.parse_comment(i) elif piopen.match(rawdata, i): # <? k = self.parse_pi(i) elif declopen.match(rawdata, i): # <! k = self.parse_declaration(i) else: self.handle_data("<") k = i + 1 if k < 0: if end: raise HTMLParseError("EOF in middle of construct", self.getpos()) break i = self.updatepos(i, k) elif rawdata[i] == '&': match = charref.match(rawdata, i) if match: name = match.group()[2:-1] self.handle_charref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = entityref.match(rawdata, i) if match: name = match.group(1) self.handle_entityref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = incomplete.match(rawdata, i) if match: rest = rawdata[i:] if end and rest != "&" and match.group() == rest: raise HTMLParseError( "EOF in middle of entity or char ref", self.getpos()) return -1 # incomplete self.handle_data("&") i = self.updatepos(i, i + 1) else: assert 0, "interesting.search() lied" # end while if end and i < n: self.handle_data(rawdata[i:n]) i = self.updatepos(i, n) self.rawdata = rawdata[i:]
|
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: match = self.interesting.search(rawdata, i) # < or & if match: j = match.start() else: j = n if i < j: self.handle_data(rawdata[i:j]) i = self.updatepos(i, j) if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): # < + letter k = self.parse_starttag(i) elif endtagopen.match(rawdata, i): # </ k = self.parse_endtag(i) if k >= 0: self.clear_cdata_mode() elif commentopen.match(rawdata, i): # <!-- k = self.parse_comment(i) elif piopen.match(rawdata, i): # <? k = self.parse_pi(i) elif declopen.match(rawdata, i): # <! k = self.parse_declaration(i) else: self.handle_data("<") k = i + 1 if k < 0: if end: raise HTMLParseError("EOF in middle of construct", self.getpos()) break i = self.updatepos(i, k) elif rawdata[i:i+2] == "& match = charref.match(rawdata, i) if match: name = match.group()[2:-1] self.handle_charref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = entityref.match(rawdata, i) if match: name = match.group(1) self.handle_entityref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = incomplete.match(rawdata, i) if match: rest = rawdata[i:] if end and rest != "&" and match.group() == rest: raise HTMLParseError( "EOF in middle of entity or char ref", self.getpos()) return -1 # incomplete self.handle_data("&") i = self.updatepos(i, i + 1) else: assert 0, "interesting.search() lied" # end while if end and i < n: self.handle_data(rawdata[i:n]) i = self.updatepos(i, n) self.rawdata = rawdata[i:]
| 13,313
|
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: match = self.interesting.search(rawdata, i) # < or & if match: j = match.start() else: j = n if i < j: self.handle_data(rawdata[i:j]) i = self.updatepos(i, j) if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): # < + letter k = self.parse_starttag(i) elif endtagopen.match(rawdata, i): # </ k = self.parse_endtag(i) if k >= 0: self.clear_cdata_mode() elif commentopen.match(rawdata, i): # <!-- k = self.parse_comment(i) elif piopen.match(rawdata, i): # <? k = self.parse_pi(i) elif declopen.match(rawdata, i): # <! k = self.parse_declaration(i) else: self.handle_data("<") k = i + 1 if k < 0: if end: raise HTMLParseError("EOF in middle of construct", self.getpos()) break i = self.updatepos(i, k) elif rawdata[i] == '&': match = charref.match(rawdata, i) if match: name = match.group()[2:-1] self.handle_charref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = entityref.match(rawdata, i) if match: name = match.group(1) self.handle_entityref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = incomplete.match(rawdata, i) if match: rest = rawdata[i:] if end and rest != "&" and match.group() == rest: raise HTMLParseError( "EOF in middle of entity or char ref", self.getpos()) return -1 # incomplete self.handle_data("&") i = self.updatepos(i, i + 1) else: assert 0, "interesting.search() lied" # end while if end and i < n: self.handle_data(rawdata[i:n]) i = self.updatepos(i, n) self.rawdata = rawdata[i:]
|
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: match = self.interesting.search(rawdata, i) # < or & if match: j = match.start() else: j = n if i < j: self.handle_data(rawdata[i:j]) i = self.updatepos(i, j) if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): # < + letter k = self.parse_starttag(i) elif endtagopen.match(rawdata, i): # </ k = self.parse_endtag(i) if k >= 0: self.clear_cdata_mode() elif commentopen.match(rawdata, i): # <!-- k = self.parse_comment(i) elif piopen.match(rawdata, i): # <? k = self.parse_pi(i) elif declopen.match(rawdata, i): # <! k = self.parse_declaration(i) else: self.handle_data("<") k = i + 1 if k < 0: if end: raise HTMLParseError("EOF in middle of construct", self.getpos()) break i = self.updatepos(i, k) elif rawdata[i] == '&': match = charref.match(rawdata, i) if match: name = match.group()[2:-1] self.handle_charref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = entityref.match(rawdata, i) if match: name = match.group(1) self.handle_entityref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = incomplete.match(rawdata, i) if match: rest = rawdata[i:] if end and match.group() == rest: raise HTMLParseError( "EOF in middle of entity or char ref", self.getpos()) return -1 # incomplete self.handle_data("&") i = self.updatepos(i, i + 1) else: assert 0, "interesting.search() lied" # end while if end and i < n: self.handle_data(rawdata[i:n]) i = self.updatepos(i, n) self.rawdata = rawdata[i:]
| 13,314
|
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: match = self.interesting.search(rawdata, i) # < or & if match: j = match.start() else: j = n if i < j: self.handle_data(rawdata[i:j]) i = self.updatepos(i, j) if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): # < + letter k = self.parse_starttag(i) elif endtagopen.match(rawdata, i): # </ k = self.parse_endtag(i) if k >= 0: self.clear_cdata_mode() elif commentopen.match(rawdata, i): # <!-- k = self.parse_comment(i) elif piopen.match(rawdata, i): # <? k = self.parse_pi(i) elif declopen.match(rawdata, i): # <! k = self.parse_declaration(i) else: self.handle_data("<") k = i + 1 if k < 0: if end: raise HTMLParseError("EOF in middle of construct", self.getpos()) break i = self.updatepos(i, k) elif rawdata[i] == '&': match = charref.match(rawdata, i) if match: name = match.group()[2:-1] self.handle_charref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = entityref.match(rawdata, i) if match: name = match.group(1) self.handle_entityref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = incomplete.match(rawdata, i) if match: rest = rawdata[i:] if end and rest != "&" and match.group() == rest: raise HTMLParseError( "EOF in middle of entity or char ref", self.getpos()) return -1 # incomplete self.handle_data("&") i = self.updatepos(i, i + 1) else: assert 0, "interesting.search() lied" # end while if end and i < n: self.handle_data(rawdata[i:n]) i = self.updatepos(i, n) self.rawdata = rawdata[i:]
|
def goahead(self, end): rawdata = self.rawdata i = 0 n = len(rawdata) while i < n: match = self.interesting.search(rawdata, i) # < or & if match: j = match.start() else: j = n if i < j: self.handle_data(rawdata[i:j]) i = self.updatepos(i, j) if i == n: break if rawdata[i] == '<': if starttagopen.match(rawdata, i): # < + letter k = self.parse_starttag(i) elif endtagopen.match(rawdata, i): # </ k = self.parse_endtag(i) if k >= 0: self.clear_cdata_mode() elif commentopen.match(rawdata, i): # <!-- k = self.parse_comment(i) elif piopen.match(rawdata, i): # <? k = self.parse_pi(i) elif declopen.match(rawdata, i): # <! k = self.parse_declaration(i) else: self.handle_data("<") k = i + 1 if k < 0: if end: raise HTMLParseError("EOF in middle of construct", self.getpos()) break i = self.updatepos(i, k) elif rawdata[i] == '&': match = charref.match(rawdata, i) if match: name = match.group()[2:-1] self.handle_charref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = entityref.match(rawdata, i) if match: name = match.group(1) self.handle_entityref(name) k = match.end() if rawdata[k-1] != ';': k = k - 1 i = self.updatepos(i, k) continue match = incomplete.match(rawdata, i) if match: rest = rawdata[i:] if end and rest != "&" and match.group() == rest: raise HTMLParseError( "EOF in middle of entity or char ref", self.getpos()) return -1 # incomplete self.handle_data("&") i = self.updatepos(i, i + 1) else: assert 0, "interesting.search() lied" # end while if end and i < n: self.handle_data(rawdata[i:n]) i = self.updatepos(i, n) self.rawdata = rawdata[i:]
| 13,315
|
def parse_comment(self, i): rawdata = self.rawdata assert rawdata[i:i+4] == '<!--', 'unexpected call to parse_comment()' match = commentclose.search(rawdata, i+4) if not match: return -1 j = match.start() self.handle_comment(rawdata[i+4: j]) j = match.end() return j
|
def parse_comment(self, i, report=1): rawdata = self.rawdata assert rawdata[i:i+4] == '<!--', 'unexpected call to parse_comment()' match = commentclose.search(rawdata, i+4) if not match: return -1 j = match.start() self.handle_comment(rawdata[i+4: j]) j = match.end() return j
| 13,316
|
def parse_comment(self, i): rawdata = self.rawdata assert rawdata[i:i+4] == '<!--', 'unexpected call to parse_comment()' match = commentclose.search(rawdata, i+4) if not match: return -1 j = match.start() self.handle_comment(rawdata[i+4: j]) j = match.end() return j
|
def parse_comment(self, i): rawdata = self.rawdata assert rawdata[i:i+4] == '<!--', 'unexpected call to parse_comment()' match = commentclose.search(rawdata, i+4) if not match: return -1 if report: j = match.start() self.handle_comment(rawdata[i+4: j]) j = match.end() return j
| 13,317
|
def parse_declaration(self, i): # This is some sort of declaration; in "HTML as # deployed," this should only be the document type # declaration ("<!DOCTYPE html...>"). rawdata = self.rawdata j = i + 2 assert rawdata[i:j] == "<!", "unexpected call to parse_declaration" if rawdata[j:j+1] in ("-", ""): # Start of comment followed by buffer boundary, # or just a buffer boundary. return -1 # in practice, this should look like: ((name|stringlit) S*)+ '>' n = len(rawdata) while j < n: c = rawdata[j] if c == ">": # end of declaration syntax self.handle_decl(rawdata[i+2:j]) return j + 1 if c in "\"'": m = declstringlit.match(rawdata, j) if not m: return -1 # incomplete j = m.end() elif c in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ": m = declname.match(rawdata, j) if not m: return -1 # incomplete j = m.end() else: raise HTMLParseError( "unexpected char in declaration: %s" % `rawdata[j]`, self.getpos()) return -1 # incomplete
|
def parse_declaration(self, i): # This is some sort of declaration; in "HTML as # deployed," this should only be the document type # declaration ("<!DOCTYPE html...>"). rawdata = self.rawdata j = i + 2 assert rawdata[i:j] == "<!", "unexpected call to parse_declaration" if rawdata[j:j+1] in ("-", ""): # Start of comment followed by buffer boundary, # or just a buffer boundary. return -1 # in practice, this should look like: ((name|stringlit) S*)+ '>' n = len(rawdata) while j < n: c = rawdata[j] if c == ">": # end of declaration syntax data = rawdata[i+2:j] if decltype == "doctype": self.handle_decl(data) else: self.unknown_decl(data) return j + 1 if c in "\"'": m = declstringlit.match(rawdata, j) if not m: return -1 # incomplete j = m.end() elif c in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ": m = declname.match(rawdata, j) if not m: return -1 # incomplete j = m.end() else: raise HTMLParseError( "unexpected char in declaration: %s" % `rawdata[j]`, self.getpos()) return -1 # incomplete
| 13,318
|
def do_suspendresume(self, event): (what, message, when, where, modifiers) = event wid = FrontWindow() if wid and self._windows.has_key(wid): window = self._windows[wid] window.do_activate(modifiers & 1, event)
|
def do_suspendresume(self, event): (what, message, when, where, modifiers) = event wid = FrontWindow() if wid and self._windows.has_key(wid): window = self._windows[wid] window.do_activate(message & 1, event)
| 13,319
|
def set_ok_domain(self, cookie, request): if self.is_blocked(cookie.domain): debug(" domain %s is in user block-list", cookie.domain) return False if self.is_not_allowed(cookie.domain): debug(" domain %s is not in user allow-list", cookie.domain) return False if cookie.domain_specified: req_host, erhn = eff_request_host(request) domain = cookie.domain if self.strict_domain and (domain.count(".") >= 2): i = domain.rfind(".") j = domain.rfind(".", 0, i) if j == 0: # domain like .foo.bar tld = domain[i+1:] sld = domain[j+1:i] if (sld.lower() in ( "co", "ac", "com", "edu", "org", "net", "gov", "mil", "int") and len(tld) == 2): # domain like .co.uk debug(" country-code second level domain %s", domain) return False if domain.startswith("."): undotted_domain = domain[1:] else: undotted_domain = domain embedded_dots = (undotted_domain.find(".") >= 0) if not embedded_dots and domain != ".local": debug(" non-local domain %s contains no embedded dot", domain) return False if cookie.version == 0: if (not erhn.endswith(domain) and (not erhn.startswith(".") and not ("."+erhn).endswith(domain))): debug(" effective request-host %s (even with added " "initial dot) does not end end with %s", erhn, domain) return False if (cookie.version > 0 or (self.strict_ns_domain & self.DomainRFC2965Match)): if not domain_match(erhn, domain): debug(" effective request-host %s does not domain-match " "%s", erhn, domain) return False if (cookie.version > 0 or (self.strict_ns_domain & self.DomainStrictNoDots)): host_prefix = req_host[:-len(domain)] if (host_prefix.find(".") >= 0 and not IPV4_RE.search(req_host)): debug(" host prefix %s for domain %s contains a dot", host_prefix, domain) return False return True
|
def set_ok_domain(self, cookie, request): if self.is_blocked(cookie.domain): debug(" domain %s is in user block-list", cookie.domain) return False if self.is_not_allowed(cookie.domain): debug(" domain %s is not in user allow-list", cookie.domain) return False if cookie.domain_specified: req_host, erhn = eff_request_host(request) domain = cookie.domain if self.strict_domain and (domain.count(".") >= 2): i = domain.rfind(".") j = domain.rfind(".", 0, i) if j == 0: # domain like .foo.bar tld = domain[i+1:] sld = domain[j+1:i] if sld.lower() in ("co", "ac", "com", "edu", "org", "net", "gov", "mil", "int", "aero", "biz", "cat", "coop", "info", "jobs", "mobi", "museum", "name", "pro", "travel", "eu") and len(tld) == 2: # domain like .co.uk debug(" country-code second level domain %s", domain) return False if domain.startswith("."): undotted_domain = domain[1:] else: undotted_domain = domain embedded_dots = (undotted_domain.find(".") >= 0) if not embedded_dots and domain != ".local": debug(" non-local domain %s contains no embedded dot", domain) return False if cookie.version == 0: if (not erhn.endswith(domain) and (not erhn.startswith(".") and not ("."+erhn).endswith(domain))): debug(" effective request-host %s (even with added " "initial dot) does not end end with %s", erhn, domain) return False if (cookie.version > 0 or (self.strict_ns_domain & self.DomainRFC2965Match)): if not domain_match(erhn, domain): debug(" effective request-host %s does not domain-match " "%s", erhn, domain) return False if (cookie.version > 0 or (self.strict_ns_domain & self.DomainStrictNoDots)): host_prefix = req_host[:-len(domain)] if (host_prefix.find(".") >= 0 and not IPV4_RE.search(req_host)): debug(" host prefix %s for domain %s contains a dot", host_prefix, domain) return False return True
| 13,320
|
def open_http(self, url): import httplib if type(url) is type(""): host, selector = splithost(url) user_passwd, host = splituser(host) else: host, selector = url urltype, rest = splittype(selector) if string.lower(urltype) == 'http': realhost, rest = splithost(rest) user_passwd, realhost = splituser(realhost) if user_passwd: selector = "%s://%s%s" % (urltype, realhost, rest) print "proxy via http:", host, selector if not host: raise IOError, ('http error', 'no host given') if user_passwd: import base64 auth = string.strip(base64.encodestring(user_passwd)) else: auth = None h = httplib.HTTP(host) h.putrequest('GET', selector) if auth: h.putheader('Authorization: Basic %s' % auth) for args in self.addheaders: apply(h.putheader, args) h.endheaders() errcode, errmsg, headers = h.getreply() fp = h.getfile() if errcode == 200: return addinfo(fp, headers) else: return self.http_error(url, fp, errcode, errmsg, headers)
|
def open_http(self, url): import httplib if type(url) is type(""): host, selector = splithost(url) user_passwd, host = splituser(host) else: host, selector = url urltype, rest = splittype(selector) if string.lower(urltype) == 'http': realhost, rest = splithost(rest) user_passwd, realhost = splituser(realhost) if user_passwd: selector = "%s://%s%s" % (urltype, realhost, rest) print "proxy via http:", host, selector if not host: raise IOError, ('http error', 'no host given') if user_passwd: import base64 auth = string.strip(base64.encodestring(user_passwd)) else: auth = None h = httplib.HTTP(host) h.putrequest('GET', selector) if auth: h.putheader('Authorization: Basic %s' % auth) for args in self.addheaders: apply(h.putheader, args) h.endheaders() errcode, errmsg, headers = h.getreply() fp = h.getfile() if errcode == 200: return addinfourl(fp, headers, self.openedurl) else: return self.http_error(url, fp, errcode, errmsg, headers)
| 13,321
|
def open_gopher(self, url): import gopherlib host, selector = splithost(url) if not host: raise IOError, ('gopher error', 'no host given') type, selector = splitgophertype(selector) selector, query = splitquery(selector) selector = unquote(selector) if query: query = unquote(query) fp = gopherlib.send_query(selector, query, host) else: fp = gopherlib.send_selector(selector, host) return addinfo(fp, noheaders())
|
def open_gopher(self, url): import gopherlib host, selector = splithost(url) if not host: raise IOError, ('gopher error', 'no host given') type, selector = splitgophertype(selector) selector, query = splitquery(selector) selector = unquote(selector) if query: query = unquote(query) fp = gopherlib.send_query(selector, query, host) else: fp = gopherlib.send_selector(selector, host) return addinfo(fp, noheaders())
| 13,322
|
def open_local_file(self, url): host, file = splithost(url) if not host: return addinfo(open(url2pathname(file), 'r'), noheaders()) host, port = splitport(host) if not port and socket.gethostbyname(host) in ( localhost(), thishost()): file = unquote(file) return addinfo(open(url2pathname(file), 'r'), noheaders()) raise IOError, ('local file error', 'not on local host')
|
def open_local_file(self, url): host, file = splithost(url) if not host: return addinfourl(open(url2pathname(file), 'r'), noheaders(), self.openedurl) host, port = splitport(host) if not port and socket.gethostbyname(host) in ( localhost(), thishost()): file = unquote(file) return addinfo(open(url2pathname(file), 'r'), noheaders()) raise IOError, ('local file error', 'not on local host')
| 13,323
|
def open_local_file(self, url): host, file = splithost(url) if not host: return addinfo(open(url2pathname(file), 'r'), noheaders()) host, port = splitport(host) if not port and socket.gethostbyname(host) in ( localhost(), thishost()): file = unquote(file) return addinfo(open(url2pathname(file), 'r'), noheaders()) raise IOError, ('local file error', 'not on local host')
|
def open_local_file(self, url): host, file = splithost(url) if not host: return addinfourl(open(url2pathname(file), 'r'), noheaders(), self.openedurl) host, port = splitport(host) if not port and socket.gethostbyname(host) in ( localhost(), thishost()): file = unquote(file) return addinfourl(open(url2pathname(file), 'r'), noheaders(), self.openedurl) raise IOError, ('local file error', 'not on local host')
| 13,324
|
def open_ftp(self, url): host, path = splithost(url) if not host: raise IOError, ('ftp error', 'no host given') host, port = splitport(host) user, host = splituser(host) if user: user, passwd = splitpasswd(user) else: passwd = None host = socket.gethostbyname(host) if not port: import ftplib port = ftplib.FTP_PORT path, attrs = splitattr(path) dirs = string.splitfields(path, '/') dirs, file = dirs[:-1], dirs[-1] if dirs and not dirs[0]: dirs = dirs[1:] key = (user, host, port, string.joinfields(dirs, '/')) try: if not self.ftpcache.has_key(key): self.ftpcache[key] = \ ftpwrapper(user, passwd, host, port, dirs) if not file: type = 'D' else: type = 'I' for attr in attrs: attr, value = splitvalue(attr) if string.lower(attr) == 'type' and \ value in ('a', 'A', 'i', 'I', 'd', 'D'): type = string.upper(value) return addinfo(self.ftpcache[key].retrfile(file, type), noheaders()) except ftperrors(), msg: raise IOError, ('ftp error', msg)
|
def open_ftp(self, url): host, path = splithost(url) if not host: raise IOError, ('ftp error', 'no host given') host, port = splitport(host) user, host = splituser(host) if user: user, passwd = splitpasswd(user) else: passwd = None host = socket.gethostbyname(host) if not port: import ftplib port = ftplib.FTP_PORT path, attrs = splitattr(path) dirs = string.splitfields(path, '/') dirs, file = dirs[:-1], dirs[-1] if dirs and not dirs[0]: dirs = dirs[1:] key = (user, host, port, string.joinfields(dirs, '/')) try: if not self.ftpcache.has_key(key): self.ftpcache[key] = \ ftpwrapper(user, passwd, host, port, dirs) if not file: type = 'D' else: type = 'I' for attr in attrs: attr, value = splitvalue(attr) if string.lower(attr) == 'type' and \ value in ('a', 'A', 'i', 'I', 'd', 'D'): type = string.upper(value) return addinfourl(self.ftpcache[key].retrfile(file, type), noheaders(), self.openedurl) except ftperrors(), msg: raise IOError, ('ftp error', msg)
| 13,325
|
def http_error_default(self, url, fp, errcode, errmsg, headers): return addinfo(fp, headers)
|
def http_error_default(self, url, fp, errcode, errmsg, headers): return addinfo(fp, headers)
| 13,326
|
def test(method, input, output, *args): if verbose: print '%s.%s%s =? %s... ' % (repr(input), method, args, output), try: f = getattr(input, method) value = apply(f, args) except: value = sys.exc_type exc = sys.exc_info()[:2] else: exc = None if value != output: if verbose: print 'no' print '*',f, `input`, `output`, `value` if exc: print ' value == %s: %s' % (exc) else: if verbose: print 'yes'
|
def test(method, input, output, *args): if verbose: print '%s.%s%s =? %s... ' % (repr(input), method, args, repr(output)), try: f = getattr(input, method) value = apply(f, args) except: value = sys.exc_type exc = sys.exc_info()[:2] else: exc = None if value != output: if verbose: print 'no' print '*',f, `input`, `output`, `value` if exc: print ' value == %s: %s' % (exc) else: if verbose: print 'yes'
| 13,327
|
def test(method, input, output, *args): if verbose: print '%s.%s%s =? %s... ' % (repr(input), method, args, output), try: f = getattr(input, method) value = apply(f, args) except: value = sys.exc_type exc = sys.exc_info()[:2] else: exc = None if value != output: if verbose: print 'no' print '*',f, `input`, `output`, `value` if exc: print ' value == %s: %s' % (exc) else: if verbose: print 'yes'
|
def test(method, input, output, *args): if verbose: print '%s.%s%s =? %s... ' % (repr(input), method, args, output), try: f = getattr(input, method) value = apply(f, args) except: value = sys.exc_type exc = sys.exc_info()[:2] else: exc = None if value != output or type(value) is not type(output): if verbose: print 'no' print '*',f, `input`, `output`, `value` if exc: print ' value == %s: %s' % (exc) else: if verbose: print 'yes'
| 13,328
|
def __init__(self): self.seq = 'wxyz'
|
def __init__(self): self.seq = 'wxyz'
| 13,329
|
def __getitem__(self, i): return self.seq[i]
|
def __getitem__(self, i): return self.seq[i]
| 13,330
|
def __getitem__(self, i): return self.seq[i]
|
def __getitem__(self, i): return self.seq[i]
| 13,331
|
def testSendAll(self): # Testing sendall() with a 2048 byte string over TCP while 1: read = self.cli_conn.recv(1024) if not read: break self.assert_(len(read) == 1024, "Error performing sendall.") read = filter(lambda x: x == 'f', read) self.assert_(len(read) == 1024, "Error performing sendall.")
|
def testSendAll(self): # Testing sendall() with a 2048 byte string over TCP while 1: read = self.cli_conn.recv(1024) if not read: break self.assert_(len(read) == 1024, "Error performing sendall.") read = filter(lambda x: x == 'f', read) self.assert_(len(read) == 1024, "Error performing sendall.")
| 13,332
|
def _filename_to_abs(self, filename): # Some filenames seem to be unix-like. Convert to Mac names.
|
def _filename_to_abs(self, filename): # Some filenames seem to be unix-like. Convert to Mac names.
| 13,333
|
def writexml(self, writer): writer.write("<" + self.tagName)
|
def writexml(self, writer): writer.write("<" + self.tagName)
| 13,334
|
def writexml(self, writer): writer.write("<" + self.tagName)
|
def writexml(self, writer): writer.write("<" + self.tagName)
| 13,335
|
def writexml(self, writer): writer.write("<" + self.tagName)
|
def writexml(self, writer): writer.write("<" + self.tagName)
| 13,336
|
def writexml(self, writer): writer.write("<!--%s-->" % self.data)
|
def writexml(self, writer): writer.write("<!--%s-->" % self.data)
| 13,337
|
def writexml(self, writer): writer.write("<?%s %s?>" % (self.target, self.data))
|
def writexml(self, writer): writer.write("<?%s %s?>" % (self.target, self.data))
| 13,338
|
def writexml(self, writer): _write_data(writer, self.data)
|
def writexml(self, writer): _write_data(writer, self.data)
| 13,339
|
def writexml(self, writer): writer.write('<?xml version="1.0" ?>\n') for node in self.childNodes: node.writexml(writer)
|
def writexml(self, writer, indent="", addindent="", newl=""): writer.write('<?xml version="1.0" ?>\n') for node in self.childNodes: node.writexml(writer)
| 13,340
|
def writexml(self, writer): writer.write('<?xml version="1.0" ?>\n') for node in self.childNodes: node.writexml(writer)
|
def writexml(self, writer): writer.write('<?xml version="1.0" ?>\n') for node in self.childNodes: node.writexml(writer)
| 13,341
|
def open_local_file(self, url): """Use local file.""" import mimetypes, mimetools, rfc822, StringIO host, file = splithost(url) localname = url2pathname(file) stats = os.stat(localname) size = stats.st_size modified = rfc822.formatdate(stats.st_mtime) mtype = mimetypes.guess_type(url)[0] headers = mimetools.Message(StringIO.StringIO( 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified))) if not host: urlfile = file if file[:1] == '/': urlfile = 'file://' + file return addinfourl(open(localname, 'rb'), headers, urlfile) host, port = splitport(host) if not port \ and socket.gethostbyname(host) in (localhost(), thishost()): urlfile = file if file[:1] == '/': urlfile = 'file://' + file return addinfourl(open(localname, 'rb'), headers, urlfile) raise IOError, ('local file error', 'not on local host')
|
def open_local_file(self, url): """Use local file.""" import mimetypes, mimetools, rfc822, StringIO host, file = splithost(url) localname = url2pathname(file) try: stats = os.stat(localname) except OSError, e: raise IOError(e.errno, e.strerror, e.filename) size = stats.st_size modified = rfc822.formatdate(stats.st_mtime) mtype = mimetypes.guess_type(url)[0] headers = mimetools.Message(StringIO.StringIO( 'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' % (mtype or 'text/plain', size, modified))) if not host: urlfile = file if file[:1] == '/': urlfile = 'file://' + file return addinfourl(open(localname, 'rb'), headers, urlfile) host, port = splitport(host) if not port \ and socket.gethostbyname(host) in (localhost(), thishost()): urlfile = file if file[:1] == '/': urlfile = 'file://' + file return addinfourl(open(localname, 'rb'), headers, urlfile) raise IOError, ('local file error', 'not on local host')
| 13,342
|
def testit(name, value, expected): if abs(value-expected) > eps: raise TestFailed, '%s returned %f, expected %f'%\ (name, value, expected)
|
def testit(name, value, expected): if abs(value-expected) > eps: raise TestFailed, '%s returned %f, expected %f'%\ (name, value, expected)
| 13,343
|
def reset(self): IncrementalDecoder.reset(self) self.bytebuffer = ""
|
def reset(self): IncrementalDecoder.reset(self) self.bytebuffer = ""
| 13,344
|
def test_main(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(GeneralModuleTests)) suite.addTest(unittest.makeSuite(BasicTCPTest)) suite.addTest(unittest.makeSuite(BasicUDPTest)) suite.addTest(unittest.makeSuite(NonBlockingTCPTests)) suite.addTest(unittest.makeSuite(FileObjectClassTestCase)) suite.addTest(unittest.makeSuite(UnbufferedFileObjectClassTestCase)) suite.addTest(unittest.makeSuite(LineBufferedFileObjectClassTestCase)) suite.addTest(unittest.makeSuite(SmallBufferedFileObjectClassTestCase)) test_support.run_suite(suite)
|
def test_main(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(GeneralModuleTests)) suite.addTest(unittest.makeSuite(BasicTCPTest)) if sys.platform != 'mac': suite.addTest(unittest.makeSuite(BasicUDPTest)) suite.addTest(unittest.makeSuite(NonBlockingTCPTests)) suite.addTest(unittest.makeSuite(FileObjectClassTestCase)) suite.addTest(unittest.makeSuite(UnbufferedFileObjectClassTestCase)) suite.addTest(unittest.makeSuite(LineBufferedFileObjectClassTestCase)) suite.addTest(unittest.makeSuite(SmallBufferedFileObjectClassTestCase)) test_support.run_suite(suite)
| 13,345
|
def document(self, object, name=None, *args): """Generate documentation for an object.""" args = (object, name) + args if inspect.ismodule(object): return self.docmodule(*args) if inspect.isclass(object): return self.docclass(*args) if inspect.isroutine(object): returnself.docroutine(*args) return self.docother(*args)
|
def document(self, object, name=None, *args): """Generate documentation for an object.""" args = (object, name) + args if inspect.ismodule(object): return self.docmodule(*args) if inspect.isclass(object): return self.docclass(*args) if inspect.isroutine(object): return self.docroutine(*args) return self.docother(*args)
| 13,346
|
def getheader(self, name, default=None): """Get the header value for a name. This is the normal interface: it return a stripped version of the header value for a given header name, or None if it doesn't exist. This uses the dictionary version which finds the *last* such header. """ try: return self.dict[string.lower(name)] except KeyError: return default
|
def getheader(self, name, default=None): """Get the header value for a name. This is the normal interface: it returns a stripped version of the header value for a given header name, or None if it doesn't exist. This uses the dictionary version which finds the *last* such header. """ try: return self.dict[string.lower(name)] except KeyError: return default
| 13,347
|
def f(): for i in range(1000): yield i
|
def f(): for i in range(1000): yield i
| 13,348
|
def __getitem__(self, key): return str(key) + '!!!'
|
def __getitem__(self, key): return str(key) + '!!!'
| 13,349
|
def selfmodifyingComparison(x,y): z.append(1) return cmp(x, y)
|
def selfmodifyingComparison(x,y): z.append(1) return cmp(x, y)
| 13,350
|
def __getitem__(self, key): return str(key) + '!!!'
|
def __getitem__(self, key): return str(key) + '!!!'
| 13,351
|
def send(self, data): """Send data to remote.""" self.sock.send(data)
|
def send(self, data): """Send data to remote.""" self.sock.send(data)
| 13,352
|
def __init__(self, path = "", title = ""): defaultfontsettings, defaulttabsettings, defaultwindowsize = geteditorprefs() global _scriptuntitledcounter if not path: if title: self.title = title else: self.title = "Untitled Script " + `_scriptuntitledcounter` _scriptuntitledcounter = _scriptuntitledcounter + 1 text = "" self._creator = W._signature self._eoln = os.linesep elif os.path.exists(path): path = resolvealiases(path) dir, name = os.path.split(path) self.title = name f = open(path, "rb") text = f.read() f.close() self._creator, filetype = MacOS.GetCreatorAndType(path) self.addrecentfile(path) else: raise IOError, "file '%s' does not exist" % path self.path = path if '\n' in text: if string.find(text, '\r\n') >= 0: self._eoln = '\r\n' else: self._eoln = '\n' text = string.replace(text, self._eoln, '\r') change = 0 else: change = 0 self._eoln = '\r' self.settings = {} if self.path: self.readwindowsettings() if self.settings.has_key("windowbounds"): bounds = self.settings["windowbounds"] else: bounds = defaultwindowsize if self.settings.has_key("fontsettings"): self.fontsettings = self.settings["fontsettings"] else: self.fontsettings = defaultfontsettings if self.settings.has_key("tabsize"): try: self.tabsettings = (tabsize, tabmode) = self.settings["tabsize"] except: self.tabsettings = defaulttabsettings else: self.tabsettings = defaulttabsettings W.Window.__init__(self, bounds, self.title, minsize = (330, 120), tabbable = 0) self.setupwidgets(text) if change > 0: self.editgroup.editor.textchanged() if self.settings.has_key("selection"): selstart, selend = self.settings["selection"] self.setselection(selstart, selend) self.open() self.setinfotext() self.globals = {} self._buf = "" # for write method self.debugging = 0 self.profiling = 0 self.run_as_main = self.settings.get("run_as_main", 0) self.run_with_interpreter = self.settings.get("run_with_interpreter", 0) self.run_with_cl_interpreter = self.settings.get("run_with_cl_interpreter", 0)
|
def __init__(self, path = "", title = ""): defaultfontsettings, defaulttabsettings, defaultwindowsize = geteditorprefs() global _scriptuntitledcounter if not path: if title: self.title = title else: self.title = "Untitled Script " + `_scriptuntitledcounter` _scriptuntitledcounter = _scriptuntitledcounter + 1 text = "" self._creator = W._signature self._eoln = os.linesep elif os.path.exists(path): path = resolvealiases(path) dir, name = os.path.split(path) self.title = name f = open(path, "rb") text = f.read() f.close() self._creator, filetype = MacOS.GetCreatorAndType(path) self.addrecentfile(path) else: raise IOError, "file '%s' does not exist" % path self.path = path self.settings = {} if self.path: self.readwindowsettings() if self.settings.has_key("windowbounds"): bounds = self.settings["windowbounds"] else: bounds = defaultwindowsize if self.settings.has_key("fontsettings"): self.fontsettings = self.settings["fontsettings"] else: self.fontsettings = defaultfontsettings if self.settings.has_key("tabsize"): try: self.tabsettings = (tabsize, tabmode) = self.settings["tabsize"] except: self.tabsettings = defaulttabsettings else: self.tabsettings = defaulttabsettings W.Window.__init__(self, bounds, self.title, minsize = (330, 120), tabbable = 0) self.setupwidgets(text) if change > 0: self.editgroup.editor.textchanged() if self.settings.has_key("selection"): selstart, selend = self.settings["selection"] self.setselection(selstart, selend) self.open() self.setinfotext() self.globals = {} self._buf = "" # for write method self.debugging = 0 self.profiling = 0 self.run_as_main = self.settings.get("run_as_main", 0) self.run_with_interpreter = self.settings.get("run_with_interpreter", 0) self.run_with_cl_interpreter = self.settings.get("run_with_cl_interpreter", 0)
| 13,353
|
def __init__(self, path = "", title = ""): defaultfontsettings, defaulttabsettings, defaultwindowsize = geteditorprefs() global _scriptuntitledcounter if not path: if title: self.title = title else: self.title = "Untitled Script " + `_scriptuntitledcounter` _scriptuntitledcounter = _scriptuntitledcounter + 1 text = "" self._creator = W._signature self._eoln = os.linesep elif os.path.exists(path): path = resolvealiases(path) dir, name = os.path.split(path) self.title = name f = open(path, "rb") text = f.read() f.close() self._creator, filetype = MacOS.GetCreatorAndType(path) self.addrecentfile(path) else: raise IOError, "file '%s' does not exist" % path self.path = path if '\n' in text: if string.find(text, '\r\n') >= 0: self._eoln = '\r\n' else: self._eoln = '\n' text = string.replace(text, self._eoln, '\r') change = 0 else: change = 0 self._eoln = '\r' self.settings = {} if self.path: self.readwindowsettings() if self.settings.has_key("windowbounds"): bounds = self.settings["windowbounds"] else: bounds = defaultwindowsize if self.settings.has_key("fontsettings"): self.fontsettings = self.settings["fontsettings"] else: self.fontsettings = defaultfontsettings if self.settings.has_key("tabsize"): try: self.tabsettings = (tabsize, tabmode) = self.settings["tabsize"] except: self.tabsettings = defaulttabsettings else: self.tabsettings = defaulttabsettings W.Window.__init__(self, bounds, self.title, minsize = (330, 120), tabbable = 0) self.setupwidgets(text) if change > 0: self.editgroup.editor.textchanged() if self.settings.has_key("selection"): selstart, selend = self.settings["selection"] self.setselection(selstart, selend) self.open() self.setinfotext() self.globals = {} self._buf = "" # for write method self.debugging = 0 self.profiling = 0 self.run_as_main = self.settings.get("run_as_main", 0) self.run_with_interpreter = self.settings.get("run_with_interpreter", 0) self.run_with_cl_interpreter = self.settings.get("run_with_cl_interpreter", 0)
|
def __init__(self, path = "", title = ""): defaultfontsettings, defaulttabsettings, defaultwindowsize = geteditorprefs() global _scriptuntitledcounter if not path: if title: self.title = title else: self.title = "Untitled Script " + `_scriptuntitledcounter` _scriptuntitledcounter = _scriptuntitledcounter + 1 text = "" self._creator = W._signature self._eoln = os.linesep elif os.path.exists(path): path = resolvealiases(path) dir, name = os.path.split(path) self.title = name f = open(path, "rb") text = f.read() f.close() self._creator, filetype = MacOS.GetCreatorAndType(path) self.addrecentfile(path) else: raise IOError, "file '%s' does not exist" % path self.path = path if '\n' in text: if string.find(text, '\r\n') >= 0: self._eoln = '\r\n' else: self._eoln = '\n' text = string.replace(text, self._eoln, '\r') change = 0 else: change = 0 self._eoln = '\r' self.settings = {} if self.path: self.readwindowsettings() if self.settings.has_key("windowbounds"): bounds = self.settings["windowbounds"] else: bounds = defaultwindowsize if self.settings.has_key("fontsettings"): self.fontsettings = self.settings["fontsettings"] else: self.fontsettings = defaultfontsettings if self.settings.has_key("tabsize"): try: self.tabsettings = (tabsize, tabmode) = self.settings["tabsize"] except: self.tabsettings = defaulttabsettings else: self.tabsettings = defaulttabsettings W.Window.__init__(self, bounds, self.title, minsize = (330, 120), tabbable = 0) self.setupwidgets(text) if self.settings.has_key("selection"): selstart, selend = self.settings["selection"] self.setselection(selstart, selend) self.open() self.setinfotext() self.globals = {} self._buf = "" # for write method self.debugging = 0 self.profiling = 0 self.run_as_main = self.settings.get("run_as_main", 0) self.run_with_interpreter = self.settings.get("run_with_interpreter", 0) self.run_with_cl_interpreter = self.settings.get("run_with_cl_interpreter", 0)
| 13,354
|
def runtest(hier, code): root = tempfile.mktemp() mkhier(root, hier) savepath = sys.path[:] codefile = tempfile.mktemp() f = open(codefile, "w") f.write(code) f.close() try: sys.path.insert(0, root) if verbose: print "sys.path =", sys.path try: execfile(codefile, globals(), {}) except: traceback.print_exc(file=sys.stdout) finally: sys.path[:] = savepath try: cleanout(root) except (os.error, IOError): pass os.remove(codefile)
|
def runtest(hier, code): root = tempfile.mktemp() mkhier(root, hier) savepath = sys.path[:] codefile = tempfile.mktemp() f = open(codefile, "w") f.write(code) f.close() try: sys.path.insert(0, root) if verbose: print "sys.path =", sys.path try: execfile(codefile, globals(), {}) except: traceback.print_exc(file=sys.stdout) finally: sys.path[:] = savepath try: cleanout(root) except (os.error, IOError): pass os.remove(codefile)
| 13,355
|
def runtest(hier, code): root = tempfile.mktemp() mkhier(root, hier) savepath = sys.path[:] codefile = tempfile.mktemp() f = open(codefile, "w") f.write(code) f.close() try: sys.path.insert(0, root) if verbose: print "sys.path =", sys.path try: execfile(codefile, globals(), {}) except: traceback.print_exc(file=sys.stdout) finally: sys.path[:] = savepath try: cleanout(root) except (os.error, IOError): pass os.remove(codefile)
|
def runtest(hier, code): root = tempfile.mktemp() mkhier(root, hier) savepath = sys.path[:] codefile = tempfile.mktemp() f = open(codefile, "w") f.write(code) f.close() try: sys.path.insert(0, root) if verbose: print "sys.path =", sys.path try: execfile(codefile, globals(), {}) except: traceback.print_exc(file=sys.stdout) finally: sys.path[:] = savepath try: cleanout(root) except (os.error, IOError): pass os.remove(codefile)
| 13,356
|
def runtest(hier, code): root = tempfile.mktemp() mkhier(root, hier) savepath = sys.path[:] codefile = tempfile.mktemp() f = open(codefile, "w") f.write(code) f.close() try: sys.path.insert(0, root) if verbose: print "sys.path =", sys.path try: execfile(codefile, globals(), {}) except: traceback.print_exc(file=sys.stdout) finally: sys.path[:] = savepath try: cleanout(root) except (os.error, IOError): pass os.remove(codefile)
|
def runtest(hier, code): root = tempfile.mktemp() mkhier(root, hier) savepath = sys.path[:] codefile = tempfile.mktemp() f = open(codefile, "w") f.write(code) f.close() try: sys.path.insert(0, root) if verbose: print "sys.path =", sys.path try: execfile(codefile, globals(), {}) except: traceback.print_exc(file=sys.stdout) finally: sys.path[:] = savepath try: cleanout(root) except (os.error, IOError): pass os.remove(codefile)
| 13,357
|
def wstring_at(ptr, size=0): """wstring_at(addr[, size]) -> string
|
def wstring_at(ptr, size=0): """wstring_at(addr[, size]) -> string
| 13,358
|
def DllGetClassObject(rclsid, riid, ppv): # First ask ctypes.com.server than comtypes.server for the # class object.
|
def DllGetClassObject(rclsid, riid, ppv): # First ask ctypes.com.server than comtypes.server for the # class object.
| 13,359
|
def DllGetClassObject(rclsid, riid, ppv): # First ask ctypes.com.server than comtypes.server for the # class object.
|
def DllGetClassObject(rclsid, riid, ppv): # First ask ctypes.com.server than comtypes.server for the # class object.
| 13,360
|
def DllGetClassObject(rclsid, riid, ppv): # First ask ctypes.com.server than comtypes.server for the # class object.
|
def DllGetClassObject(rclsid, riid, ppv): # First ask ctypes.com.server than comtypes.server for the # class object.
| 13,361
|
def DllGetClassObject(rclsid, riid, ppv): # First ask ctypes.com.server than comtypes.server for the # class object.
|
def DllGetClassObject(rclsid, riid, ppv): # First ask ctypes.com.server than comtypes.server for the # class object.
| 13,362
|
def DllCanUnloadNow(): # First ask ctypes.com.server than comtypes.server if we can unload or not. # trick py2exe by doing dynamic imports result = 0 # S_OK try: ctcom = __import__("ctypes.com.server", globals(), locals(), ['*']) except ImportError: pass else: result = ctcom.DllCanUnloadNow() if result != 0: # != S_OK return result
|
def DllCanUnloadNow(): # First ask ctypes.com.server than comtypes.server if we can unload or not. # trick py2exe by doing dynamic imports result = 0 # S_OK try: ctcom = __import__("ctypes.com.server", globals(), locals(), ['*']) except ImportError: pass else: result = ctcom.DllCanUnloadNow() if result != 0: # != S_OK return result
| 13,363
|
def DllCanUnloadNow(): # First ask ctypes.com.server than comtypes.server if we can unload or not. # trick py2exe by doing dynamic imports result = 0 # S_OK try: ctcom = __import__("ctypes.com.server", globals(), locals(), ['*']) except ImportError: pass else: result = ctcom.DllCanUnloadNow() if result != 0: # != S_OK return result
|
def DllCanUnloadNow(): # First ask ctypes.com.server than comtypes.server if we can unload or not. # trick py2exe by doing dynamic imports result = 0 # S_OK try: ccom = __import__("comtypes.server.inprocserver", globals(), locals(), ['*']) except ImportError: pass else: result = ctcom.DllCanUnloadNow() if result != 0: # != S_OK return result
| 13,364
|
def DllCanUnloadNow(): # First ask ctypes.com.server than comtypes.server if we can unload or not. # trick py2exe by doing dynamic imports result = 0 # S_OK try: ctcom = __import__("ctypes.com.server", globals(), locals(), ['*']) except ImportError: pass else: result = ctcom.DllCanUnloadNow() if result != 0: # != S_OK return result
|
def DllCanUnloadNow(): # First ask ctypes.com.server than comtypes.server if we can unload or not. # trick py2exe by doing dynamic imports result = 0 # S_OK try: ctcom = __import__("ctypes.com.server", globals(), locals(), ['*']) except ImportError: pass else: result = ctcom.DllCanUnloadNow() if result != 0: # != S_OK return result
| 13,365
|
def test_getstatus(self): # This pattern should match 'ls -ld /bin/ls' on any posix # system, however perversely configured. pat = r'''-..x..x..x # It is executable. \s+\d+ # It has some number of links. \s+\w+\s+\w+ # It has a user and group, which may # be named anything. [^/]* # Skip the date. /bin/ls # and end with the name of the file. '''
|
def test_getstatus(self): # This pattern should match 'ls -ld /bin/ls' on any posix # system, however perversely configured. pat = r'''[l-]..x..x..x # It is executable. \s+\d+ # It has some number of links. \s+\w+\s+\w+ # It has a user and group, which may # be named anything. [^/]* # Skip the date. /bin/ls # and end with the name of the file. '''
| 13,366
|
def test(fn = 'f:just samples:just.aif'): import aifc af = aifc.open(fn, 'r') print af.getparams() p = Play_Audio_mac() p.setoutrate(af.getframerate()) p.setsampwidth(af.getsampwidth()) p.setnchannels(af.getnchannels()) BUFSIZ = 10000 while 1: data = af.readframes(BUFSIZ) if not data: break p.writeframes(data) p.wait()
|
def test(): import aifc af = aifc.open(fn, 'r') print af.getparams() p = Play_Audio_mac() p.setoutrate(af.getframerate()) p.setsampwidth(af.getsampwidth()) p.setnchannels(af.getnchannels()) BUFSIZ = 10000 while 1: data = af.readframes(BUFSIZ) if not data: break p.writeframes(data) p.wait()
| 13,367
|
def set_break(self, filename, lineno, temporary=0, cond = None): filename = self.canonic(filename) import linecache # Import as late as possible line = linecache.getline(filename, lineno) if not line: return 'Line %s:%d does not exist' % (filename, lineno) if not self.breaks.has_key(filename): self.breaks[filename] = [] list = self.breaks[filename] if not lineno in list: list.append(lineno) bp = Breakpoint(filename, lineno, temporary, cond) print "Breakpoint in", filename, "at", lineno
|
def set_break(self, filename, lineno, temporary=0, cond = None): filename = self.canonic(filename) import linecache # Import as late as possible line = linecache.getline(filename, lineno) if not line: return 'Line %s:%d does not exist' % (filename, lineno) if not self.breaks.has_key(filename): self.breaks[filename] = [] list = self.breaks[filename] if not lineno in list: list.append(lineno) bp = Breakpoint(filename, lineno, temporary, cond) print "Breakpoint in", filename, "at", lineno
| 13,368
|
def range(*a): if len(a) == 1: start, stop, step = 0, a[0], 1 elif len(a) == 2: start, stop = a step = 1 elif len(a) == 3: start, stop, step = a else: raise TypeError, 'range() needs 1-3 arguments' return Range(start, stop, step)
|
def genrange(*a): """Function to implement 'range' as a generator""" start, stop, step = handleargs(a) value = start while value < stop: yield value value += step
| 13,369
|
def range(*a): if len(a) == 1: start, stop, step = 0, a[0], 1 elif len(a) == 2: start, stop = a step = 1 elif len(a) == 3: start, stop, step = a else: raise TypeError, 'range() needs 1-3 arguments' return Range(start, stop, step)
|
def range(*a): if len(a) == 1: start, stop, step = 0, a[0], 1 elif len(a) == 2: start, stop = a step = 1 elif len(a) == 3: start, stop, step = a else: raise TypeError, 'range() needs 1-3 arguments' return Range(start, stop, step)
| 13,370
|
def range(*a): if len(a) == 1: start, stop, step = 0, a[0], 1 elif len(a) == 2: start, stop = a step = 1 elif len(a) == 3: start, stop, step = a else: raise TypeError, 'range() needs 1-3 arguments' return Range(start, stop, step)
|
def range(*a): if len(a) == 1: start, stop, step = 0, a[0], 1 elif len(a) == 2: start, stop = a step = 1 elif len(a) == 3: start, stop, step = a else: raise TypeError, 'range() needs 1-3 arguments' return Range(start, stop, step)
| 13,371
|
def range(*a): if len(a) == 1: start, stop, step = 0, a[0], 1 elif len(a) == 2: start, stop = a step = 1 elif len(a) == 3: start, stop, step = a else: raise TypeError, 'range() needs 1-3 arguments' return Range(start, stop, step)
|
def range(*a): if len(a) == 1: start, stop, step = 0, a[0], 1 elif len(a) == 2: start, stop = a step = 1 elif len(a) == 3: start, stop, step = a else: raise TypeError, 'range() needs 1-3 arguments' return Range(start, stop, step)
| 13,372
|
def __init__(self, start, stop, step): if step == 0: raise ValueError, 'range() called with zero step' self.start = start self.stop = stop self.step = step self.len = max(0, int((self.stop - self.start) / self.step))
|
def__init__(self,start,stop,step):ifstep==0:raiseValueError,'range()calledwithzerostep'self.start=startself.stop=stopself.step=stepself.len=max(0,int((self.stop-self.start)/self.step))
| 13,373
|
def __repr__(self): return 'range(%r, %r, %r)' % (self.start, self.stop, self.step)
|
def__repr__(self):return'range(%r,%r,%r)'%(self.start,self.stop,self.step)
| 13,374
|
def __len__(self): return self.len
|
def__len__(self):returnself.len
| 13,375
|
def __getitem__(self, i): if 0 <= i < self.len: return self.start + self.step * i else: raise IndexError, 'range[i] index out of range'
|
def __getitem__(self, i): """implement x[i]""" if 0 <= i <= self.len: return self.start + self.step * i else: raise IndexError, 'range[i] index out of range'
| 13,376
|
def __getitem__(self, i): if 0 <= i < self.len: return self.start + self.step * i else: raise IndexError, 'range[i] index out of range'
|
def __getitem__(self, i): if 0 <= i < self.len: return self.start + self.step * i else: raise IndexError, 'range[i] index out of range'
| 13,377
|
def get_python_inc(plat_specific=0): """Return the directory containing installed Python header files. If 'plat_specific' is false (the default), this is the path to the non-platform-specific header files, i.e. Python.h and so on; otherwise, this is the path to platform-specific header files (namely config.h). """ prefix = (plat_specific and EXEC_PREFIX or PREFIX) if os.name == "posix": return os.path.join(prefix, "include", "python" + sys.version[:3]) elif os.name == "nt": return os.path.join(prefix, "Include") # include or Include? elif os.name == "mac": return os.path.join(prefix, "Include") else: raise DistutilsPlatformError, \ ("I don't know where Python installs its C header files " + "on platform '%s'") % os.name
|
def get_python_inc(plat_specific=0, prefix=None): """Return the directory containing installed Python header files. If 'plat_specific' is false (the default), this is the path to the non-platform-specific header files, i.e. Python.h and so on; otherwise, this is the path to platform-specific header files (namely config.h). """ prefix = (plat_specific and EXEC_PREFIX or PREFIX) if os.name == "posix": return os.path.join(prefix, "include", "python" + sys.version[:3]) elif os.name == "nt": return os.path.join(prefix, "Include") # include or Include? elif os.name == "mac": return os.path.join(prefix, "Include") else: raise DistutilsPlatformError, \ ("I don't know where Python installs its C header files " + "on platform '%s'") % os.name
| 13,378
|
def get_python_inc(plat_specific=0): """Return the directory containing installed Python header files. If 'plat_specific' is false (the default), this is the path to the non-platform-specific header files, i.e. Python.h and so on; otherwise, this is the path to platform-specific header files (namely config.h). """ prefix = (plat_specific and EXEC_PREFIX or PREFIX) if os.name == "posix": return os.path.join(prefix, "include", "python" + sys.version[:3]) elif os.name == "nt": return os.path.join(prefix, "Include") # include or Include? elif os.name == "mac": return os.path.join(prefix, "Include") else: raise DistutilsPlatformError, \ ("I don't know where Python installs its C header files " + "on platform '%s'") % os.name
|
def get_python_inc(plat_specific=0): """Return the directory containing installed Python header files. If 'plat_specific' is false (the default), this is the path to the non-platform-specific header files, i.e. Python.h and so on; otherwise, this is the path to platform-specific header files (namely config.h). """ if prefix is None: prefix = (plat_specific and EXEC_PREFIX or PREFIX) if os.name == "posix": return os.path.join(prefix, "include", "python" + sys.version[:3]) elif os.name == "nt": return os.path.join(prefix, "Include") # include or Include? elif os.name == "mac": return os.path.join(prefix, "Include") else: raise DistutilsPlatformError, \ ("I don't know where Python installs its C header files " + "on platform '%s'") % os.name
| 13,379
|
def get_python_lib(plat_specific=0, standard_lib=0): """Return the directory containing the Python library (standard or site additions). If 'plat_specific' is true, return the directory containing platform-specific modules, i.e. any module from a non-pure-Python module distribution; otherwise, return the platform-shared library directory. If 'standard_lib' is true, return the directory containing standard Python library modules; otherwise, return the directory for site-specific modules. """ prefix = (plat_specific and EXEC_PREFIX or PREFIX) if os.name == "posix": libpython = os.path.join(prefix, "lib", "python" + sys.version[:3]) if standard_lib: return libpython else: return os.path.join(libpython, "site-packages") elif os.name == "nt": if standard_lib: return os.path.join(PREFIX, "Lib") else: return prefix elif os.name == "mac": if platform_specific: if standard_lib: return os.path.join(EXEC_PREFIX, "Mac", "Plugins") else: raise DistutilsPlatformError, \ "OK, where DO site-specific extensions go on the Mac?" else: if standard_lib: return os.path.join(PREFIX, "Lib") else: raise DistutilsPlatformError, \ "OK, where DO site-specific modules go on the Mac?" else: raise DistutilsPlatformError, \ ("I don't know where Python installs its library " + "on platform '%s'") % os.name
|
def get_python_lib(plat_specific=0, standard_lib=0, prefix=None): """Return the directory containing the Python library (standard or site additions). If 'plat_specific' is true, return the directory containing platform-specific modules, i.e. any module from a non-pure-Python module distribution; otherwise, return the platform-shared library directory. If 'standard_lib' is true, return the directory containing standard Python library modules; otherwise, return the directory for site-specific modules. """ prefix = (plat_specific and EXEC_PREFIX or PREFIX) if os.name == "posix": libpython = os.path.join(prefix, "lib", "python" + sys.version[:3]) if standard_lib: return libpython else: return os.path.join(libpython, "site-packages") elif os.name == "nt": if standard_lib: return os.path.join(PREFIX, "Lib") else: return prefix elif os.name == "mac": if platform_specific: if standard_lib: return os.path.join(EXEC_PREFIX, "Mac", "Plugins") else: raise DistutilsPlatformError, \ "OK, where DO site-specific extensions go on the Mac?" else: if standard_lib: return os.path.join(PREFIX, "Lib") else: raise DistutilsPlatformError, \ "OK, where DO site-specific modules go on the Mac?" else: raise DistutilsPlatformError, \ ("I don't know where Python installs its library " + "on platform '%s'") % os.name
| 13,380
|
def get_python_lib(plat_specific=0, standard_lib=0): """Return the directory containing the Python library (standard or site additions). If 'plat_specific' is true, return the directory containing platform-specific modules, i.e. any module from a non-pure-Python module distribution; otherwise, return the platform-shared library directory. If 'standard_lib' is true, return the directory containing standard Python library modules; otherwise, return the directory for site-specific modules. """ prefix = (plat_specific and EXEC_PREFIX or PREFIX) if os.name == "posix": libpython = os.path.join(prefix, "lib", "python" + sys.version[:3]) if standard_lib: return libpython else: return os.path.join(libpython, "site-packages") elif os.name == "nt": if standard_lib: return os.path.join(PREFIX, "Lib") else: return prefix elif os.name == "mac": if platform_specific: if standard_lib: return os.path.join(EXEC_PREFIX, "Mac", "Plugins") else: raise DistutilsPlatformError, \ "OK, where DO site-specific extensions go on the Mac?" else: if standard_lib: return os.path.join(PREFIX, "Lib") else: raise DistutilsPlatformError, \ "OK, where DO site-specific modules go on the Mac?" else: raise DistutilsPlatformError, \ ("I don't know where Python installs its library " + "on platform '%s'") % os.name
|
def get_python_lib(plat_specific=0, standard_lib=0): """Return the directory containing the Python library (standard or site additions). If 'plat_specific' is true, return the directory containing platform-specific modules, i.e. any module from a non-pure-Python module distribution; otherwise, return the platform-shared library directory. If 'standard_lib' is true, return the directory containing standard Python library modules; otherwise, return the directory for site-specific modules. """ if prefix is None: prefix = (plat_specific and EXEC_PREFIX or PREFIX) if os.name == "posix": libpython = os.path.join(prefix, "lib", "python" + sys.version[:3]) if standard_lib: return libpython else: return os.path.join(libpython, "site-packages") elif os.name == "nt": if standard_lib: return os.path.join(PREFIX, "Lib") else: return prefix elif os.name == "mac": if platform_specific: if standard_lib: return os.path.join(EXEC_PREFIX, "Mac", "Plugins") else: raise DistutilsPlatformError, \ "OK, where DO site-specific extensions go on the Mac?" else: if standard_lib: return os.path.join(PREFIX, "Lib") else: raise DistutilsPlatformError, \ "OK, where DO site-specific modules go on the Mac?" else: raise DistutilsPlatformError, \ ("I don't know where Python installs its library " + "on platform '%s'") % os.name
| 13,381
|
def makepipeline(infile, steps, outfile): # Build a list with for each command: # [input filename or '', command string, kind, output filename or ''] list = [] for cmd, kind in steps: list.append(['', cmd, kind, '']) # # Make sure there is at least one step # if not list: list.append(['', 'cat', '--', '']) # # Take care of the input and output ends # [cmd, kind] = list[0][1:3] if kind[0] == 'f' and not infile: list.insert(0, ['', 'cat', '--', '']) list[0][0] = infile # [cmd, kind] = list[-1][1:3] if kind[1] == 'f' and not outfile: list.append(['', 'cat', '--', '']) list[-1][-1] = outfile # # Invent temporary files to connect stages that need files # garbage = [] for i in range(1, len(list)): lkind = list[i-1][2] rkind = list[i][2] if lkind[1] == 'f' or rkind[0] == 'f': temp = tempfile.mktemp() garbage.append(temp) list[i-1][-1] = list[i][0] = temp # for item in list: [inf, cmd, kind, outf] = item if kind[1] == 'f': cmd = 'OUT=' + quote(outf) + '; ' + cmd if kind[0] == 'f': cmd = 'IN=' + quote(inf) + '; ' + cmd if kind[0] == '-' and inf: cmd = cmd + ' <' + quote(inf) if kind[1] == '-' and outf: cmd = cmd + ' >' + quote(outf) item[1] = cmd # cmdlist = list[0][1] for item in list[1:]: [cmd, kind] = item[1:3] if item[0] == '': if 'f' in kind: cmd = '{ ' + cmd + '; }' cmdlist = cmdlist + ' |\n' + cmd else: cmdlist = cmdlist + '\n' + cmd # if garbage: rmcmd = 'rm -f' for file in garbage: rmcmd = rmcmd + ' ' + quote(file) trapcmd = 'trap ' + quote(rmcmd + '; exit') + ' 1 2 3 13 14 15' cmdlist = trapcmd + '\n' + cmdlist + '\n' + rmcmd # return cmdlist
|
def makepipeline(infile, steps, outfile): # Build a list with for each command: # [input filename or '', command string, kind, output filename or ''] list = [] for cmd, kind in steps: list.append(['', cmd, kind, '']) # # Make sure there is at least one step # if not list: list.append(['', 'cat', '--', '']) # # Take care of the input and output ends # [cmd, kind] = list[0][1:3] if kind[0] == 'f' and not infile: list.insert(0, ['', 'cat', '--', '']) list[0][0] = infile # [cmd, kind] = list[-1][1:3] if kind[1] == 'f' and not outfile: list.append(['', 'cat', '--', '']) list[-1][-1] = outfile # # Invent temporary files to connect stages that need files # garbage = [] for i in range(1, len(list)): lkind = list[i-1][2] rkind = list[i][2] if lkind[1] == 'f' or rkind[0] == 'f': temp = tempfile.mktemp() garbage.append(temp) list[i-1][-1] = list[i][0] = temp # for item in list: [inf, cmd, kind, outf] = item if kind[1] == 'f': cmd = 'OUT=' + quote(outf) + '; ' + cmd if kind[0] == 'f': cmd = 'IN=' + quote(inf) + '; ' + cmd if kind[0] == '-' and inf: cmd = cmd + ' <' + quote(inf) if kind[1] == '-' and outf: cmd = cmd + ' >' + quote(outf) item[1] = cmd # cmdlist = list[0][1] for item in list[1:]: [cmd, kind] = item[1:3] if item[0] == '': if 'f' in kind: cmd = '{ ' + cmd + '; }' cmdlist = cmdlist + ' |\n' + cmd else: cmdlist = cmdlist + '\n' + cmd # if garbage: rmcmd = 'rm -f' for file in garbage: rmcmd = rmcmd + ' ' + quote(file) trapcmd = 'trap ' + quote(rmcmd + '; exit') + ' 1 2 3 13 14 15' cmdlist = trapcmd + '\n' + cmdlist + '\n' + rmcmd # return cmdlist
| 13,382
|
def clear_flags(self): """Reset all flags to zero""" for flag in self.flags: self.flag = 0
|
def clear_flags(self): """Reset all flags to zero""" for flag in self.flags: self.flag = 0
| 13,383
|
def test_strptime(self): tt = time.gmtime(self.t) for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', 'j', 'm', 'M', 'p', 'S', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): format = ' %' + directive try: time.strptime(time.strftime(format, tt), format) except ValueError: self.fail('conversion specifier: %r failed.' % format)
|
def test_strptime(self): tt = time.gmtime(self.t) for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', 'j', 'm', 'M', 'p', 'S', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): format = '%' + directive strf_output = time.strftime(format, tt) try: time.strptime(time.strftime(format, tt), format) except ValueError: self.fail('conversion specifier: %r failed.' % format)
| 13,384
|
def test_strptime(self): tt = time.gmtime(self.t) for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', 'j', 'm', 'M', 'p', 'S', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): format = ' %' + directive try: time.strptime(time.strftime(format, tt), format) except ValueError: self.fail('conversion specifier: %r failed.' % format)
|
def test_strptime(self): tt = time.gmtime(self.t) for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', 'j', 'm', 'M', 'p', 'S', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): format = ' %' + directive try: time.strptime(strf_output, format) except ValueError: self.fail('conversion specifier: %r failed.' % format)
| 13,385
|
def test_strptime(self): tt = time.gmtime(self.t) for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', 'j', 'm', 'M', 'p', 'S', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): format = ' %' + directive try: time.strptime(time.strftime(format, tt), format) except ValueError: self.fail('conversion specifier: %r failed.' % format)
|
def test_strptime(self): tt = time.gmtime(self.t) for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', 'j', 'm', 'M', 'p', 'S', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): format = ' %' + directive try: time.strptime(time.strftime(format, tt), format) except ValueError: self.fail('conversion specifier: %r failed.' % format)
| 13,386
|
def runtime_library_dir_option(self, dir): # XXX Hackish, at the very least. See Python bug #445902: # http://sourceforge.net/tracker/index.php # ?func=detail&aid=445902&group_id=5470&atid=105470 # Linkers on different platforms need different options to # specify that directories need to be added to the list of # directories searched for dependencies when a dynamic library # is sought. GCC has to be told to pass the -R option through # to the linker, whereas other compilers just know this. # Other compilers may need something slightly different. At # this time, there's no way to determine this information from # the configuration data stored in the Python installation, so # we use this hack. compiler = os.path.basename(sysconfig.get_config_var("CC")) if sys.platform[:6] == "darwin": # MacOSX's linker doesn't understand the -R flag at all return "-L" + dir elif compiler[:3] == "gcc" or compiler[:3] == "g++": return "-Wl,-R" + dir else: return "-R" + dir
|
def runtime_library_dir_option(self, dir): # XXX Hackish, at the very least. See Python bug #445902: # http://sourceforge.net/tracker/index.php # ?func=detail&aid=445902&group_id=5470&atid=105470 # Linkers on different platforms need different options to # specify that directories need to be added to the list of # directories searched for dependencies when a dynamic library # is sought. GCC has to be told to pass the -R option through # to the linker, whereas other compilers just know this. # Other compilers may need something slightly different. At # this time, there's no way to determine this information from # the configuration data stored in the Python installation, so # we use this hack. compiler = os.path.basename(sysconfig.get_config_var("CC")) if sys.platform[:6] == "darwin": # MacOSX's linker doesn't understand the -R flag at all return "-L" + dir elif sys.platform[:5] == "hp-ux": return "+s -L" + dir elif compiler[:3] == "gcc" or compiler[:3] == "g++": return "-Wl,-R" + dir else: return "-R" + dir
| 13,387
|
def buildcgiapplet(): buildtools.DEBUG=1 # Find the template # (there's no point in proceeding if we can't find it) template = buildtools.findtemplate() wrapper = os.path.join(sys.exec_prefix, ":Mac:Tools:CGI:PythonCGISlave.py") # Ask for source text if not specified in sys.argv[1:] if not sys.argv[1:]: srcfss, ok = macfs.PromptGetFile('Select a CGI script:', 'TEXT', 'APPL') if not ok: return filename = srcfss.as_pathname() dstfilename = mkcgifilename(filename) dstfss, ok = macfs.StandardPutFile('Save application as:', os.path.basename(dstfilename)) if not ok: return dstfilename = dstfss.as_pathname() buildone(template, wrapper, filename, dstfilename) else: # Loop over all files to be processed for filename in sys.argv[1:]: dstfilename = mkcgifilename(filename) buildone(template, wrapper, filename, dstfilename)
|
def buildcgiapplet(): buildtools.DEBUG=1 # Find the template # (there's no point in proceeding if we can't find it) template = buildtools.findtemplate() wrapper = "PythonCGISlave.py" if not os.path.exists("PythonCGISlave.py"): wrapper = os.path.join(sys.exec_prefix, ":Mac:Tools:CGI", wrapper) # Ask for source text if not specified in sys.argv[1:] if not sys.argv[1:]: srcfss, ok = macfs.PromptGetFile('Select a CGI script:', 'TEXT', 'APPL') if not ok: return filename = srcfss.as_pathname() dstfilename = mkcgifilename(filename) dstfss, ok = macfs.StandardPutFile('Save application as:', os.path.basename(dstfilename)) if not ok: return dstfilename = dstfss.as_pathname() buildone(template, wrapper, filename, dstfilename) else: # Loop over all files to be processed for filename in sys.argv[1:]: dstfilename = mkcgifilename(filename) buildone(template, wrapper, filename, dstfilename)
| 13,388
|
def makeconfig(infp, outfp, modules): m1 = regex.compile('-- ADDMODULE MARKER 1 --') m2 = regex.compile('-- ADDMODULE MARKER 2 --') while 1: line = infp.readline() if not line: break outfp.write(line) if m1 and m1.search(line) >= 0: m1 = None for mod in modules: if mod in never: continue outfp.write('extern void init%s();\n' % mod) elif m2 and m2.search(line) >= 0: m2 = None for mod in modules: if mod in never: continue outfp.write('\t{"%s", init%s},\n' % (mod, mod)) if m1: sys.stderr.write('MARKER 1 never found\n') elif m2: sys.stderr.write('MARKER 2 never found\n')
|
def makeconfig(infp, outfp, modules, with_ifdef=0): m1 = regex.compile('-- ADDMODULE MARKER 1 --') m2 = regex.compile('-- ADDMODULE MARKER 2 --') while 1: line = infp.readline() if not line: break outfp.write(line) if m1 and m1.search(line) >= 0: m1 = None for mod in modules: if mod in never: continue outfp.write('extern void init%s();\n' % mod) elif m2 and m2.search(line) >= 0: m2 = None for mod in modules: if mod in never: continue outfp.write('\t{"%s", init%s},\n' % (mod, mod)) if m1: sys.stderr.write('MARKER 1 never found\n') elif m2: sys.stderr.write('MARKER 2 never found\n')
| 13,389
|
def _setval(self, pos, val): f = _open(self._datfile, 'rb+') f.seek(pos) f.write(val) f.close() return pos, (val)
|
def _setval(self, pos, val): f = _open(self._datfile, 'rb+') f.seek(pos) f.write(val) f.close() return (pos, len(val))
| 13,390
|
def connect(self, address): self.connected = False err = self.socket.connect_ex(address) # XXX Should interpret Winsock return values if err in (EINPROGRESS, EALREADY, EWOULDBLOCK): return if err in (0, EISCONN): self.addr = address self.connected = True self.handle_connect() else: raise socket.error, err
|
def connect(self, address): self.connected = False err = self.socket.connect_ex(address) # XXX Should interpret Winsock return values if err in (EINPROGRESS, EALREADY, EWOULDBLOCK): return if err in (0, EISCONN): self.addr = address self.connected = True self.handle_connect() else: raise socket.error, err
| 13,391
|
def accept(self): # XXX can return either an address pair or None try: conn, addr = self.socket.accept() return conn, addr except socket.error, why: if why[0] == EWOULDBLOCK: pass else: raise socket.error, why
|
def accept(self): # XXX can return either an address pair or None try: conn, addr = self.socket.accept() return conn, addr except socket.error, why: if why[0] == EWOULDBLOCK: pass else: raise socket.error, why
| 13,392
|
def send(self, data): try: result = self.socket.send(data) return result except socket.error, why: if why[0] == EWOULDBLOCK: return 0 else: raise socket.error, why return 0
|
def send(self, data): try: result = self.socket.send(data) return result except socket.error, why: if why[0] == EWOULDBLOCK: return 0 else: raise return 0
| 13,393
|
def recv(self, buffer_size): try: data = self.socket.recv(buffer_size) if not data: # a closed connection is indicated by signaling # a read condition, and having recv() return 0. self.handle_close() return '' else: return data except socket.error, why: # winsock sometimes throws ENOTCONN if why[0] in [ECONNRESET, ENOTCONN, ESHUTDOWN]: self.handle_close() return '' else: raise socket.error, why
|
def recv(self, buffer_size): try: data = self.socket.recv(buffer_size) if not data: # a closed connection is indicated by signaling # a read condition, and having recv() return 0. self.handle_close() return '' else: return data except socket.error, why: # winsock sometimes throws ENOTCONN if why[0] in [ECONNRESET, ENOTCONN, ESHUTDOWN]: self.handle_close() return '' else: raise socket.error, why
| 13,394
|
def _create_formatters(cp): """Create and return formatters""" flist = cp.get("formatters", "keys") if not len(flist): return {} flist = string.split(flist, ",") formatters = {} for form in flist: sectname = "formatter_%s" % form opts = cp.options(sectname) if "format" in opts: fs = cp.get(sectname, "format", 1) else: fs = None if "datefmt" in opts: dfs = cp.get(sectname, "datefmt", 1) else: dfs = None c = logging.Formatter if "class" in opts: class_name = cp.get(sectname, "class") if class_name: c = _resolve(class_name) f = c(fs, dfs) formatters[form] = f return formatters
|
def _create_formatters(cp): """Create and return formatters""" flist = cp.get("formatters", "keys") if not len(flist): return {} flist = string.split(flist, ",") formatters = {} for form in flist: sectname = "formatter_%s" % string.strip(form) opts = cp.options(sectname) if "format" in opts: fs = cp.get(sectname, "format", 1) else: fs = None if "datefmt" in opts: dfs = cp.get(sectname, "datefmt", 1) else: dfs = None c = logging.Formatter if "class" in opts: class_name = cp.get(sectname, "class") if class_name: c = _resolve(class_name) f = c(fs, dfs) formatters[form] = f return formatters
| 13,395
|
def _install_handlers(cp, formatters): """Install and return handlers""" hlist = cp.get("handlers", "keys") if not len(hlist): return {} hlist = string.split(hlist, ",") handlers = {} fixups = [] #for inter-handler references for hand in hlist: sectname = "handler_%s" % hand klass = cp.get(sectname, "class") opts = cp.options(sectname) if "formatter" in opts: fmt = cp.get(sectname, "formatter") else: fmt = "" klass = eval(klass, vars(logging)) args = cp.get(sectname, "args") args = eval(args, vars(logging)) h = apply(klass, args) if "level" in opts: level = cp.get(sectname, "level") h.setLevel(logging._levelNames[level]) if len(fmt): h.setFormatter(formatters[fmt]) #temporary hack for FileHandler and MemoryHandler. if klass == logging.handlers.MemoryHandler: if "target" in opts: target = cp.get(sectname,"target") else: target = "" if len(target): #the target handler may not be loaded yet, so keep for later... fixups.append((h, target)) handlers[hand] = h #now all handlers are loaded, fixup inter-handler references... for h, t in fixups: h.setTarget(handlers[t]) return handlers
|
def _install_handlers(cp, formatters): """Install and return handlers""" hlist = cp.get("handlers", "keys") if not len(hlist): return {} hlist = string.split(hlist, ",") handlers = {} fixups = [] #for inter-handler references for hand in hlist: sectname = "handler_%s" % string.strip(hand) klass = cp.get(sectname, "class") opts = cp.options(sectname) if "formatter" in opts: fmt = cp.get(sectname, "formatter") else: fmt = "" klass = eval(klass, vars(logging)) args = cp.get(sectname, "args") args = eval(args, vars(logging)) h = apply(klass, args) if "level" in opts: level = cp.get(sectname, "level") h.setLevel(logging._levelNames[level]) if len(fmt): h.setFormatter(formatters[fmt]) #temporary hack for FileHandler and MemoryHandler. if klass == logging.handlers.MemoryHandler: if "target" in opts: target = cp.get(sectname,"target") else: target = "" if len(target): #the target handler may not be loaded yet, so keep for later... fixups.append((h, target)) handlers[hand] = h #now all handlers are loaded, fixup inter-handler references... for h, t in fixups: h.setTarget(handlers[t]) return handlers
| 13,396
|
def _install_loggers(cp, handlers): """Create and install loggers""" # configure the root first llist = cp.get("loggers", "keys") llist = string.split(llist, ",") llist.remove("root") sectname = "logger_root" root = logging.root log = root opts = cp.options(sectname) if "level" in opts: level = cp.get(sectname, "level") log.setLevel(logging._levelNames[level]) for h in root.handlers[:]: root.removeHandler(h) hlist = cp.get(sectname, "handlers") if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: log.addHandler(handlers[hand]) #and now the others... #we don't want to lose the existing loggers, #since other threads may have pointers to them. #existing is set to contain all existing loggers, #and as we go through the new configuration we #remove any which are configured. At the end, #what's left in existing is the set of loggers #which were in the previous configuration but #which are not in the new configuration. existing = root.manager.loggerDict.keys() #now set up the new ones... for log in llist: sectname = "logger_%s" % log qn = cp.get(sectname, "qualname") opts = cp.options(sectname) if "propagate" in opts: propagate = cp.getint(sectname, "propagate") else: propagate = 1 logger = logging.getLogger(qn) if qn in existing: existing.remove(qn) if "level" in opts: level = cp.get(sectname, "level") logger.setLevel(logging._levelNames[level]) for h in logger.handlers[:]: logger.removeHandler(h) logger.propagate = propagate logger.disabled = 0 hlist = cp.get(sectname, "handlers") if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: logger.addHandler(handlers[hand]) #Disable any old loggers. There's no point deleting #them as other threads may continue to hold references #and by disabling them, you stop them doing any logging. for log in existing: root.manager.loggerDict[log].disabled = 1
|
def _install_loggers(cp, handlers): """Create and install loggers""" # configure the root first llist = cp.get("loggers", "keys") llist = string.split(llist, ",") llist.remove("root") sectname = "logger_root" root = logging.root log = root opts = cp.options(sectname) if "level" in opts: level = cp.get(sectname, "level") log.setLevel(logging._levelNames[level]) for h in root.handlers[:]: root.removeHandler(h) hlist = cp.get(sectname, "handlers") if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: log.addHandler(handlers[string.strip(hand)]) #and now the others... #we don't want to lose the existing loggers, #since other threads may have pointers to them. #existing is set to contain all existing loggers, #and as we go through the new configuration we #remove any which are configured. At the end, #what's left in existing is the set of loggers #which were in the previous configuration but #which are not in the new configuration. existing = root.manager.loggerDict.keys() #now set up the new ones... for log in llist: sectname = "logger_%s" % log qn = cp.get(sectname, "qualname") opts = cp.options(sectname) if "propagate" in opts: propagate = cp.getint(sectname, "propagate") else: propagate = 1 logger = logging.getLogger(qn) if qn in existing: existing.remove(qn) if "level" in opts: level = cp.get(sectname, "level") logger.setLevel(logging._levelNames[level]) for h in logger.handlers[:]: logger.removeHandler(h) logger.propagate = propagate logger.disabled = 0 hlist = cp.get(sectname, "handlers") if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: logger.addHandler(handlers[hand]) #Disable any old loggers. There's no point deleting #them as other threads may continue to hold references #and by disabling them, you stop them doing any logging. for log in existing: root.manager.loggerDict[log].disabled = 1
| 13,397
|
def _install_loggers(cp, handlers): """Create and install loggers""" # configure the root first llist = cp.get("loggers", "keys") llist = string.split(llist, ",") llist.remove("root") sectname = "logger_root" root = logging.root log = root opts = cp.options(sectname) if "level" in opts: level = cp.get(sectname, "level") log.setLevel(logging._levelNames[level]) for h in root.handlers[:]: root.removeHandler(h) hlist = cp.get(sectname, "handlers") if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: log.addHandler(handlers[hand]) #and now the others... #we don't want to lose the existing loggers, #since other threads may have pointers to them. #existing is set to contain all existing loggers, #and as we go through the new configuration we #remove any which are configured. At the end, #what's left in existing is the set of loggers #which were in the previous configuration but #which are not in the new configuration. existing = root.manager.loggerDict.keys() #now set up the new ones... for log in llist: sectname = "logger_%s" % log qn = cp.get(sectname, "qualname") opts = cp.options(sectname) if "propagate" in opts: propagate = cp.getint(sectname, "propagate") else: propagate = 1 logger = logging.getLogger(qn) if qn in existing: existing.remove(qn) if "level" in opts: level = cp.get(sectname, "level") logger.setLevel(logging._levelNames[level]) for h in logger.handlers[:]: logger.removeHandler(h) logger.propagate = propagate logger.disabled = 0 hlist = cp.get(sectname, "handlers") if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: logger.addHandler(handlers[hand]) #Disable any old loggers. There's no point deleting #them as other threads may continue to hold references #and by disabling them, you stop them doing any logging. for log in existing: root.manager.loggerDict[log].disabled = 1
|
def _install_loggers(cp, handlers): """Create and install loggers""" # configure the root first llist = cp.get("loggers", "keys") llist = string.split(llist, ",") llist.remove("root") sectname = "logger_root" root = logging.root log = root opts = cp.options(sectname) if "level" in opts: level = cp.get(sectname, "level") log.setLevel(logging._levelNames[level]) for h in root.handlers[:]: root.removeHandler(h) hlist = cp.get(sectname, "handlers") if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: log.addHandler(handlers[hand]) #and now the others... #we don't want to lose the existing loggers, #since other threads may have pointers to them. #existing is set to contain all existing loggers, #and as we go through the new configuration we #remove any which are configured. At the end, #what's left in existing is the set of loggers #which were in the previous configuration but #which are not in the new configuration. existing = root.manager.loggerDict.keys() #now set up the new ones... for log in llist: sectname = "logger_%s" % log qn = cp.get(sectname, "qualname") opts = cp.options(sectname) if "propagate" in opts: propagate = cp.getint(sectname, "propagate") else: propagate = 1 logger = logging.getLogger(qn) if qn in existing: existing.remove(qn) if "level" in opts: level = cp.get(sectname, "level") logger.setLevel(logging._levelNames[level]) for h in logger.handlers[:]: logger.removeHandler(h) logger.propagate = propagate logger.disabled = 0 hlist = cp.get(sectname, "handlers") if len(hlist): hlist = string.split(hlist, ",") for hand in hlist: logger.addHandler(handlers[string.strip(hand)]) #Disable any old loggers. There's no point deleting #them as other threads may continue to hold references #and by disabling them, you stop them doing any logging. for log in existing: root.manager.loggerDict[log].disabled = 1
| 13,398
|
def main(tests=None, testdir=None): """Execute a test suite. This also parses command-line options and modifies its behaviour accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. """ try: opts, args = getopt.getopt(sys.argv[1:], 'vgqxs') except getopt.error, msg: print msg print __doc__ return 2 verbose = 0 quiet = 0 generate = 0 exclude = 0 single = 0 for o, a in opts: if o == '-v': verbose = verbose+1 if o == '-q': quiet = 1; verbose = 0 if o == '-g': generate = 1 if o == '-x': exclude = 1 if o == '-s': single = 1 if generate and verbose: print "-g and -v don't go together!" return 2 good = [] bad = [] skipped = [] if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = string.strip(fp.read()) tests = [next] fp.close() except IOError: pass for i in range(len(args)): # Strip trailing ".py" from arguments if args[i][-3:] == '.py': args[i] = args[i][:-3] stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] test_support.verbose = verbose # Tell tests to be moderately quiet save_modules = sys.modules.keys() for test in tests: if not quiet: print test ok = runtest(test, generate, verbose, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: if not quiet: print "test", test, print "skipped -- an optional feature could not be imported" skipped.append(test) # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules: test_support.unload(module) if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if bad: print count(len(bad), "test"), "failed:", print string.join(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:", print string.join(skipped) if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) return len(bad) > 0
|
def main(tests=None, testdir=None): """Execute a test suite. This also parses command-line options and modifies its behaviour accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. """ try: opts, args = getopt.getopt(sys.argv[1:], 'vgqxs') except getopt.error, msg: print msg print __doc__ return 2 verbose = 0 quiet = 0 generate = 0 exclude = 0 single = 0 for o, a in opts: if o == '-v': verbose = verbose+1 if o == '-q': quiet = 1; verbose = 0 if o == '-g': generate = 1 if o == '-x': exclude = 1 if o == '-s': single = 1 if generate and verbose: print "-g and -v don't go together!" return 2 good = [] bad = [] skipped = [] if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = string.strip(fp.read()) tests = [next] fp.close() except IOError: pass for i in range(len(args)): # Strip trailing ".py" from arguments if args[i][-3:] == '.py': args[i] = args[i][:-3] stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] test_support.verbose = verbose # Tell tests to be moderately quiet save_modules = sys.modules.keys() for test in tests: if not quiet: print test ok = runtest(test, generate, verbose, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: if not quiet: print "test", test, print "skipped -- an optional feature could not be imported" skipped.append(test) # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if bad: print count(len(bad), "test"), "failed:", print string.join(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:", print string.join(skipped) if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) return len(bad) > 0
| 13,399
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.