rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
runner=unittest.TextTestRunner(verbosity=VERBOSE) | runner=unittest.TextTestRunner(verbosity=self.verbosity) | def runSuite(self, suite): runner=unittest.TextTestRunner(verbosity=VERBOSE) runner.run(suite) |
fname, ext=os.path.splitext(name) if name[:4]=='test' and name[-3:]=='.py' and \ name != 'testrunner.py': filepath=os.path.join(pathname, name) if self.smellsLikeATest(filepath): self.runFile(filepath) for name in names: | def runPath(self, pathname): """Run all tests found in the directory named by pathname and all subdirectories.""" if not os.path.isabs(pathname): pathname = os.path.join(self.basepath, pathname) names=os.listdir(pathname) for name in names: fname, ext=os.path.splitext(name) if name[:4]=='test' and name[-3:]=='.py' and \ name != 'testrunner.py': filepath=os.path.join(pathname, name) if self.smellsLikeATest(filepath): self.runFile(filepath) for name in names: fullpath=os.path.join(pathname, name) if os.path.isdir(fullpath): self.runPath(fullpath) |
|
try: suite=self.getSuiteFromFile(filename) | try: suite=self.getSuiteFromFile(name) | def runFile(self, filename): """Run the test suite defined by filename.""" working_dir = os.getcwd() dirname, name = os.path.split(filename) if dirname: os.chdir(dirname) self.report('Running: %s' % filename) try: suite=self.getSuiteFromFile(filename) except: traceback.print_exc() suite=None if suite is None: self.report('No test suite found in file:\n%s' % filename) return self.runSuite(suite) os.chdir(working_dir) |
suite=None if suite is None: self.report('No test suite found in file:\n%s' % filename) return self.runSuite(suite) | suite=None if suite is not None: self.runSuite(suite) else: self.report('No test suite found in file:\n%s\n' % filename) | def runFile(self, filename): """Run the test suite defined by filename.""" working_dir = os.getcwd() dirname, name = os.path.split(filename) if dirname: os.chdir(dirname) self.report('Running: %s' % filename) try: suite=self.getSuiteFromFile(filename) except: traceback.print_exc() suite=None if suite is None: self.report('No test suite found in file:\n%s' % filename) return self.runSuite(suite) os.chdir(working_dir) |
whether it succeeded. Quiet mode prints a period as each test runs. | whether it succeeded. Running with -q is the same as running with -v1. | def main(args): usage_msg="""Usage: python testrunner.py options If run without options, testrunner will display this usage message. If you want to run all test suites found in all subdirectories of the current working directory, use the -a option. options: -a Run all tests found in all subdirectories of the current working directory. This is the default if no options are specified. -d dirpath Run all tests found in the directory specified by dirpath, and recursively in all its subdirectories. The dirpath should be a full system path. -f filepath Run the test suite found in the file specified. The filepath should be a fully qualified path to the file to be run. -q Run tests without producing verbose output. The tests are normally run in verbose mode, which produces a line of output for each test that includes the name of the test and whether it succeeded. Quiet mode prints a period as each test runs. -h Display usage information. """ pathname=None filename=None test_all=None options, arg=getopt.getopt(args, 'ahd:f:q') if not options: err_exit(usage_msg) for name, value in options: name=name[1:] if name == 'a': test_all=1 elif name == 'd': pathname=string.strip(value) elif name == 'f': filename=string.strip(value) elif name == 'h': err_exit(usage_msg, 0) elif name == 'q': global VERBOSE VERBOSE = 1 else: err_exit(usage_msg) testrunner=TestRunner(os.getcwd()) if test_all: testrunner.runAllTests() elif pathname: testrunner.runPath(pathname) elif filename: testrunner.runFile(filename) sys.exit(0) |
options, arg=getopt.getopt(args, 'ahd:f:q') | verbosity = VERBOSE options, arg=getopt.getopt(args, 'ahd:f:v:q') | def main(args): usage_msg="""Usage: python testrunner.py options If run without options, testrunner will display this usage message. If you want to run all test suites found in all subdirectories of the current working directory, use the -a option. options: -a Run all tests found in all subdirectories of the current working directory. This is the default if no options are specified. -d dirpath Run all tests found in the directory specified by dirpath, and recursively in all its subdirectories. The dirpath should be a full system path. -f filepath Run the test suite found in the file specified. The filepath should be a fully qualified path to the file to be run. -q Run tests without producing verbose output. The tests are normally run in verbose mode, which produces a line of output for each test that includes the name of the test and whether it succeeded. Quiet mode prints a period as each test runs. -h Display usage information. """ pathname=None filename=None test_all=None options, arg=getopt.getopt(args, 'ahd:f:q') if not options: err_exit(usage_msg) for name, value in options: name=name[1:] if name == 'a': test_all=1 elif name == 'd': pathname=string.strip(value) elif name == 'f': filename=string.strip(value) elif name == 'h': err_exit(usage_msg, 0) elif name == 'q': global VERBOSE VERBOSE = 1 else: err_exit(usage_msg) testrunner=TestRunner(os.getcwd()) if test_all: testrunner.runAllTests() elif pathname: testrunner.runPath(pathname) elif filename: testrunner.runFile(filename) sys.exit(0) |
global VERBOSE VERBOSE = 1 | verbosity = 1 | def main(args): usage_msg="""Usage: python testrunner.py options If run without options, testrunner will display this usage message. If you want to run all test suites found in all subdirectories of the current working directory, use the -a option. options: -a Run all tests found in all subdirectories of the current working directory. This is the default if no options are specified. -d dirpath Run all tests found in the directory specified by dirpath, and recursively in all its subdirectories. The dirpath should be a full system path. -f filepath Run the test suite found in the file specified. The filepath should be a fully qualified path to the file to be run. -q Run tests without producing verbose output. The tests are normally run in verbose mode, which produces a line of output for each test that includes the name of the test and whether it succeeded. Quiet mode prints a period as each test runs. -h Display usage information. """ pathname=None filename=None test_all=None options, arg=getopt.getopt(args, 'ahd:f:q') if not options: err_exit(usage_msg) for name, value in options: name=name[1:] if name == 'a': test_all=1 elif name == 'd': pathname=string.strip(value) elif name == 'f': filename=string.strip(value) elif name == 'h': err_exit(usage_msg, 0) elif name == 'q': global VERBOSE VERBOSE = 1 else: err_exit(usage_msg) testrunner=TestRunner(os.getcwd()) if test_all: testrunner.runAllTests() elif pathname: testrunner.runPath(pathname) elif filename: testrunner.runFile(filename) sys.exit(0) |
testrunner=TestRunner(os.getcwd()) | testrunner = TestRunner(os.getcwd(), verbosity=verbosity) | def main(args): usage_msg="""Usage: python testrunner.py options If run without options, testrunner will display this usage message. If you want to run all test suites found in all subdirectories of the current working directory, use the -a option. options: -a Run all tests found in all subdirectories of the current working directory. This is the default if no options are specified. -d dirpath Run all tests found in the directory specified by dirpath, and recursively in all its subdirectories. The dirpath should be a full system path. -f filepath Run the test suite found in the file specified. The filepath should be a fully qualified path to the file to be run. -q Run tests without producing verbose output. The tests are normally run in verbose mode, which produces a line of output for each test that includes the name of the test and whether it succeeded. Quiet mode prints a period as each test runs. -h Display usage information. """ pathname=None filename=None test_all=None options, arg=getopt.getopt(args, 'ahd:f:q') if not options: err_exit(usage_msg) for name, value in options: name=name[1:] if name == 'a': test_all=1 elif name == 'd': pathname=string.strip(value) elif name == 'f': filename=string.strip(value) elif name == 'h': err_exit(usage_msg, 0) elif name == 'q': global VERBOSE VERBOSE = 1 else: err_exit(usage_msg) testrunner=TestRunner(os.getcwd()) if test_all: testrunner.runAllTests() elif pathname: testrunner.runPath(pathname) elif filename: testrunner.runFile(filename) sys.exit(0) |
'--ignore-pyexpat', 'prefix=', | 'ignore-pyexpat', 'prefix=', | def main(): # below assumes this script is in the BASE_DIR/inst directory global PREFIX BASE_DIR=os.path.abspath(os.path.dirname(os.path.dirname(sys.argv[0]))) BUILD_BASE=os.path.join(os.getcwd(), 'build-base') PYTHON=sys.executable MAKEFILE=open(os.path.join(BASE_DIR, 'inst', IN_MAKEFILE)).read() REQUIRE_LF_ENABLED = 1 REQUIRE_ZLIB = 1 REQURE_PYEXPAT = 1 INSTALL_FLAGS = '' DISTUTILS_OPTS = '' try: longopts = ['help', 'ignore-largefile', 'ignore-zlib', '--ignore-pyexpat', 'prefix=', 'build-base=', 'optimize', 'no-compile', 'quiet'] opts, args = getopt.getopt(sys.argv[1:], 'h', longopts) except getopt.GetoptError, v: print v usage() sys.exit(1) for o, a in opts: if o in ('-h', '--help'): usage() sys.exit() if o == '--prefix': PREFIX=os.path.abspath(os.path.expanduser(a)) if o == '--ignore-largefile': REQUIRE_LF_ENABLED=0 if o == '--ignore-zlib': REQUIRE_ZLIB=0 if o == '--ignore-pyexpat': REQUIRE_PYEXPAT=0 if o == '--optimize': INSTALL_FLAGS = '--optimize=1 --no-compile' if o == '--no-compile': INSTALL_FLAGS = '--no-compile' if o == '--build-base': BUILD_BASE = a if o == '--quiet': DISTUTILS_OPTS = '-q' global QUIET QUIET = 1 if REQUIRE_LF_ENABLED: test_largefile() if REQUIRE_ZLIB: test_zlib() if REQUIRE_PYEXPAT: test_pyexpat() out(' - Zope top-level binary directory will be %s.' % PREFIX) if INSTALL_FLAGS: out(' - Distutils install flags will be "%s"' % INSTALL_FLAGS) idata = { '<<PYTHON>>':PYTHON, '<<PREFIX>>':PREFIX, '<<BASE_DIR>>':BASE_DIR, '<<BUILD_BASE>>':BUILD_BASE, '<<INSTALL_FLAGS>>':INSTALL_FLAGS, '<<ZOPE_MAJOR_VERSION>>':versions.ZOPE_MAJOR_VERSION, '<<ZOPE_MINOR_VERSION>>':versions.ZOPE_MINOR_VERSION, '<<VERSION_RELEASE_TAG>>':versions.VERSION_RELEASE_TAG, '<<DISTUTILS_OPTS>>':DISTUTILS_OPTS, } for k,v in idata.items(): MAKEFILE = MAKEFILE.replace(k, v) f = open(os.path.join(os.getcwd(), 'makefile'), 'w') f.write(MAKEFILE) out(' - Makefile written.') out('') out(' Next, run %s.' % MAKE_COMMAND) out('') |
if uri[0]=='/': uri=uri[1:] return uri | return urllib.unquote(uri) | def url(self, ftype=urllib.splittype, fhost=urllib.splithost): """Return a SCRIPT_NAME-based url for an object.""" if hasattr(self, 'DestinationURL') and \ callable(self.DestinationURL): url='%s/%s' % (self.DestinationURL(), self.id) else: url=self.absolute_url() type, uri=ftype(url) host, uri=fhost(uri) script_name=self.REQUEST['SCRIPT_NAME'] __traceback_info__=(`uri`, `script_name`) if script_name: uri=filter(None, string.split(uri, script_name))[0] uri=uri or '/' if uri[0]=='/': uri=uri[1:] return uri |
if md.has_key(args['header']): output(md.getitem(args['header'],0)( | doc=args['header'] if hasattr(self, doc): doc=getattr(self, doc) elif md.has_key(doc): doc=md.getitem(args['header'],0) else: doc=None if doc is not None: output(doc( | def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data, colspan, section, md, treeData, level=0, args=None): "Render a tree as a table" have_arg=args.has_key if level >= 0: tpUrl=self.tpURL() url = (url and ('%s/%s' % (url, tpUrl))) or tpUrl root_url = root_url or tpUrl treeData['tree-item-url']=url treeData['tree-level']=level treeData['tree-item-expanded']=0 exp=0 sub=None output=data.append script=md['SCRIPT_NAME'] try: items=getattr(self, args['branches'])() except: items=None if not items and have_arg('leaves'): items=1 if (args.has_key('sort')) and (items is not None) and (items != 1): # Faster/less mem in-place sort if type(items)==type(()): items=list(items) sort=args['sort'] size=range(len(items)) for i in size: v=items[i] k=getattr(v,sort) try: k=k() except: pass items[i]=(k,v) items.sort() for i in size: items[i]=items[i][1] diff.append(id) if substate is state: output('<TABLE CELLSPACING="0">\n') sub=substate[0] exp=items else: # Add prefix output('<TR>\n') # Add +/- icon if items: if level: if level > 3: output( '<TD COLSPAN="%s"></TD>' % (level-1)) elif level > 1: output('<TD></TD>' * (level-1)) output('<TD WIDTH="16"></TD>\n') output('<TD WIDTH="16" VALIGN="TOP">') for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break #################################### # Mostly inline encode_seq for speed s=compress(str(diff)) if len(s) > 57: s=encode_str(s) else: s=b2a_base64(s)[:-1] l=find(s,'=') if l >= 0: s=s[:l] s=translate(s, tplus) #################################### if exp: treeData['tree-item-expanded']=1 output('<A HREF="%s?tree-c=%s">' '<IMG SRC="%s/p_/mi" BORDER=0></A>' % (root_url,s, script)) else: output('<A HREF="%s?tree-e=%s">' '<IMG SRC="%s/p_/pl" BORDER=0></A>' % (root_url,s, script)) output('</TD>\n') else: if level > 2: output('<TD COLSPAN="%s"></TD>' % level) elif level > 0: output('<TD></TD>' * level) output('<TD WIDTH="16"></TD>\n') # add item text dataspan=colspan-level output('<TD%s%s VALIGN="TOP">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(section(self, md)) output('</TD>\n</TR>\n') if exp: level=level+1 dataspan=colspan-level if level > 3: h='<TD COLSPAN="%s"></TD>' % (level-1) elif level > 1: h='<TD></TD>' * (level-1) else: h='' if have_arg('header'): if md.has_key(args['header']): output(md.getitem(args['header'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) if items==1: # leaves treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['leaves'],0)( self,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) md._pop(1) elif have_arg('expand'): treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['expand'],0)(self,md)) md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, 'tpId'): id=item.tpId() elif hasattr(item, '_p_oid'): id=item._p_oid else: id=pyid(item) if len(sub)==1: sub.append([]) substate=sub[1] ids[id]=1 data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) if not sub[1]: del sub[1] ids=ids.has_key for i in range(len(substate)-1,-1): if not ids(substate[i][0]): del substate[i] if have_arg('footer'): if md.has_key(args['footer']): output(md.getitem(args['footer'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) del diff[-1] if not diff: output('</TABLE>\n') return data |
treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['leaves'],0)( self,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) md._pop(1) | doc=args['leaves'] if hasattr(self, doc): doc=getattr(self, doc) elif md.has_key(doc): doc=md.getitem(args['header'],0) else: doc=None if doc is not None: treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(doc( self,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) md._pop(1) | def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data, colspan, section, md, treeData, level=0, args=None): "Render a tree as a table" have_arg=args.has_key if level >= 0: tpUrl=self.tpURL() url = (url and ('%s/%s' % (url, tpUrl))) or tpUrl root_url = root_url or tpUrl treeData['tree-item-url']=url treeData['tree-level']=level treeData['tree-item-expanded']=0 exp=0 sub=None output=data.append script=md['SCRIPT_NAME'] try: items=getattr(self, args['branches'])() except: items=None if not items and have_arg('leaves'): items=1 if (args.has_key('sort')) and (items is not None) and (items != 1): # Faster/less mem in-place sort if type(items)==type(()): items=list(items) sort=args['sort'] size=range(len(items)) for i in size: v=items[i] k=getattr(v,sort) try: k=k() except: pass items[i]=(k,v) items.sort() for i in size: items[i]=items[i][1] diff.append(id) if substate is state: output('<TABLE CELLSPACING="0">\n') sub=substate[0] exp=items else: # Add prefix output('<TR>\n') # Add +/- icon if items: if level: if level > 3: output( '<TD COLSPAN="%s"></TD>' % (level-1)) elif level > 1: output('<TD></TD>' * (level-1)) output('<TD WIDTH="16"></TD>\n') output('<TD WIDTH="16" VALIGN="TOP">') for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break #################################### # Mostly inline encode_seq for speed s=compress(str(diff)) if len(s) > 57: s=encode_str(s) else: s=b2a_base64(s)[:-1] l=find(s,'=') if l >= 0: s=s[:l] s=translate(s, tplus) #################################### if exp: treeData['tree-item-expanded']=1 output('<A HREF="%s?tree-c=%s">' '<IMG SRC="%s/p_/mi" BORDER=0></A>' % (root_url,s, script)) else: output('<A HREF="%s?tree-e=%s">' '<IMG SRC="%s/p_/pl" BORDER=0></A>' % (root_url,s, script)) output('</TD>\n') else: if level > 2: output('<TD COLSPAN="%s"></TD>' % level) elif level > 0: output('<TD></TD>' * level) output('<TD WIDTH="16"></TD>\n') # add item text dataspan=colspan-level output('<TD%s%s VALIGN="TOP">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(section(self, md)) output('</TD>\n</TR>\n') if exp: level=level+1 dataspan=colspan-level if level > 3: h='<TD COLSPAN="%s"></TD>' % (level-1) elif level > 1: h='<TD></TD>' * (level-1) else: h='' if have_arg('header'): if md.has_key(args['header']): output(md.getitem(args['header'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) if items==1: # leaves treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['leaves'],0)( self,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) md._pop(1) elif have_arg('expand'): treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['expand'],0)(self,md)) md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, 'tpId'): id=item.tpId() elif hasattr(item, '_p_oid'): id=item._p_oid else: id=pyid(item) if len(sub)==1: sub.append([]) substate=sub[1] ids[id]=1 data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) if not sub[1]: del sub[1] ids=ids.has_key for i in range(len(substate)-1,-1): if not ids(substate[i][0]): del substate[i] if have_arg('footer'): if md.has_key(args['footer']): output(md.getitem(args['footer'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) del diff[-1] if not diff: output('</TABLE>\n') return data |
if md.has_key(args['footer']): output(md.getitem(args['footer'],0)( | doc=args['footer'] if hasattr(self, doc): doc=getattr(self, doc) elif md.has_key(doc): doc=md.getitem(args['header'],0) else: doc=None if doc is not None: output(doc( | def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data, colspan, section, md, treeData, level=0, args=None): "Render a tree as a table" have_arg=args.has_key if level >= 0: tpUrl=self.tpURL() url = (url and ('%s/%s' % (url, tpUrl))) or tpUrl root_url = root_url or tpUrl treeData['tree-item-url']=url treeData['tree-level']=level treeData['tree-item-expanded']=0 exp=0 sub=None output=data.append script=md['SCRIPT_NAME'] try: items=getattr(self, args['branches'])() except: items=None if not items and have_arg('leaves'): items=1 if (args.has_key('sort')) and (items is not None) and (items != 1): # Faster/less mem in-place sort if type(items)==type(()): items=list(items) sort=args['sort'] size=range(len(items)) for i in size: v=items[i] k=getattr(v,sort) try: k=k() except: pass items[i]=(k,v) items.sort() for i in size: items[i]=items[i][1] diff.append(id) if substate is state: output('<TABLE CELLSPACING="0">\n') sub=substate[0] exp=items else: # Add prefix output('<TR>\n') # Add +/- icon if items: if level: if level > 3: output( '<TD COLSPAN="%s"></TD>' % (level-1)) elif level > 1: output('<TD></TD>' * (level-1)) output('<TD WIDTH="16"></TD>\n') output('<TD WIDTH="16" VALIGN="TOP">') for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break #################################### # Mostly inline encode_seq for speed s=compress(str(diff)) if len(s) > 57: s=encode_str(s) else: s=b2a_base64(s)[:-1] l=find(s,'=') if l >= 0: s=s[:l] s=translate(s, tplus) #################################### if exp: treeData['tree-item-expanded']=1 output('<A HREF="%s?tree-c=%s">' '<IMG SRC="%s/p_/mi" BORDER=0></A>' % (root_url,s, script)) else: output('<A HREF="%s?tree-e=%s">' '<IMG SRC="%s/p_/pl" BORDER=0></A>' % (root_url,s, script)) output('</TD>\n') else: if level > 2: output('<TD COLSPAN="%s"></TD>' % level) elif level > 0: output('<TD></TD>' * level) output('<TD WIDTH="16"></TD>\n') # add item text dataspan=colspan-level output('<TD%s%s VALIGN="TOP">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(section(self, md)) output('</TD>\n</TR>\n') if exp: level=level+1 dataspan=colspan-level if level > 3: h='<TD COLSPAN="%s"></TD>' % (level-1) elif level > 1: h='<TD></TD>' * (level-1) else: h='' if have_arg('header'): if md.has_key(args['header']): output(md.getitem(args['header'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) if items==1: # leaves treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['leaves'],0)( self,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) md._pop(1) elif have_arg('expand'): treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['expand'],0)(self,md)) md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, 'tpId'): id=item.tpId() elif hasattr(item, '_p_oid'): id=item._p_oid else: id=pyid(item) if len(sub)==1: sub.append([]) substate=sub[1] ids[id]=1 data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) if not sub[1]: del sub[1] ids=ids.has_key for i in range(len(substate)-1,-1): if not ids(substate[i][0]): del substate[i] if have_arg('footer'): if md.has_key(args['footer']): output(md.getitem(args['footer'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) del diff[-1] if not diff: output('</TABLE>\n') return data |
$Id: Publish.py,v 1.22 1996/10/25 19:34:27 jim Exp $""" | $Id: Publish.py,v 1.23 1996/10/28 22:13:45 jim Exp $""" | def taste(spam): "a favorable reviewer" return spam,'yum yum, I like ' + spam |
__version__='$Revision: 1.22 $'[11:-2] | __version__='$Revision: 1.23 $'[11:-2] | def taste(spam): "a favorable reviewer" return spam,'yum yum, I like ' + spam |
self.code[at:at]=rcode | self.code[at + 1:at + 1] = [self.code[at]] self.code[at + 1:at + 1] = rcode del self.code[at] | def insert_code(self, rcode, at = None): opn = self.opn # rcode is passed as a (callables, args) pair rcode = map(apply, rcode[0], rcode[1]) if at is None: at = opn self.code[at:at]=rcode self.opn = opn + len(rcode) return rcode |
result.append(r"fters") | def query(self, pattern): """ """ result = [] for x in self.lexicon.get(pattern): if self.globbing: result.append(self.lexicon._inverseLex[x]) else: result.append(pattern) |
|
LOG('UnTextIndex', PROBLEM, | LOG('UnTextIndex', ERROR, | def unindex_object(self, i, tt=type(()) ): """ carefully unindex document with integer id 'i' from the text index and do not fail if it does not exist """ index = self._index unindex = self._unindex val = unindex.get(i, None) if val is not None: for n in val: v = index.get(n, None) if type(v) is tt: del index[n] elif v is not None: try: del index[n][i] except (KeyError, IndexError, TypeError): LOG('UnTextIndex', PROBLEM, 'unindex_object tried to unindex nonexistent' ' document %s' % str(i)) del unindex[i] self._index = index self._unindex = unindex |
result[key] = positionsr | result[key] = score,positionsr | def near(self, x, distance = 1): '''\ near(rl, distance = 1) Returns a ResultList containing documents which contain''' result = self.__class__() for key, v in self.items(): try: value = x[key] except KeyError: value = None if value is None: continue positions = v[1] + value[1] positions.sort() positionsr = [] rel = pow(v[0] * value[0], 0.5) pl = positions[0] rl = -1 for i in range(1, len(positions)): p = positions[i] d = p - pl if d > 0 and d <= distance: if pl != rl: positionsr.append(pl) positionsr.append(p) rl = p pl = p if (len(positionsr)): result[key] = positionsr return result |
return self.__snd_request('UNLOCK', self.uri, headers, body) | return self.__snd_request('UNLOCK', self.uri, headers) | def unlock(self, token, **kw): """Remove the lock identified by token from the resource and all other resources included in the lock. If all resources which have been locked under the submitted lock token can not be unlocked the unlock method will fail.""" headers=self.__get_headers(kw) token='<opaquelocktoken:%s>' % str(token) headers['Lock-Token']=token return self.__snd_request('UNLOCK', self.uri, headers, body) |
r.data_record_score__ = 1 | r.data_record_score_ = 1 | def __getitem__(self, index, ttype=type(())): """ Returns instances of self._v_brains, or whatever is passed into self.useBrains. """ if type(index) is ttype: normalized_score, score, key = index r=self._v_result_class(self.data[key]).__of__(self.aq_parent) r.data_record_id_ = key r.data_record_score_ = score r.data_record_normalized_score_ = normalized_score else: r=self._v_result_class(self.data[index]).__of__(self.aq_parent) r.data_record_id_ = index r.data_record_score__ = 1 r.data_record_normalized_score_ = 1 return r |
return '%s&%s=%s' % (url, name, bid) | return '%s&%s=%s' % (url, name, bid) | def encodeUrl(self, url, create=1): """ encode a URL with the browser id as a postfixed query string element """ bid = self.getBrowserId(create) if bid is None: raise BrowserIdManagerErr, 'There is no current browser id.' name = self.getBrowserIdName() if '?' in url: return '%s&%s=%s' % (url, name, bid) else: return '%s?%s=%s' % (url, name, bid) |
def objectIds(self,t=None): | def objectIds(self, spec=None): | def objectIds(self,t=None): # Return a list of subobject ids |
if t is not None: if type(t)==type('s'): t=(t,) return filter(None, map(lambda x,v=t: (x['meta_type'] in v) and x['id'] or None, self._objects)) | if spec is not None: if type(spec)==type('s'): spec=[spec] set=[] for ob in self._objects: if ob['meta_type'] in spec: set.append(ob['id']) return set | def objectIds(self,t=None): # Return a list of subobject ids |
def objectValues(self,t=None): | def objectValues(self, spec=None): | def objectValues(self,t=None): # Return a list of the actual subobjects |
if t is not None: if type(t)==type('s'): t=(t,) return filter(None, map(lambda x,v=t,s=self: (x['meta_type'] in v) and getattr(s,x['id']) or None, self._objects)) | if spec is not None: if type(spec)==type('s'): spec=[spec] set=[] for ob in self._objects: if ob['meta_type'] in spec: set.append(getattr(self, ob['id'])) return set | def objectValues(self,t=None): # Return a list of the actual subobjects |
def objectItems(self,t=None): | def objectItems(self, spec=None): | def objectItems(self,t=None): # Return a list of (id, subobject) tuples |
if t is not None: if type(t)==type('s'): t=(t,) return filter(None, map(lambda x,v=t,s=self: (x['meta_type'] in v) and \ (x['id'],getattr(s,x['id'])) or None, self._objects)) | if spec is not None: if type(spec)==type('s'): spec=[spec] set=[] for ob in self._objects: if ob['meta_type'] in spec: set.append((ob['id'], getattr(self, ob['id']))) | def objectItems(self,t=None): # Return a list of (id, subobject) tuples |
CVS = os.path.normcase("CVS") | CVS_DIRS = [os.path.normcase("CVS"), os.path.normcase(".svn")] | def copyskel(sourcedir, targetdir, uid, gid, **replacements): """ This is an independent function because we'd like to import and call it from mkzopeinstance """ # Create the top of the instance: if not os.path.exists(targetdir): os.makedirs(targetdir) # This is fairly ugly. The chdir() makes path manipulation in the # walk() callback a little easier (less magical), so we'll live # with it. pwd = os.getcwd() os.chdir(sourcedir) try: try: os.path.walk(os.curdir, copydir, (targetdir, replacements, uid, gid)) finally: os.chdir(pwd) except (IOError, OSError), msg: print >>sys.stderr, msg sys.exit(1) |
if os.path.normcase(name) == CVS: | if os.path.normcase(name) in CVS_DIRS: | def copydir((targetdir, replacements, uid, gid), sourcedir, names): # Don't recurse into CVS directories: for name in names[:]: if os.path.normcase(name) == CVS: names.remove(name) elif os.path.isfile(os.path.join(sourcedir, name)): # Copy the file: sn, ext = os.path.splitext(name) if os.path.normcase(ext) == ".in": dst = os.path.join(targetdir, sourcedir, sn) if os.path.exists(dst): continue copyin(os.path.join(sourcedir, name), dst, replacements, uid, gid) if uid is not None: os.chown(dst, uid, gid) else: src = os.path.join(sourcedir, name) dst = os.path.join(targetdir, src) if os.path.exists(dst): continue shutil.copyfile(src, dst) shutil.copymode(src, dst) if uid is not None: os.chown(dst, uid, gid) else: # Directory: dn = os.path.join(targetdir, sourcedir, name) if not os.path.exists(dn): os.mkdir(dn) shutil.copymode(os.path.join(sourcedir, name), dn) if uid is not None: os.chown(dn, uid, gid) |
if k=='' or k in '().012FGIJKLMNTUVX]adeghjlpqrstu}': | if k=='' or k in '().012FGIJKLMNTUVXS]adeghjlpqrstu}': | def refuse_to_unpickle(self): raise pickle.UnpicklingError, 'Refused' |
elif k in [pickle.STRING]: pass | def refuse_to_unpickle(self): raise pickle.UnpicklingError, 'Refused' |
|
_should_fail('hello',0) | def _test(): _should_fail('hello',0) _should_succeed('hello') _should_succeed(1) _should_succeed(1L) _should_succeed(1.0) _should_succeed((1,2,3)) _should_succeed([1,2,3]) _should_succeed({1:2,3:4}) _should_fail(open) _should_fail(_junk_class) _should_fail(_junk_class()) |
|
manage_menu =HTMLFile('dtml/menu', globals()) | manage_menu =DTMLFile('dtml/menu', globals()) | def tabs_path_info(self, script, path, # Static vars quote=urllib.quote, ): out=[] while path[:1]=='/': path=path[1:] while path[-1:]=='/': path=path[:-1] while script[:1]=='/': script=script[1:] while script[-1:]=='/': script=script[:-1] path=split(path,'/')[:-1] if script: path=[script]+path if not path: return '' script='' last=path[-1] del path[-1] for p in path: script="%s/%s" % (script, quote(p)) out.append('<a href="%s/manage_workspace">%s</a>' % (script, p)) out.append(last) return join(out, '/') |
manage_zmi_prefs=HTMLFile('dtml/manage_zmi_prefs', globals()) | manage_zmi_prefs=DTMLFile('dtml/manage_zmi_prefs', globals()) | def manage_zmi_logout(self, REQUEST, RESPONSE): """Logout current user""" p = getattr(REQUEST, '_logout_path', None) if p is not None: return apply(self.restrictedTraverse(p)) |
else: hide_tracebacks=None | else: hide_tracebacks=1 | def get_module_info(module_name, modules={}, acquire=_l.acquire, release=_l.release, ): if modules.has_key(module_name): return modules[module_name] if module_name[-4:]=='.cgi': module_name=module_name[:-4] acquire() tb=None try: try: module=__import__(module_name, globals(), globals(), ('__doc__',)) realm=module_name # Let the app specify a realm if hasattr(module,'__bobo_realm__'): realm=module.__bobo_realm__ elif os.environ.has_key('BOBO_REALM'): realm=request.environ['BOBO_REALM'] else: realm=module_name # Check for debug mode if hasattr(module,'__bobo_debug_mode__'): debug_mode=not not module.__bobo_debug_mode__ elif os.environ.has_key('BOBO_DEBUG_MODE'): debug_mode=lower(os.environ['BOBO_DEBUG_MODE']) if debug_mode=='y' or debug_mode=='yes': debug_mode=1 else: try: debug_mode=atoi(debug_mode) except: debug_mode=None else: debug_mode=None # Check whether tracebacks should be hidden: if hasattr(module,'__bobo_hide_tracebacks__'): hide_tracebacks=not not module.__bobo_hide_tracebacks__ elif os.environ.has_key('BOBO_HIDE_TRACEBACKS'): hide_tracebacks=lower(os.environ['BOBO_HIDE_TRACEBACKS']) if hide_tracebacks=='y' or hide_tracebacks=='yes': hide_tracebacks=1 else: try: hide_tracebacks=atoi(hide_tracebacks) except: hide_tracebacks=None else: hide_tracebacks=None # Reset response handling of tracebacks, if necessary: if debug_mode or not hide_tracebacks: def hack_response(): import Response Response._tbopen = '<PRE>' Response._tbclose = '</PRE>' hack_response() if hasattr(module,'__bobo_before__'): bobo_before=module.__bobo_before__ else: bobo_before=None if hasattr(module,'__bobo_after__'): bobo_after=module.__bobo_after__ else: bobo_after=None # Get request data from outermost environment: if hasattr(module,'__request_data__'): request_params=module.__request_data__ else: request_params=None # Get initial group data: inherited_groups=[] if hasattr(module,'__allow_groups__'): groups=module.__allow_groups__ inherited_groups.append(groups) else: groups=None web_objects=None roles=UNSPECIFIED_ROLES if hasattr(module,'bobo_application'): object=module.bobo_application if hasattr(object,'__allow_groups__'): groups=object.__allow_groups__ inherited_groups.append(groups) else: groups=None if hasattr(object,'__roles__'): roles=object.__roles__ else: if hasattr(module,'web_objects'): web_objects=module.web_objects object=web_objects else: object=module published=web_objects try: doc=module.__doc__ except: if web_objects is not None: doc=' ' else: doc=None info= (bobo_before, bobo_after, request_params, inherited_groups, groups, roles, object, doc, published, realm, module_name, debug_mode) modules[module_name]=modules[module_name+'.cgi']=info return info except: if hasattr(sys, 'exc_info'): t,v,tb=sys.exc_info() else: t, v, tb = sys.exc_type, sys.exc_value, sys.exc_traceback v=str(v) raise ImportError, (t, v), tb finally: tb=None release() |
self.pt_edit(REQUEST.get('BODY', '')) | text = REQUEST.get('BODY', '') content_type = guess_type('', text) self.pt_edit(text, content_type, self.output_encoding) | def PUT(self, REQUEST, RESPONSE): """ Handle HTTP PUT requests """ self.dav__init(REQUEST, RESPONSE) self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1) ## XXX this should be unicode or we must pass an encoding self.pt_edit(REQUEST.get('BODY', '')) RESPONSE.setStatus(204) return RESPONSE |
self.REQUEST.RESPONSE.setHeader('Content-Type', self.content_type) return self.read() | return self.pt_render() | def manage_FTPget(self): "Get source for FTP download" self.REQUEST.RESPONSE.setHeader('Content-Type', self.content_type) return self.read() |
for sub in ast[2][2][1:]: | for sub in ast[i][2][1:]: | def item_munge(ast, i): # Munge an item access into a function call name=ast[i][2][1] args=[arglist] append=args.append a=(factor, (power, (atom, (NAME, '_vars')))) a=(argument, (test, (and_test, (not_test, (comparison, (expr, (xor_expr, (and_expr, (shift_expr, (arith_expr, (term, a))))))))))) append(a) append([COMMA,',']) a=ast[:i] a=(argument, (test, (and_test, (not_test, (comparison, (expr, (xor_expr, (and_expr, (shift_expr, (arith_expr, (term, (factor, a)))))))))))) append(a) append([COMMA,',']) for sub in ast[2][2][1:]: if sub[0]==COMMA: append(sub) else: if len(sub) != 2: raise ParseError, 'Invalid slice in subscript' append([argument, sub[1]]) return [power, [atom, [NAME, '__guarded_getitem__']], [trailer, [LPAR, '('], args, [RPAR, ')'], ] ] |
[trailer, [LPAR, '('], args, [RPAR, ')'], ] | [trailer, [LPAR, '('], args, [RPAR, ')']], | def dot_munge(ast, i): # Munge an attribute access into a function call name=ast[i][2][1] args=[arglist] append=args.append a=(factor, (power, (atom, (NAME, '_vars')))) a=(argument, (test, (and_test, (not_test, (comparison, (expr, (xor_expr, (and_expr, (shift_expr, (arith_expr, (term, a))))))))))) append(a) append([COMMA,',']) a=ast[:i] a=(argument, (test, (and_test, (not_test, (comparison, (expr, (xor_expr, (and_expr, (shift_expr, (arith_expr, (term, (factor, a)))))))))))) append(a) append([COMMA,',']) a=(factor, (power, (atom, (STRING, `name`)))) a=(argument, (test, (and_test, (not_test, (comparison, (expr, (xor_expr, (and_expr, (shift_expr, (arith_expr, (term, a))))))))))) append(a) return [power, [atom, [NAME, '__guarded_getattr__']], [trailer, [LPAR, '('], args, [RPAR, ')'], ] ] |
if not hasattr(Folder, name): setattr(Folder, name, method) | if not hasattr(Folder.Folder, name): setattr(Folder.Folder, name, method) | def install_product(app, product_dir, product_name, meta_types, folder_permissions, raise_exc=0, log_exc=1): path_join=os.path.join isdir=os.path.isdir exists=os.path.exists DictType=type({}) global_dict=globals() silly=('__doc__',) if 1: # Preserve indentation for diff :-) package_dir=path_join(product_dir, product_name) __traceback_info__=product_name if not isdir(package_dir): return if not exists(path_join(package_dir, '__init__.py')): if not exists(path_join(package_dir, '__init__.pyc')): return try: product=__import__("Products.%s" % product_name, global_dict, global_dict, silly) # Install items into the misc_ namespace, used by products # and the framework itself to store common static resources # like icon images. misc_=pgetattr(product, 'misc_', {}) if misc_: if type(misc_) is DictType: misc_=Misc_(product_name, misc_) Application.misc_.__dict__[product_name]=misc_ # Here we create a ProductContext object which contains # information about the product and provides an interface # for registering things like classes and help topics that # should be associated with that product. Products are # expected to implement a method named 'initialize' in # their __init__.py that takes the ProductContext as an # argument. productObject=App.Product.initializeProduct( product, product_name, package_dir, app) context=ProductContext(productObject, app, product) # Look for an 'initialize' method in the product. If it does # not exist, then this is an old product that has never been # updated. In that case, we will analyze the product and # build up enough information to do initialization manually. initmethod=pgetattr(product, 'initialize', None) if initmethod is not None: initmethod(context) # Support old-style product metadata. Older products may # define attributes to name their permissions, meta_types, # constructors, etc. permissions={} new_permissions={} for p in pgetattr(product, '__ac_permissions__', ()): permission, names, default = ( tuple(p)+('Manager',))[:3] if names: for name in names: permissions[name]=permission elif not folder_permissions.has_key(permission): new_permissions[permission]=() for meta_type in pgetattr(product, 'meta_types', ()): # Modern product initialization via a ProductContext # adds 'product' and 'permission' keys to the meta_type # mapping. We have to add these here for old products. pname=permissions.get(meta_type['action'], None) if pname is not None: meta_type['permission']=pname meta_type['product']=productObject.id meta_types.append(meta_type) for name,method in pgetattr( product, 'methods', {}).items(): if not hasattr(Folder, name): setattr(Folder, name, method) if name[-9:]!='__roles__': # not Just setting roles if (permissions.has_key(name) and not folder_permissions.has_key( permissions[name])): permission=permissions[name] if new_permissions.has_key(permission): new_permissions[permission].append(name) else: new_permissions[permission]=[name] if new_permissions: new_permissions=new_permissions.items() for permission, names in new_permissions: folder_permissions[permission]=names new_permissions.sort() Folder.Folder.__dict__['__ac_permissions__']=tuple( list(Folder.Folder.__ac_permissions__)+new_permissions) if (os.environ.get('ZEO_CLIENT') and not os.environ.get('FORCE_PRODUCT_LOAD')): # we don't want to install products from clients # (unless FORCE_PRODUCT_LOAD is defined). get_transaction().abort() else: get_transaction().note('Installed product '+product_name) get_transaction().commit() except: if log_exc: LOG('Zope',ERROR,'Couldn\'t install %s' % product_name, error=sys.exc_info()) get_transaction().abort() if raise_exc: raise |
tpUrl=self.tpURL() url = (url and ('%s/%s' % (url, tpUrl))) or tpUrl root_url = root_url or tpUrl | if level >= 0: tpUrl=self.tpURL() url = (url and ('%s/%s' % (url, tpUrl))) or tpUrl root_url = root_url or tpUrl | def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data, colspan, section, md, treeData, level=0, args=None): "Render a tree as a table" have_arg=args.has_key tpUrl=self.tpURL() url = (url and ('%s/%s' % (url, tpUrl))) or tpUrl root_url = root_url or tpUrl treeData['tree-item-url']=url treeData['tree-level']=level treeData['tree-item-expanded']=0 exp=0 sub=None output=data.append try: items=getattr(self, args['branches'])() except: items=None if not items and have_arg('leaves'): items=1 if (args.has_key('sort')) and (items is not None) and (items != 1): # Faster/less mem in-place sort sort=args['sort'] size=range(len(items)) for i in size: v=items[i] k=getattr(v,sort) try: k=k() except: pass items[i]=(k,v) items.sort() for i in size: items[i]=items[i][1] diff.append(id) if substate is state: output('<TABLE CELLSPACING="0">\n') sub=substate[0] exp=items else: # Add prefix output('<TR>\n') # Add +/- icon if items: if level: if level > 3: output( '<TD COLSPAN="%s"></TD>' % (level-1)) elif level > 1: output('<TD></TD>' * (level-1)) output('<TD WIDTH="16"></TD>\n') output('<TD WIDTH="16" VALIGN="TOP">') for i in range(len(substate)): sub=substate[i] if sub[0]==id: exp=i+1 break #################################### # Mostly inline encode_seq for speed s=compress(str(diff)) if len(s) > 57: s=encode_str(s) else: s=b2a_base64(s)[:-1] l=find(s,'=') if l >= 0: s=s[:l] #################################### if exp: treeData['tree-item-expanded']=1 output('<A HREF="%s?tree-c=%s">%s</A>' % (root_url,s, icoMinus)) else: output('<A HREF="%s?tree-e=%s">%s</A>' % (root_url,s, icoPlus)) output('</TD>\n') else: if level > 2: output('<TD COLSPAN="%s"></TD>' % level) elif level > 0: output('<TD></TD>' * level) output('<TD WIDTH="16"></TD>\n') # add item text dataspan=colspan-level output('<TD%s%s VALIGN="TOP">' % ((dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''), (have_arg('nowrap') and args['nowrap'] and ' NOWRAP' or '')) ) output(section(self, md)) output('</TD>\n</TR>\n') if exp: level=level+1 dataspan=colspan-level if level > 3: h='<TD COLSPAN="%s"></TD>' % (level-1) elif level > 1: h='<TD></TD>' * (level-1) else: h='' if have_arg('header'): if md.has_key(args['header']): output(md.getitem(args['header'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) if items==1: # leaves treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['leaves'],0)( self,md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) md._pop(1) elif have_arg('expand'): treeData['-tree-substate-']=sub treeData['tree-level']=level md._push(treeData) output(md.getitem(args['expand'],0)(self,md)) md._pop(1) else: __traceback_info__=sub, args, state, substate ids={} for item in items: if hasattr(item, 'tpId'): id=item.tpId() elif hasattr(item, '_p_oid'): id=item._p_oid else: id=pyid(item) if len(sub)==1: sub.append([]) substate=sub[1] ids[id]=1 data=tpRenderTABLE( item,id,root_url,url,state,substate,diff,data, colspan, section, md, treeData, level, args) if not sub[1]: del sub[1] ids=ids.has_key for i in range(len(substate)-1,-1): if not ids(substate[i][0]): del substate[i] if have_arg('footer'): if md.has_key(args['footer']): output(md.getitem(args['footer'],0)( self, md, standard_html_header=( '<TR>%s<TD WIDTH="16"></TD>' '<TD%s VALIGN="TOP">' % (h, (dataspan > 1 and (' COLSPAN="%s"' % dataspan) or ''))), standard_html_footer='</TD></TR>', )) del diff[-1] if not diff: output('</TABLE>\n') return data |
header_re=regex.compile( | header_re=ts_regex.compile( | def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html |
space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), | space_re=ts_regex.compile('\([ \t]+\)'), name_re=ts_regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), | def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html |
if header_re.match(html) < 0: | ts_results = header_re.match_group(html, (1,3)) if not ts_results: | def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html |
headers, html = header_re.group(1,3) | headers, html = ts_results[1] | def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html |
elif space_re.match(headers[i]) >= 0: | continue ts_results = space_re.match_group(headers[i], (1,)) if ts_results: | def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html |
headers[i][len(space_re.group(1)):]) | headers[i][len(ts_results[1]):]) | def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html |
else: i=i+1 | continue i=i+1 | def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html |
if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) | ts_results = name_re.match_group(headers[i], (1,2)) if ts_results: k, v = ts_results[1] | def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\n\0\- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0\- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0\- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html |
for key, value in default_stop_words: | for key, value in default_stop_words.items(): | def __init__(self, index_dictionary = None, synstop = None): 'Create an inverted index' if (synstop is None): synstop = {} for key, value in default_stop_words: synstop[key] = value self.synstop = synstop |
try: v,expires,domain,path,secure=self.cookies[name] except: v,expires,domain,path,secure='','','','','' self.cookies[name]=v+value,expires,domain,path,secure | self.setCookie(name,value) | def appendCookie(self, name, value): |
self.cookies[name]='deleted','01-Jan-96 11:11:11 GMT','','','' def setCookie(self,name, value=None, expires=None, domain=None, path=None, secure=None): | self.setCookie(name,'deleted', max_age=0) def setCookie(self,name,value,**kw): | def expireCookie(self, name): |
except: cookie=('')*5 def f(a,b): if b is not None: return b return a self.cookies[name]=tuple(map(f,cookie, (value,expires,domain,path,secure) ) ) | except: cookie=self.cookies[name]={} for k, v in kw.items(): cookie[k]=v cookie['value']=value | def setCookie(self,name, value=None, |
for name in self.cookies.keys(): value,expires,domain,path,secure=self.cookies[name] cookie='set-cookie: %s=%s' % (name,value) if expires: cookie = "%s; expires=%s" % (cookie,expires) if domain: cookie = "%s; domain=%s" % (cookie,domain) if path: cookie = "%s; path=%s" % (cookie,path) if secure: cookie = cookie+'; secure' | for name, attrs in self.cookies.items(): if attrs.has_key('expires'): cookie='set-cookie: %s="%s"' % (name,attrs['value']) else: cookie=('set-cookie: %s="%s"; Version="1"' % (name,attrs['value'])) for name, v in attrs.items(): if name=='expires': cookie = '%s; Expires="%s"' % (cookie,v) elif name=='domain': cookie = '%s; Domain="%s"' % (cookie,v) elif name=='path': cookie = '%s; Path=%s' % (cookie,v) elif name=='max_age': cookie = '%s; Max-Age="%s"' % (cookie,v) elif name=='comment': cookie = '%s; Comment="%s"' % (cookie,v) elif name=='secure': cookie = '%s; Secure' % cookie elif name!='value': raise ValueError, ( 'Invalid cookie attribute, %s' % name) | def _cookie_list(self): |
REQUEST['RESPONSE'].setCookie('cp_', 'deleted', | REQUEST['RESPONSE'].setCookie('__cp', 'deleted', | def manage_pasteObjects(self, cb_copy_data=None, REQUEST=None): """Paste previously copied objects into the current object. If calling manage_pasteObjects from python code, pass the result of a previous call to manage_cutObjects or manage_copyObjects as the first argument.""" cp=None if cb_copy_data is not None: cp=cb_copy_data else: if REQUEST and REQUEST.has_key('__cp'): cp=REQUEST['__cp'] if cp is None: raise CopyError, eNoData try: cp=_cb_decode(cp) except: raise CopyError, eInvalid |
tnamelast='' | tnamelast=None | def _read_and_report(file, rpt=None, fromEnd=0, both=0, n=99999999, show=0): """\ Read a file's index up to the given time. """ first=1 seek=file.seek read=file.read unpack=struct.unpack split=string.split join=string.join find=string.find seek(0,2) file_size=file.tell() gmtime=time.gmtime if fromEnd: pos=file_size else: pos=newpos=len(packed_version) tlast=0 err=0 tnamelast='' while 1: if fromEnd: seek(pos-4) l=unpack(">i", read(4))[0] if l==0: b=pos p=pos-4 while l==0: p=p-4 seek(p) l=unpack(">i", read(4))[0] pos=p+4 error("nulls skipped from %s to %s" % (pos,b)) p=pos-l if p < 0: error('Corrupted data before %s' % pos) if show > 0: p=pos-show if p < 0: p=0 seek(p) p=read(pos-p) else: p='' error(p,1) pos=p else: pos=newpos seek(pos) h=read(24) # 24=header_size if not h: break if len(h) != 24: break oid,prev,start,tlen,plen=unpack(">iidii",h) if (prev < 0 or prev >= pos or start < tlast or plen > tlen or plen < 0 or oid < -999): __traceback_info__=pos, oid,prev,start,tlen,plen error('Corrupted data record at %s' % pos) if show > 0: error(read(show)) err=1 break newpos=pos+tlen if newpos > file_size: error('Truncated data record at %s' % pos) if show > 0: error(read(show)) err=1 break seek(newpos-4) if read(4) != h[16:20]: __traceback_info__=pos, oid,prev,start,tlen,plen error('Corrupted data record at %s' % pos) if show > 0: seek(pos+24) error(read(show)) err=1 break tlast=start-100 if rpt is None: continue n=n-1 if n < 1: break seek(pos+24) if plen > 0: p=read(plen) if p[-1:] != '.': error('Corrupted pickle at %s %s %s' % (pos,plen,len(p))) if show > 0: seek(pos+24) error(read(show)) err=1 break else: p='' t=split(read(tlen-plen-28),'\t') tname, user = (t+[''])[:2] t=join(t[2:],'\t') start,f=divmod(start,1) y,m,d,h,mn,s=gmtime(start)[:6] s=s+f start="%.4d-%.2d-%.2d %.2d:%.2d:%.3f" % (y,m,d,h,mn,s) rpt(pos,oid,start,tname,user,t,p,first,tname!=tnamelast) first=0 tnamelast=tname if err and both and not fromEnd: _read_and_report(file, rpt, 1, 0, n, show) rpt(None, None, None, None, None, None, None, None, None) |
if __name__=='__main__': | def main(argv): | def xmls(pos, oid, start, tname, user, t, p, first, newtrans): write=sys.stdout.write if first: write('<?xml version="1.0">\n<transactions>\n') if pos is None: write('</transaction>\n') write('</transactioons>\n') return if newtrans: if pos > 9: write('</transaction>\n') write('<transaction name="%s" user="%s">\n%s\n' % (tname, user,t)) |
opts, args = getopt.getopt(sys.argv[1:],'r:ebl:s:f:p:') | opts, args = getopt.getopt(argv,'r:ebl:s:f:p:') | def xmls(pos, oid, start, tname, user, t, p, first, newtrans): write=sys.stdout.write if first: write('<?xml version="1.0">\n<transactions>\n') if pos is None: write('</transaction>\n') write('</transactioons>\n') return if newtrans: if pos > 9: write('</transaction>\n') write('<transaction name="%s" user="%s">\n%s\n' % (tname, user,t)) |
print s | def doc_underline(self, s, expr=re.compile("_([%s0-9\s\.,\?\/]+)_" % letters).search): |
|
print "got it" | def doc_underline(self, s, expr=re.compile("_([%s0-9\s\.,\?\/]+)_" % letters).search): |
|
_DQUOTEDTEXT = r'("[%s0-9\n%s]+")' % (letters,punctuation) _URL_AND_PUNC = r'([%s0-9_\@%s]+)' % (letters,punctuation) | _DQUOTEDTEXT = r'("[%s0-9\n%s]+")' % (letters,punctuations) _URL_AND_PUNC = r'([%s0-9_\@%s]+)' % (letters,punctuations) | def doc_strong(self, s, expr = re.compile(r'\s*\*\*([ \n%s0-9]+)\*\*' % lettpunc).search ): |
self.getFunction() | self.getFunction(1) | def manage_edit(self, title, module, function, REQUEST=None): |
def getFunction(self): | def getFunction(self, check=0): | def getFunction(self): |
if self.func_defaults != ff.func_defaults: self.func_defaults = ff.func_defaults func_code=FuncCode(ff,f is not ff) if func_code != self.func_code: self.func_code=func_code | func_code=FuncCode(ff,f is not ff) if func_code != self.func_code: self.func_code=func_code | def getFunction(self): |
(othr.co_argcount, othr.co_varnames)) | (other.co_argcount, other.co_varnames)) | def __cmp__(self,other): |
self.handlers = [] for tname,nargs,nsection in blocks[1:]: for errname in string.split(nargs): self.handlers.append((errname,nsection.blocks)) if string.strip(nargs)=='': self.handlers.append(('',nsection.blocks)) | if len(blocks) == 2 and blocks[1][0] == 'finally': self.finallyBlock = blocks[1][2].blocks else: self.handlers = [] defaultHandlerFound = 0 for tname,nargs,nsection in blocks[1:]: if tname == 'else': if not self.elseBlock is None: raise ParseError, ( 'No more than one else block is allowed', self.name) self.elseBlock = nsection.blocks elif tname == 'finally': raise ParseError, ( 'A try..finally combination cannot contain ' 'any other else, except or finally blocks', self.name) else: if not self.elseBlock is None: raise ParseError, ( 'The else block should be the last block ' 'in a try tag', self.name) for errname in string.split(nargs): self.handlers.append((errname,nsection.blocks)) if string.strip(nargs)=='': if defaultHandlerFound: raise ParseError, ( 'Only one default exception handler ' 'is allowed', self.name) else: defaultHandlerFound = 1 self.handlers.append(('',nsection.blocks)) | def __init__(self, blocks): tname, args, section = blocks[0] |
return render_blocks(self.section, md) | result = render_blocks(self.section, md) | def render(self, md): # first we try to render the first block try: return render_blocks(self.section, md) except DTReturn: raise except: # but an error occurs.. save the info. t,v = sys.exc_info()[:2] if type(t)==type(''): errname = t else: errname = t.__name__ |
else: if (self.elseBlock is None): return result else: return result + render_blocks(self.elseBlock, md) def render_try_finally(self, md): result = '' try: result = render_blocks(self.section, md) finally: result = result + render_blocks(self.finallyBlock, md) return result | def render(self, md): # first we try to render the first block try: return render_blocks(self.section, md) except DTReturn: raise except: # but an error occurs.. save the info. t,v = sys.exc_info()[:2] if type(t)==type(''): errname = t else: errname = t.__name__ |
|
(item.filename is not None or 'content-type' in map(lower, item.headers.keys()))): | (item.filename is not None )): | def processInputs( self, # "static" variables that we want to be local for speed SEQUENCE=1, DEFAULT=2, RECORD=4, RECORDS=8, REC=12, # RECORD|RECORDS EMPTY=16, CONVERTED=32, hasattr=hasattr, getattr=getattr, setattr=setattr, search_type=regex.compile(':[a-zA-Z][a-zA-Z0-9_]+$').search, rfind=string.rfind, ): """Process request inputs |
fields=self._class(fields, self._parent) | parent=self._parent fields=self._class(fields, parent) | def __getitem__(self,index): |
return fields | if parent is None: return fields return fields.__of__(parent) | def __getitem__(self,index): |
ob=self._p_jar.importFile(file) | connection=self._p_jar obj=self while connection is None: obj=obj.aq_parent connection=obj._p_jar ob=connection.importFile(file) | def manage_importObject(self, file, REQUEST=None): """Import an object from a file""" dirname, file=os.path.split(file) if dirname: raise 'Bad Request', 'Invalid file name %s' % file file=os.path.join(INSTANCE_HOME, 'import', file) if not os.path.exists(file): raise 'Bad Request', 'File does not exist: %s' % file ob=self._p_jar.importFile(file) if REQUEST: self._verifyObjectPaste(ob, REQUEST) id=ob.id if hasattr(id, 'im_func'): id=id() self._setObject(id, ob) if REQUEST is not None: return MessageDialog( title='Object imported', message='<EM>%s</EM> sucessfully imported' % id, action='manage_main' ) |
if isop(q[i]): q[i] = operator_dict[q[i]] | if type(q[i]) is not ListType and isop(q[i]): q[i] = operator_dict[q[i]] | def parse2(q, default_operator, operator_dict = {AndNot: AndNot, And: And, Or: Or, Near: Near}, ListType=type([]), ): '''Find operators and operands''' i = 0 isop=operator_dict.has_key while (i < len(q)): if (type(q[i]) is ListType): q[i] = parse2(q[i], default_operator) # every other item, starting with the first, should be an operand if ((i % 2) != 0): # This word should be an operator; if it is not, splice in # the default operator. if isop(q[i]): q[i] = operator_dict[q[i]] else: q[i : i] = [ default_operator ] i = i + 1 return q |
REQUEST.RESPONSE.notFoundError("%s\n%s" % (name, method)) | try: REQUEST.RESPONSE.notFoundError("%s\n%s" % (name, method)) except AttributeError: raise KeyError, name | def __bobo_traverse__(self, REQUEST, name=None): |
self._init() | self._index=BTree() | def clear(self): |
ts=os.stat(self.filepath()) if not hasattr(self, '_v_last_read') or \ (ts != self._v_last_read): | ts=os.stat(self.filepath())[stat.ST_MTIME] if (not hasattr(self, '_v_last_read') or (ts != self._v_last_read)): | def __call__(self, *args, **kw): """Call an ExternalMethod |
class Foo(Acquisition.Implicit): pass | class DummyAqImplicit(Acquisition.Implicit): pass class DummyPersistent(Persistent): pass | def _delDB(): transaction.abort() del stuff['db'] |
def testSubcommit(self): sd = self.app.session_data_manager.getSessionData() sd.set('foo', 'bar') | def testSubcommitAssignsPJar(self): sd = self.app.session_data_manager.getSessionData() dummy = DummyPersistent() sd.set('dp', dummy) self.failUnless(sd['dp']._p_jar is None) | def testSubcommit(self): sd = self.app.session_data_manager.getSessionData() sd.set('foo', 'bar') # TODO: this is used to test that transaction.commit(1) returned # None, but transaction.commit(whatever) always returns None (unless # there's an exception). What is this really trying to test? transaction.savepoint(optimistic=True) |
a = Foo() b = Foo() | a = DummyAqImplicit() b = DummyAqImplicit() | def testAqWrappedObjectsFail(self): a = Foo() b = Foo() aq_wrapped = a.__of__(b) sd = self.app.session_data_manager.getSessionData() sd.set('foo', aq_wrapped) self.assertRaises(TypeError, transaction.commit) |
that interacts correctly with objects requiring.""" | that interacts correctly with objects providing OFS.interfaces.ITraversable. """ | def boboTraverseAwareSimpleTraverse(object, path_items, econtext): """A slightly modified version of zope.tales.expressions.simpleTraverse that interacts correctly with objects requiring.""" request = getattr(econtext, 'request', None) path_items = list(path_items) path_items.reverse() while path_items: name = path_items.pop() if ITraversable.providedBy(object): try: object = object.restrictedTraverse(name) except (NotFound, Unauthorized), e: # OFS.Traversable.restrictedTraverse spits out # NotFound or Unauthorized (the Zope 2 versions) which # Zope 3's ZPT implementation obviously doesn't know # as exceptions indicating failed traversal. Perhaps # the Zope 2's versions should be replaced with their # Zope 3 equivalent at some point. For the time # being, however, we simply convert them into # LookupErrors: raise LookupError(*e.args) else: object = traversePathElement(object, name, path_items, request=request) return object |
'import Zope2; app=Zope2.app();' 'app.acl_users._doAddUser(\'%s\', \'%s\', [\'Manager\'], []);' 'transaction.commit()' | 'import Zope2; ' 'app = Zope2.app(); ' 'app.acl_users._doAddUser(\'%s\', \'%s\', [\'Manager\'], []); ' 'import transaction; ' 'transaction.commit(); ' | def do_adduser(self, arg): try: name, password = arg.split() except: print "usage: adduser <name> <password>" return cmdline = self.get_startup_cmd( self.options.python , 'import Zope2; app=Zope2.app();' 'app.acl_users._doAddUser(\'%s\', \'%s\', [\'Manager\'], []);' 'transaction.commit()' ) % (name, password) os.system(cmdline) |
result = self._lexicon.get(pattern, ()) | result = self._lexicon.get(pattern, None) if result is None: return () | def get(self, pattern): """ Query the lexicon for words matching a pattern.""" wc_set = [self.multi_wc, self.single_wc] |
if object.aq_inContextOf(context, 1): return 1 | return object.aq_inContextOf(context, 1) | def _check_context(self, object): # Check that 'object' exists in the acquisition context of # the parent of the acl_users object containing this user, # to prevent "stealing" access through acquisition tricks. # Return true if in context, false if not or if context # cannot be determined (object is not wrapped). parent = getattr(self, 'aq_parent', None) context = getattr(parent, 'aq_parent', None) if context is not None: if object is None: return 1 if not hasattr(object, 'aq_inContextOf'): if hasattr(object, 'im_self'): # This is a method. Grab its self. object=object.im_self if not hasattr(object, 'aq_inContextOf'): # Object is not wrapped, so return false. return 0 if object.aq_inContextOf(context, 1): return 1 # This is lame, but required to keep existing behavior. return 1 |
elif kw.kas_key('sort_order'): | elif kw.has_key('sort_order'): | def searchResults(self, REQUEST=None, used=None, query_map={ type(regex.compile('')): Query.Regex, type([]): orify, type(''): Query.String, }, **kw): |
if not xhas(id): result[id] = xdict[id]+score | if not xhas(id): result[id] = score | def and_not(self, x): result = {} dict = self._dict xdict = x._dict xhas = xdict.has_key for id, score in dict.items(): if not xhas(id): result[id] = xdict[id]+score return self.__class__(result, self._words, self._index) |
parents=[] | request['PARENTS']=parents=[] | def publish(self, module_name, after_list, published='web_objects', |
else: if (entry_name=='manage' or entry_name[:7]=='manage_'): roles='manage', | def publish(self, module_name, after_list, published='web_objects', |
|
parents.append(object) | def publish(self, module_name, after_list, published='web_objects', |
|
for i in range(last_parent_index): if hasattr(parents[i],'__allow_groups__'): groups=parents[i].__allow_groups__ else: continue | if hasattr(object, '__allow_groups__'): groups=object.__allow_groups__ inext=0 else: inext=None for i in range(last_parent_index): if hasattr(parents[i],'__allow_groups__'): groups=parents[i].__allow_groups__ inext=i+1 break if inext is not None: i=inext | def publish(self, module_name, after_list, published='web_objects', |
if groups is None: break auth=self.HTTP_AUTHORIZATION | if groups is None: roles=None auth='' | def publish(self, module_name, after_list, published='web_objects', |
break | def publish(self, module_name, after_list, published='web_objects', |
|
del parents[0] | def publish(self, module_name, after_list, published='web_objects', |
|
if parents: selfarg=parents[0] for i in range(len(parents)): parent=parents[i] if hasattr(parent,'aq_self'): p=parent.aq_self parents[i]=p request['PARENTS']=parents | def publish(self, module_name, after_list, published='web_objects', |
|
if argument_name=='self': args.append(selfarg) elif name_index < nrequired: self.badRequestError(argument_name) else: args.append(defaults[name_index-nrequired]) else: args.append(v) if debug: result=self.call_object(object,tuple(args)) else: result=apply(object,tuple(args)) | if argument_name=='self': args.append(parents[0]) elif name_index < nrequired: self.badRequestError(argument_name) else: args.append(defaults[name_index-nrequired]) else: args.append(v) args=tuple(args) if debug: result=self.call_object(object,args) else: result=apply(object,args) | def publish(self, module_name, after_list, published='web_objects', |
str(self,'other'),str(self,'environ')) | str(self,'form'),str(self,'environ')) | def str(self,name): dict=getattr(self,name) return "%s:\n\t%s\n\n" % ( name, join( map(lambda k, d=dict: "%s: %s" % (k, `d[k]`), dict.keys()), "\n\t" ) ) |
if lower(HTTP_AUTHORIZATION[:6]) != 'basic ': return None | if lower(HTTP_AUTHORIZATION[:6]) != 'basic ': if roles is None: return '' return None | def old_validation(groups, HTTP_AUTHORIZATION, roles=UNSPECIFIED_ROLES): global base64 if base64 is None: import base64 if lower(HTTP_AUTHORIZATION[:6]) != 'basic ': return None [name,password] = string.splitfields( base64.decodestring( split(HTTP_AUTHORIZATION)[-1]), ':') if roles is None: return name keys=None try: keys=groups.keys except: try: groups=groups() # Maybe it was a method defining a group keys=groups.keys except: pass if keys is not None: # OK, we have a named group, so apply the roles to the named # group. if roles is UNSPECIFIED_ROLES: roles=keys() g=[] for role in roles: if groups.has_key(role): g.append(groups[role]) groups=g for d in groups: if d.has_key(name) and d[name]==password: return name if keys is None: # Not a named group, so don't go further raise 'Forbidden', ( """<strong>You are not authorized to access this resource""") return None |
if find('\\') < 0 or (find('\\t') < 0 and find('\\n') < 0): return s | if find(s,'\\') < 0 or (find(s,'\\t') < 0 and find(s,'\\n') < 0): return s | def parse_text(s): if find('\\') < 0 or (find('\\t') < 0 and find('\\n') < 0): return s r=[] for x in split(s,'\\\\'): x=join(split(x,'\\n'),'\n') r.append(join(split(x,'\\t'),'\t')) return join(r,'\\') |
except: doc=getattr(subobject, entry_name+'__doc__') | except: doc=getattr(object, entry_name+'__doc__') | def publish(self, module_name, after_list, published='web_objects', |
if len(e) > 2: | if len(e) >= 2: | def handler(self, conn): from string import split, join, atoi hdr = conn.recv(10) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.