bugged
stringlengths 4
228k
| fixed
stringlengths 0
96.3M
| __index_level_0__
int64 0
481k
|
|---|---|---|
def __init__(self, options, args, test): # The known list of tests. # Recognise the original abbreviations as well as full executable names. self._test_list = { "base": self.TestBase, "base_unittests": self.TestBase, "browser": self.TestBrowser, "browser_tests": self.TestBrowser, "googleurl": self.TestGURL, "googleurl_unittests": self.TestGURL, "ipc": self.TestIpc, "ipc_tests": self.TestIpc, "layout": self.TestLayout, "layout_tests": self.TestLayout, "media": self.TestMedia, "media_unittests": self.TestMedia, "net": self.TestNet, "net_unittests": self.TestNet, "printing": self.TestPrinting, "printing_unittests": self.TestPrinting, "startup": self.TestStartup, "startup_tests": self.TestStartup, "sync": self.TestSync, "sync_unit_tests": self.TestSync, "test_shell": self.TestTestShell, "test_shell_tests": self.TestTestShell, "ui": self.TestUI, "ui_tests": self.TestUI, "unit": self.TestUnit, "unit_tests": self.TestUnit, "app": self.TestApp, "app_unittests": self.TestApp, }
|
def __init__(self, options, args, test): # The known list of tests. # Recognise the original abbreviations as well as full executable names. self._test_list = { "base": self.TestBase, "base_unittests": self.TestBase, "browser": self.TestBrowser, "browser_tests": self.TestBrowser, "googleurl": self.TestGURL, "googleurl_unittests": self.TestGURL, "ipc": self.TestIpc, "ipc_tests": self.TestIpc, "layout": self.TestLayout, "layout_tests": self.TestLayout, "media": self.TestMedia, "media_unittests": self.TestMedia, "net": self.TestNet, "net_unittests": self.TestNet, "printing": self.TestPrinting, "printing_unittests": self.TestPrinting, "startup": self.TestStartup, "startup_tests": self.TestStartup, "sync": self.TestSync, "sync_unit_tests": self.TestSync, "test_shell": self.TestTestShell, "test_shell_tests": self.TestTestShell, "ui": self.TestUI, "ui_tests": self.TestUI, "unit": self.TestUnit, "unit_tests": self.TestUnit, "app": self.TestApp, "app_unittests": self.TestApp, }
| 476,400
|
def TestLayoutChunk(self, chunk_num, chunk_size): # Run tests [chunk_num*chunk_size .. (chunk_num+1)*chunk_size) from the # list of tests. Wrap around to beginning of list at end. # If chunk_size is zero, run all tests in the list once. # If a text file is given as argument, it is used as the list of tests. # # Build the ginormous commandline in 'cmd'. # It's going to be roughly # python valgrind_test.py ... python run-chromium-webkit-tests ... # but we'll use the --indirect flag to valgrind_test.py # to avoid valgrinding python. # Start by building the valgrind_test.py commandline. cmd = self._DefaultCommand("webkit") cmd.append("--trace_children") cmd.append("--indirect") # Now build script_cmd, the run_chromium-webkits_tests commandline # Store each chunk in its own directory so that we can find the data later chunk_dir = os.path.join("layout", "chunk_%05d" % chunk_num) test_shell = os.path.join(self._options.build_dir, "test_shell") out_dir = os.path.join(google.path_utils.ScriptDir(), "latest") out_dir = os.path.join(out_dir, chunk_dir) if os.path.exists(out_dir): old_files = glob.glob(os.path.join(out_dir, "*.txt")) for f in old_files: os.remove(f) else: os.makedirs(out_dir) script = os.path.join(self._source_dir, "third_party", "WebKit", "WebKitTools", "Scripts", "run-chromium-webkit-tests") script_cmd = ["python", script, "--run-singly", "-v", "--noshow-results", "--time-out-ms=200000", "--nocheck-sys-deps"] # Pass build mode to run-chromium-webkit-tests. We aren't passed it # directly, so parse it out of build_dir. run-chromium-webkit-tests # can only handle the two values "Release" and "Debug". # TODO(Hercules): unify how all our scripts pass around build mode # (--mode / --target / --build_dir / --debug) if self._options.build_dir.endswith("Debug"): script_cmd.append("--debug"); if (chunk_size > 0): script_cmd.append("--run-chunk=%d:%d" % (chunk_num, chunk_size)) if len(self._args): # if the arg is a txt file, then treat it as a list of tests if os.path.isfile(self._args[0]) and self._args[0][-4:] == ".txt": script_cmd.append("--test-list=%s" % self._args[0]) else: script_cmd.extend(self._args) self._ReadGtestFilterFile("layout", script_cmd) # Now run script_cmd with the wrapper in cmd cmd.extend(["--"]) cmd.extend(script_cmd) return valgrind_test.RunTool(cmd, "layout")
|
def TestLayoutChunk(self, chunk_num, chunk_size): # Run tests [chunk_num*chunk_size .. (chunk_num+1)*chunk_size) from the # list of tests. Wrap around to beginning of list at end. # If chunk_size is zero, run all tests in the list once. # If a text file is given as argument, it is used as the list of tests. # # Build the ginormous commandline in 'cmd'. # It's going to be roughly # python valgrind_test.py ... python run-chromium-webkit-tests ... # but we'll use the --indirect flag to valgrind_test.py # to avoid valgrinding python. # Start by building the valgrind_test.py commandline. cmd = self._DefaultCommand("webkit") cmd.append("--trace_children") cmd.append("--indirect") # Now build script_cmd, the run_chromium-webkits_tests commandline # Store each chunk in its own directory so that we can find the data later chunk_dir = os.path.join("layout", "chunk_%05d" % chunk_num) test_shell = os.path.join(self._options.build_dir, "test_shell") out_dir = os.path.join(google.path_utils.ScriptDir(), "latest") out_dir = os.path.join(out_dir, chunk_dir) if os.path.exists(out_dir): old_files = glob.glob(os.path.join(out_dir, "*.txt")) for f in old_files: os.remove(f) else: os.makedirs(out_dir) script = os.path.join(self._source_dir, "third_party", "WebKit", "WebKitTools", "Scripts", "run-chromium-webkit-tests") script_cmd = ["python", script, "--run-singly", "-v", "--noshow-results", "--time-out-ms=200000", "--nocheck-sys-deps"] # Pass build mode to run-chromium-webkit-tests. We aren't passed it # directly, so parse it out of build_dir. run-chromium-webkit-tests # can only handle the two values "Release" and "Debug". # TODO(Hercules): unify how all our scripts pass around build mode # (--mode / --target / --build_dir / --debug) if self._options.build_dir.endswith("Debug"): script_cmd.append("--debug"); if (chunk_size > 0): script_cmd.append("--run-chunk=%d:%d" % (chunk_num, chunk_size)) if len(self._args): # if the arg is a txt file, then treat it as a list of tests if os.path.isfile(self._args[0]) and self._args[0][-4:] == ".txt": script_cmd.append("--test-list=%s" % self._args[0]) else: script_cmd.extend(self._args) self._ReadGtestFilterFile("layout", script_cmd) # Now run script_cmd with the wrapper in cmd cmd.extend(["--"]) cmd.extend(script_cmd) return valgrind_test.RunTool(cmd, "layout")
| 476,401
|
def TestLayoutChunk(self, chunk_num, chunk_size): # Run tests [chunk_num*chunk_size .. (chunk_num+1)*chunk_size) from the # list of tests. Wrap around to beginning of list at end. # If chunk_size is zero, run all tests in the list once. # If a text file is given as argument, it is used as the list of tests. # # Build the ginormous commandline in 'cmd'. # It's going to be roughly # python valgrind_test.py ... python run-chromium-webkit-tests ... # but we'll use the --indirect flag to valgrind_test.py # to avoid valgrinding python. # Start by building the valgrind_test.py commandline. cmd = self._DefaultCommand("webkit") cmd.append("--trace_children") cmd.append("--indirect") # Now build script_cmd, the run_chromium-webkits_tests commandline # Store each chunk in its own directory so that we can find the data later chunk_dir = os.path.join("layout", "chunk_%05d" % chunk_num) test_shell = os.path.join(self._options.build_dir, "test_shell") out_dir = os.path.join(google.path_utils.ScriptDir(), "latest") out_dir = os.path.join(out_dir, chunk_dir) if os.path.exists(out_dir): old_files = glob.glob(os.path.join(out_dir, "*.txt")) for f in old_files: os.remove(f) else: os.makedirs(out_dir) script = os.path.join(self._source_dir, "third_party", "WebKit", "WebKitTools", "Scripts", "run-chromium-webkit-tests") script_cmd = ["python", script, "--run-singly", "-v", "--noshow-results", "--time-out-ms=200000", "--nocheck-sys-deps"] # Pass build mode to run-chromium-webkit-tests. We aren't passed it # directly, so parse it out of build_dir. run-chromium-webkit-tests # can only handle the two values "Release" and "Debug". # TODO(Hercules): unify how all our scripts pass around build mode # (--mode / --target / --build_dir / --debug) if self._options.build_dir.endswith("Debug"): script_cmd.append("--debug"); if (chunk_size > 0): script_cmd.append("--run-chunk=%d:%d" % (chunk_num, chunk_size)) if len(self._args): # if the arg is a txt file, then treat it as a list of tests if os.path.isfile(self._args[0]) and self._args[0][-4:] == ".txt": script_cmd.append("--test-list=%s" % self._args[0]) else: script_cmd.extend(self._args) self._ReadGtestFilterFile("layout", script_cmd) # Now run script_cmd with the wrapper in cmd cmd.extend(["--"]) cmd.extend(script_cmd) return valgrind_test.RunTool(cmd, "layout")
|
def TestLayoutChunk(self, chunk_num, chunk_size): # Run tests [chunk_num*chunk_size .. (chunk_num+1)*chunk_size) from the # list of tests. Wrap around to beginning of list at end. # If chunk_size is zero, run all tests in the list once. # If a text file is given as argument, it is used as the list of tests. # # Build the ginormous commandline in 'cmd'. # It's going to be roughly # python valgrind_test.py ... python run-chromium-webkit-tests ... # but we'll use the --indirect flag to valgrind_test.py # to avoid valgrinding python. # Start by building the valgrind_test.py commandline. cmd = self._DefaultCommand("webkit") cmd.append("--trace_children") cmd.append("--indirect") # Now build script_cmd, the run_chromium-webkits_tests commandline # Store each chunk in its own directory so that we can find the data later chunk_dir = os.path.join("layout", "chunk_%05d" % chunk_num) test_shell = os.path.join(self._options.build_dir, "test_shell") out_dir = os.path.join(google.path_utils.ScriptDir(), "latest") out_dir = os.path.join(out_dir, chunk_dir) if os.path.exists(out_dir): old_files = glob.glob(os.path.join(out_dir, "*.txt")) for f in old_files: os.remove(f) else: os.makedirs(out_dir) script = os.path.join(self._source_dir, "third_party", "WebKit", "WebKitTools", "Scripts", "run-chromium-webkit-tests") script_cmd = ["python", script, "--run-singly", "-v", "--noshow-results", "--time-out-ms=200000", "--nocheck-sys-deps"] # Pass build mode to run-chromium-webkit-tests. We aren't passed it # directly, so parse it out of build_dir. run-chromium-webkit-tests # can only handle the two values "Release" and "Debug". # TODO(Hercules): unify how all our scripts pass around build mode # (--mode / --target / --build_dir / --debug) if self._options.build_dir.endswith("Debug"): script_cmd.append("--debug"); if (chunk_size > 0): script_cmd.append("--run-chunk=%d:%d" % (chunk_num, chunk_size)) if len(self._args): # if the arg is a txt file, then treat it as a list of tests if os.path.isfile(self._args[0]) and self._args[0][-4:] == ".txt": script_cmd.append("--test-list=%s" % self._args[0]) else: script_cmd.extend(self._args) self._ReadGtestFilterFile("layout", script_cmd) # Now run script_cmd with the wrapper in cmd cmd.extend(["--"]) cmd.extend(script_cmd) return valgrind_test.RunTool(cmd, "layout")
| 476,402
|
def TestLayoutChunk(self, chunk_num, chunk_size): # Run tests [chunk_num*chunk_size .. (chunk_num+1)*chunk_size) from the # list of tests. Wrap around to beginning of list at end. # If chunk_size is zero, run all tests in the list once. # If a text file is given as argument, it is used as the list of tests. # # Build the ginormous commandline in 'cmd'. # It's going to be roughly # python valgrind_test.py ... python run-chromium-webkit-tests ... # but we'll use the --indirect flag to valgrind_test.py # to avoid valgrinding python. # Start by building the valgrind_test.py commandline. cmd = self._DefaultCommand("webkit") cmd.append("--trace_children") cmd.append("--indirect") # Now build script_cmd, the run_chromium-webkits_tests commandline # Store each chunk in its own directory so that we can find the data later chunk_dir = os.path.join("layout", "chunk_%05d" % chunk_num) test_shell = os.path.join(self._options.build_dir, "test_shell") out_dir = os.path.join(google.path_utils.ScriptDir(), "latest") out_dir = os.path.join(out_dir, chunk_dir) if os.path.exists(out_dir): old_files = glob.glob(os.path.join(out_dir, "*.txt")) for f in old_files: os.remove(f) else: os.makedirs(out_dir) script = os.path.join(self._source_dir, "third_party", "WebKit", "WebKitTools", "Scripts", "run-chromium-webkit-tests") script_cmd = ["python", script, "--run-singly", "-v", "--noshow-results", "--time-out-ms=200000", "--nocheck-sys-deps"] # Pass build mode to run-chromium-webkit-tests. We aren't passed it # directly, so parse it out of build_dir. run-chromium-webkit-tests # can only handle the two values "Release" and "Debug". # TODO(Hercules): unify how all our scripts pass around build mode # (--mode / --target / --build_dir / --debug) if self._options.build_dir.endswith("Debug"): script_cmd.append("--debug"); if (chunk_size > 0): script_cmd.append("--run-chunk=%d:%d" % (chunk_num, chunk_size)) if len(self._args): # if the arg is a txt file, then treat it as a list of tests if os.path.isfile(self._args[0]) and self._args[0][-4:] == ".txt": script_cmd.append("--test-list=%s" % self._args[0]) else: script_cmd.extend(self._args) self._ReadGtestFilterFile("layout", script_cmd) # Now run script_cmd with the wrapper in cmd cmd.extend(["--"]) cmd.extend(script_cmd) return valgrind_test.RunTool(cmd, "layout")
|
def TestLayoutChunk(self, chunk_num, chunk_size): # Run tests [chunk_num*chunk_size .. (chunk_num+1)*chunk_size) from the # list of tests. Wrap around to beginning of list at end. # If chunk_size is zero, run all tests in the list once. # If a text file is given as argument, it is used as the list of tests. # # Build the ginormous commandline in 'cmd'. # It's going to be roughly # python valgrind_test.py ... python run-chromium-webkit-tests ... # but we'll use the --indirect flag to valgrind_test.py # to avoid valgrinding python. # Start by building the valgrind_test.py commandline. cmd = self._DefaultCommand("webkit") cmd.append("--trace_children") cmd.append("--indirect") # Now build script_cmd, the run_chromium-webkits_tests commandline # Store each chunk in its own directory so that we can find the data later chunk_dir = os.path.join("layout", "chunk_%05d" % chunk_num) test_shell = os.path.join(self._options.build_dir, "test_shell") out_dir = os.path.join(google.path_utils.ScriptDir(), "latest") out_dir = os.path.join(out_dir, chunk_dir) if os.path.exists(out_dir): old_files = glob.glob(os.path.join(out_dir, "*.txt")) for f in old_files: os.remove(f) else: os.makedirs(out_dir) script = os.path.join(self._source_dir, "webkit", "tools", "layout_tests", "run_webkit_tests.py") script_cmd = ["python", script, "--run-singly", "-v", "--noshow-results", "--time-out-ms=200000", "--nocheck-sys-deps"] # Pass build mode to run-chromium-webkit-tests. We aren't passed it # directly, so parse it out of build_dir. run-chromium-webkit-tests # can only handle the two values "Release" and "Debug". # TODO(Hercules): unify how all our scripts pass around build mode # (--mode / --target / --build_dir / --debug) if self._options.build_dir.endswith("Debug"): script_cmd.append("--debug"); if (chunk_size > 0): script_cmd.append("--run-chunk=%d:%d" % (chunk_num, chunk_size)) if len(self._args): # if the arg is a txt file, then treat it as a list of tests if os.path.isfile(self._args[0]) and self._args[0][-4:] == ".txt": script_cmd.append("--test-list=%s" % self._args[0]) else: script_cmd.extend(self._args) self._ReadGtestFilterFile("layout", script_cmd) # Now run script_cmd with the wrapper in cmd cmd.extend(["--"]) cmd.extend(script_cmd) return valgrind_test.RunTool(cmd, "layout")
| 476,403
|
def TestLayoutChunk(self, chunk_num, chunk_size): # Run tests [chunk_num*chunk_size .. (chunk_num+1)*chunk_size) from the # list of tests. Wrap around to beginning of list at end. # If chunk_size is zero, run all tests in the list once. # If a text file is given as argument, it is used as the list of tests. # # Build the ginormous commandline in 'cmd'. # It's going to be roughly # python valgrind_test.py ... python run-chromium-webkit-tests ... # but we'll use the --indirect flag to valgrind_test.py # to avoid valgrinding python. # Start by building the valgrind_test.py commandline. cmd = self._DefaultCommand("webkit") cmd.append("--trace_children") cmd.append("--indirect") # Now build script_cmd, the run_chromium-webkits_tests commandline # Store each chunk in its own directory so that we can find the data later chunk_dir = os.path.join("layout", "chunk_%05d" % chunk_num) test_shell = os.path.join(self._options.build_dir, "test_shell") out_dir = os.path.join(google.path_utils.ScriptDir(), "latest") out_dir = os.path.join(out_dir, chunk_dir) if os.path.exists(out_dir): old_files = glob.glob(os.path.join(out_dir, "*.txt")) for f in old_files: os.remove(f) else: os.makedirs(out_dir) script = os.path.join(self._source_dir, "third_party", "WebKit", "WebKitTools", "Scripts", "run-chromium-webkit-tests") script_cmd = ["python", script, "--run-singly", "-v", "--noshow-results", "--time-out-ms=200000", "--nocheck-sys-deps"] # Pass build mode to run-chromium-webkit-tests. We aren't passed it # directly, so parse it out of build_dir. run-chromium-webkit-tests # can only handle the two values "Release" and "Debug". # TODO(Hercules): unify how all our scripts pass around build mode # (--mode / --target / --build_dir / --debug) if self._options.build_dir.endswith("Debug"): script_cmd.append("--debug"); if (chunk_size > 0): script_cmd.append("--run-chunk=%d:%d" % (chunk_num, chunk_size)) if len(self._args): # if the arg is a txt file, then treat it as a list of tests if os.path.isfile(self._args[0]) and self._args[0][-4:] == ".txt": script_cmd.append("--test-list=%s" % self._args[0]) else: script_cmd.extend(self._args) self._ReadGtestFilterFile("layout", script_cmd) # Now run script_cmd with the wrapper in cmd cmd.extend(["--"]) cmd.extend(script_cmd) return valgrind_test.RunTool(cmd, "layout")
|
def TestLayoutChunk(self, chunk_num, chunk_size): # Run tests [chunk_num*chunk_size .. (chunk_num+1)*chunk_size) from the # list of tests. Wrap around to beginning of list at end. # If chunk_size is zero, run all tests in the list once. # If a text file is given as argument, it is used as the list of tests. # # Build the ginormous commandline in 'cmd'. # It's going to be roughly # python valgrind_test.py ... python run-chromium-webkit-tests ... # but we'll use the --indirect flag to valgrind_test.py # to avoid valgrinding python. # Start by building the valgrind_test.py commandline. cmd = self._DefaultCommand("webkit") cmd.append("--trace_children") cmd.append("--indirect") # Now build script_cmd, the run_chromium-webkits_tests commandline # Store each chunk in its own directory so that we can find the data later chunk_dir = os.path.join("layout", "chunk_%05d" % chunk_num) test_shell = os.path.join(self._options.build_dir, "test_shell") out_dir = os.path.join(google.path_utils.ScriptDir(), "latest") out_dir = os.path.join(out_dir, chunk_dir) if os.path.exists(out_dir): old_files = glob.glob(os.path.join(out_dir, "*.txt")) for f in old_files: os.remove(f) else: os.makedirs(out_dir) script = os.path.join(self._source_dir, "third_party", "WebKit", "WebKitTools", "Scripts", "run-chromium-webkit-tests") script_cmd = ["python", script, "--run-singly", "-v", "--noshow-results", "--time-out-ms=200000", "--nocheck-sys-deps"] # Pass build mode to run-chromium-webkit-tests. We aren't passed it # directly, so parse it out of build_dir. run-chromium-webkit-tests # can only handle the two values "Release" and "Debug". # TODO(Hercules): unify how all our scripts pass around build mode # (--mode / --target / --build_dir / --debug) if self._options.build_dir.endswith("Debug"): script_cmd.append("--debug"); if (chunk_size > 0): script_cmd.append("--run-chunk=%d:%d" % (chunk_num, chunk_size)) if len(self._args): # if the arg is a txt file, then treat it as a list of tests if os.path.isfile(self._args[0]) and self._args[0][-4:] == ".txt": script_cmd.append("--test-list=%s" % self._args[0]) else: script_cmd.extend(self._args) self._ReadGtestFilterFile("layout", script_cmd) # Now run script_cmd with the wrapper in cmd cmd.extend(["--"]) cmd.extend(script_cmd) return valgrind_test.RunTool(cmd, "layout")
| 476,404
|
def _LocateBinDirs(): """Setup a few dirs where we expect to find dependency libraries.""" script_dir = os.path.dirname(__file__) chrome_src = os.path.join(script_dir, os.pardir, os.pardir, os.pardir) bin_dirs = { 'linux2': [ os.path.join(chrome_src, 'out', 'Debug'), os.path.join(chrome_src, 'sconsbuild', 'Debug'), os.path.join(chrome_src, 'out', 'Release'), os.path.join(chrome_src, 'sconsbuild', 'Release')], 'darwin': [ os.path.join(chrome_src, 'xcodebuild', 'Debug'), os.path.join(chrome_src, 'xcodebuild', 'Release')], 'win32': [ os.path.join(chrome_src, 'chrome', 'Debug'), os.path.join(chrome_src, 'chrome', 'Release')], 'cygwin': [ os.path.join(chrome_src, 'chrome', 'Debug'), os.path.join(chrome_src, 'chrome', 'Release')], } deps_dirs = [ os.path.join(script_dir, os.pardir, os.pardir, os.pardir, 'third_party'), script_dir, ] sys.path += map(os.path.normpath, bin_dirs.get(sys.platform, []) + deps_dirs)
|
def _LocateBinDirs(): """Setup a few dirs where we expect to find dependency libraries.""" script_dir = os.path.dirname(__file__) chrome_src = os.path.join(script_dir, os.pardir, os.pardir, os.pardir) bin_dirs = { 'linux2': [ os.path.join(chrome_src, 'out', 'Debug'), os.path.join(chrome_src, 'sconsbuild', 'Debug'), os.path.join(chrome_src, 'out', 'Release'), os.path.join(chrome_src, 'sconsbuild', 'Release')], 'darwin': [ os.path.join(chrome_src, 'xcodebuild', 'Debug'), os.path.join(chrome_src, 'xcodebuild', 'Release')], 'win32': [ os.path.join(chrome_src, 'chrome', 'Debug'), os.path.join(chrome_src, 'build', 'Debug'), os.path.join(chrome_src, 'chrome', 'Release'), os.path.join(chrome_src, 'build', 'Release')], 'cygwin': [ os.path.join(chrome_src, 'chrome', 'Debug'), os.path.join(chrome_src, 'build', 'Debug'), os.path.join(chrome_src, 'chrome', 'Release'), os.path.join(chrome_src, 'build', 'Release')], } deps_dirs = [ os.path.join(script_dir, os.pardir, os.pardir, os.pardir, 'third_party'), script_dir, ] sys.path += map(os.path.normpath, bin_dirs.get(sys.platform, []) + deps_dirs)
| 476,405
|
def main(argv): usage = """Usage: python %prog [--root <root>] [tocheck] tocheck Specifies the directory, relative to root, to check. This defaults to "." so it checks everything.
|
def main(argv): usage = """Usage: python %prog [--root <root>] [tocheck] tocheck Specifies the directory, relative to root, to check. This defaults to "." so it checks everything.
| 476,406
|
def get(self): extURL = cgi.escape(self.request.get('extURL')) extMethod = cgi.escape(self.request.get('extMethod')) queryString = cgi.escape(self.request.query_string) queryDict = dict(cgi.parse_qsl(queryString)) callback = cgi.escape(self.request.get('_callback')) if queryString: error = 1 method = urlfetch.POST if extURL: del queryDict['extURL'] if extMethod: del queryDict['extMethod'] m = extMethod.lower() if m == 'put': method = urlfetch.PUT elif m == 'delete': method = urlfetch.DELETE elif m == 'get': method = urlfetch.GET # Huh?? elif m == 'head': method = urlfetch.HEAD # Oh, wait the minute... if len(queryDict): try: data = urllib.urlencode(queryDict) result = urlfetch.fetch(extURL, method=method, payload=data) if result.status_code == 200 or result.status_code == 201: error = 0 self.response.headers['Content-Type'] = 'application/javascript; charset=utf-8' content = result.content if callback: logging.info('Adding callback to JSON') exp = re.compile('^[A-Za-z_$][A-Za-z0-9._$]*?$') match = exp.match(callback) if match: content = callback + '(' + content + ')' self.response.out.write(content) except urlfetch.Error: logging.error('urlfetch error') error = 1 if error: self.response.set_status(400) self.response.out.write('Status: 400 Error parsing URL. There was an error processing your request: Error parsing URL.') else: self.response.out.write(""" <!DOCTYPE html> <title>jsonptunnel</title> <style> body{font-family: helvetica, arial, sans-serif} var{font-weight: bold; font-style: normal;} dt{display: list-item;} dl{margin-left: 40px;} </style> <h1>jsonptunnel</h1> <p>JSONP tunnel for letting you POST to remote services from your client-side JavaScript application and receive JSONP data.</p> <p><a href="http://labs.thinkminimo.com/jsonptunnel/#example">Try it out on the example form</a> and put <strong>http://jsonptunnel.appspot.com/</strong> as the jsonptunnel URL.</p> <p>Or try the following URL: <a href="/?callback=foo&extURL=http://dipert.org/alan/calc.php&num1=1&num2=2">/?callback=foo&extURL=http://dipert.org/alan/calc.php&num1=1&num2=2</a></p> <p>The parameters:</p> <dl> <dt><var>extURL</var></dt> <dd>Indicates the <em>external</em> web service URL. <strong>Required</strong>.</dd> <dt><var>extMethod</var> <em>(experimental)</em></dt> <dd>Indicates the HTTP method to use for the request, such as: <ul> <li>post <em>(default)</em></li> <li>put</li> <li>delete</li> </ul> </dd> <dt>...and any parameters to pass to the web service.</dt> </dl> <p>Inspired by <a href="http://ubergibson.com/">Alan Dipert</a>'s <a href="http://labs.thinkminimo.com/jsonptunnel/">jsonptunnel</a>. <a href="http://jsonptunnel.googlecode.com/">Google Code</a></p> """)
|
def get(self): extURL = cgi.escape(self.request.get('extURL')) extMethod = cgi.escape(self.request.get('extMethod')) queryString = cgi.escape(self.request.query_string) queryDict = dict(cgi.parse_qsl(queryString)) callback = cgi.escape(self.request.get('_callback')) if queryString: error = 1 method = urlfetch.POST if extURL: del queryDict['extURL'] if extMethod: del queryDict['extMethod'] m = extMethod.lower() if m == 'put': method = urlfetch.PUT elif m == 'delete': method = urlfetch.DELETE elif m == 'get': method = urlfetch.GET # Huh?? elif m == 'head': method = urlfetch.HEAD # Oh, wait the minute... if len(queryDict): try: data = urllib.urlencode(queryDict) result = urlfetch.fetch(extURL, method=method, payload=data) if result.status_code == 200 or result.status_code == 201: error = 0 self.response.headers['Content-Type'] = 'application/javascript; charset=utf-8' content = result.content if callback: logging.info('Adding callback to JSON') exp = re.compile('^[A-Za-z_$][A-Za-z0-9._$]*?$') match = exp.match(callback) if match: content = callback + '(' + content.decode('utf-8') + ')' self.response.out.write(content) except urlfetch.Error: logging.error('urlfetch error') error = 1 if error: self.response.set_status(400) self.response.out.write('Status: 400 Error parsing URL. There was an error processing your request: Error parsing URL.') else: self.response.out.write(""" <!DOCTYPE html> <title>jsonptunnel</title> <style> body{font-family: helvetica, arial, sans-serif} var{font-weight: bold; font-style: normal;} dt{display: list-item;} dl{margin-left: 40px;} </style> <h1>jsonptunnel</h1> <p>JSONP tunnel for letting you POST to remote services from your client-side JavaScript application and receive JSONP data.</p> <p><a href="http://labs.thinkminimo.com/jsonptunnel/#example">Try it out on the example form</a> and put <strong>http://jsonptunnel.appspot.com/</strong> as the jsonptunnel URL.</p> <p>Or try the following URL: <a href="/?callback=foo&extURL=http://dipert.org/alan/calc.php&num1=1&num2=2">/?callback=foo&extURL=http://dipert.org/alan/calc.php&num1=1&num2=2</a></p> <p>The parameters:</p> <dl> <dt><var>extURL</var></dt> <dd>Indicates the <em>external</em> web service URL. <strong>Required</strong>.</dd> <dt><var>extMethod</var> <em>(experimental)</em></dt> <dd>Indicates the HTTP method to use for the request, such as: <ul> <li>post <em>(default)</em></li> <li>put</li> <li>delete</li> </ul> </dd> <dt>...and any parameters to pass to the web service.</dt> </dl> <p>Inspired by <a href="http://ubergibson.com/">Alan Dipert</a>'s <a href="http://labs.thinkminimo.com/jsonptunnel/">jsonptunnel</a>. <a href="http://jsonptunnel.googlecode.com/">Google Code</a></p> """)
| 476,407
|
def _appendToProjectsPy(self, moduleName, branchLocation, destination, template):
|
def _appendToProjectsPy(self, moduleName, branchLocation, destination, template):
| 476,408
|
def __init__(self): """ Initialization of members. No other functionality. """ usage = "" usage += "The list below shows global available options.\n"
|
def __init__(self): """ Initialization of members. No other functionality. """ usage = "" usage += "The list below shows global available options.\n"
| 476,409
|
def update(self): value = zope.component.queryMultiAdapter( (self.context, self.request, self.widget, self.field, self.form, self), interfaces.IValue, name='message') if value is not None: self.message = value.get() else: self.message = self.createMessage()
|
def update(self): value = zope.component.queryMultiAdapter( (self.context, self.request, self.widget, self.field, self.form, self.content), interfaces.IValue, name='message') if value is not None: self.message = value.get() else: self.message = self.createMessage()
| 476,410
|
def getSpecification(spec, force=False): """Get the specification of the given object. If the given object is already a specification acceptable to the component architecture, it is simply returned. This is true for classes and specification objects (which includes interfaces). In case of instances, an interface is generated on the fly and tagged onto the object. Then the interface is returned as the specification. """ # If the specification is an instance, then we do some magic. if (force or (spec is not None and not zope.interface.interfaces.ISpecification.providedBy(spec) and not isinstance(spec, classTypes)) ): # Step 1: Create an interface iface = zope.interface.interface.InterfaceClass( 'IGeneratedForObject_%i' %hash(spec)) # Step 2: Directly-provide the interface on the specification zope.interface.alsoProvides(spec, iface) # Step 3: Make the new interface the specification for this instance spec = iface return spec
|
def getSpecification(spec, force=False): """Get the specification of the given object. If the given object is already a specification acceptable to the component architecture, it is simply returned. This is true for classes and specification objects (which includes interfaces). In case of instances, an interface is generated on the fly and tagged onto the object. Then the interface is returned as the specification. """ # If the specification is an instance, then we do some magic. if (force or (spec is not None and not zope.interface.interfaces.ISpecification.providedBy(spec) and not isinstance(spec, classTypes)) ): # Step 1: Create an interface iface = zope.interface.interface.InterfaceClass( 'IGeneratedForObject_%i' %hash(spec)) # Step 2: Directly-provide the interface on the specification zope.interface.alsoProvides(spec, iface) # Step 3: Make the new interface the specification for this instance spec = iface return spec
| 476,411
|
def get(self): """See z3c.form.interfaces.IDataManager""" return self.data.get(self.field.__name__, self.field.missing_value)
|
def get(self): """See z3c.form.interfaces.IDataManager""" return self.data.get(self.field.__name__, self.field.missing_value)
| 476,412
|
def _construct_ids(self, element, prefix, baseuri, skip_fragments=[], find_definitions = False): find_definitions_recursive = find_definitions counters = defaultdict(int) if isinstance(element, CompoundStructure): # Hitta begreppsdefinitioner if isinstance(element, Paragraf): # kolla om frsta stycket innehller en text som # antyder att definitioner fljer # log.debug("Testing %r against some regexes" % element[0][0]) if self.re_definitions(element[0][0]): find_definitions = "normal" if (self.re_brottsdef(element[0][0]) or self.re_brottsdef_alt(element[0][0])): find_definitions = "brottsrubricering" if self.re_parantesdef(element[0][0]): find_definitions = "parantes" if self.re_loptextdef(element[0][0]): find_definitions = "loptext"
|
def _construct_ids(self, element, prefix, baseuri, skip_fragments=[], find_definitions = False): find_definitions_recursive = find_definitions counters = defaultdict(int) if isinstance(element, CompoundStructure): # Hitta begreppsdefinitioner if isinstance(element, Paragraf): # kolla om frsta stycket innehller en text som # antyder att definitioner fljer # log.debug("Testing %r against some regexes" % element[0][0]) if self.re_definitions(element[0][0]): find_definitions = "normal" if (self.re_brottsdef(element[0][0]) or self.re_brottsdef_alt(element[0][0])): find_definitions = "brottsrubricering" if self.re_parantesdef(element[0][0]): find_definitions = "parantes" if self.re_loptextdef(element[0][0]): find_definitions = "loptext"
| 476,413
|
def prep_annotation_file(self,basefile): print "prep_annotation_file"
|
def prep_annotation_file(self,basefile): print "prep_annotation_file"
| 476,414
|
def prep_annotation_file(self,basefile): print "prep_annotation_file"
|
def prep_annotation_file(self,basefile): print "prep_annotation_file"
| 476,415
|
def prep_annotation_file(self,basefile): print "prep_annotation_file"
|
def prep_annotation_file(self,basefile): print "prep_annotation_file"
| 476,416
|
def prep_annotation_file(self,basefile): print "prep_annotation_file"
|
def prep_annotation_file(self,basefile): print "prep_annotation_file"
| 476,417
|
def prep_annotation_file(self,basefile): print "prep_annotation_file"
|
defpass prep_annotation_file(self,basefile):pass printpass "prep_annotation_file"
| 476,418
|
def __str__(self): return repr(self.value)
|
def __str__(self): return repr(self.value)
| 476,419
|
def parse(self, indata, baseuri="http://rinfo.lagrummet.se/publ/sfs/9999:999#K9P9S9P9",predicate=None): if indata == "": return indata # this actually triggered a bug... # h = hashlib.sha1() # h.update(indata) # print "Called with %r (%s) (%s)" % (indata, h.hexdigest(), self.verbose) self.predicate = predicate self.baseuri = baseuri if baseuri: m = self.re_urisegments.match(baseuri) if m: self.baseuri_attributes = {'baseuri':m.group(1), 'law':m.group(2), 'chapter':m.group(6), 'section':m.group(8), 'piece':m.group(10), 'item':m.group(12)} else: self.baseuri_attributes = {'baseuri':baseuri} else: self.baseuri_attributes = {} # Det r svrt att f EBNF-grammatiken att knna igen # godtyckliga ord som slutar p ett givet suffix (exv # 'bokfringslagen' med suffixet 'lagen'). Drfr frbehandlar # vi indatastrngen och stoppar in ett '|'-tecken innan vissa # suffix. Vi transformerar ven 'Radio- och TV-lagen' till # 'Radio-_och_TV-lagen' fixedindata = self.re_escape_compound.sub(r'\1_\2_\3\4', indata) fixedindata = self.re_escape_named.sub(r'|\1', fixedindata)
|
defparse(self,indata,baseuri="http://rinfo.lagrummet.se/publ/sfs/9999:999#K9P9S9P9",predicate=None):ifindata=="":returnindata#thisactuallytriggeredabug...#h=hashlib.sha1()#h.update(indata)#print"Calledwith%r(%s)(%s)"%(indata,h.hexdigest(),self.verbose)self.predicate=predicateself.baseuri=baseuriifbaseuri:m=self.re_urisegments.match(baseuri)ifm:self.baseuri_attributes={'baseuri':m.group(1),'law':m.group(2),'chapter':m.group(6),'section':m.group(8),'piece':m.group(10),'item':m.group(12)}else:self.baseuri_attributes={'baseuri':baseuri}else:self.baseuri_attributes={}#DetrsvrtattfEBNF-grammatikenattknnaigen#godtyckligaordsomslutarpettgivetsuffix(exv#'bokfringslagen'medsuffixet'lagen').Drfrfrbehandlar#viindatastrngenochstopparinett'|'-teckeninnanvissa#suffix.Vitransformerarven'Radio-ochTV-lagen'till#'Radio-_och_TV-lagen'fixedindata=self.re_escape_compound.sub(r'\1_\2_\3\4',indata)fixedindata=self.re_escape_named.sub(r'|\1',fixedindata)
| 476,420
|
def __getSolrData(self): prefix = self.getSearchTerms() if prefix: query = '%(prefix)s OR %(prefix)s*' % { "prefix" : prefix } else: query = "*:*" req = SearchRequest(query) req.addParam("fq", 'item_type:"object"') req.addParam("fq", 'repository_type:"SEO"') req.setParam("fl", "score") req.setParam("sort", "score desc") req.setParam("start", self.getStartIndex()) req.setParam("rows", self.getItemsPerPage()) level = self.getFormData("level", None) if level is not None: if level=="top": #query += " AND skos_hasTopConcept:http*" query += ' AND dc_identifier:"http://purl.org/anzsrc/seo/#division"' else: query += ' AND skos_broader:"%s"' % level try: out = ByteArrayOutputStream() indexer = self.services.getIndexer() indexer.search(req, out) return JsonConfigHelper(ByteArrayInputStream(out.toByteArray())) except Exception, e: self.log.error("Failed to lookup '{}': {}", prefix, str(e)) return JsonConfigHelper()
|
def __getSolrData(self): prefix = self.getSearchTerms() if prefix: query = '%(prefix)s OR %(prefix)s*' % { "prefix" : prefix } else: query = "*:*" req = SearchRequest(query) req.addParam("fq", 'item_type:"object"') req.addParam("fq", 'repository_type:"SEO"') req.setParam("fl", "score") req.setParam("sort", "score desc") req.setParam("start", self.getStartIndex()) req.setParam("rows", self.getItemsPerPage()) level = self.getFormData("level", None) if level is not None: if level=="top": #query += " AND skos_hasTopConcept:http*" query += ' AND dc_identifier:"http://purl.org/anzsrc/seo/#division"' else: query += ' AND skos_broader:"%s"' % level try: out = ByteArrayOutputStream() indexer = self.services.getIndexer() indexer.search(req, out) return JsonConfigHelper(ByteArrayInputStream(out.toByteArray())) except Exception, e: self.log.error("Failed to lookup '{}': {}", prefix, str(e)) return JsonConfigHelper()
| 476,421
|
def __init__(self, bundleDir, ipswDir, outDir, verbose): self.bundleDir = bundleDir self.ipswDir = ipswDir self.outDir = outDir self.verbose = verbose
|
def __init__(self, bundleDir, ipswDir, outDir, verbose): self.bundleDir = bundleDir self.ipswDir = ipswDir self.outDir = outDir self.verbose = verbose
| 476,422
|
def main(): parser = OptionParser() parser.add_option("-b", "--bundle", dest="bundle", help="Bundle directory to use", metavar="BUNDLE_DIR") parser.add_option("-i", "--ipsw", dest="ipsw", help="Unpacked IPSW directory", metavar="IPSW_DIR") parser.add_option("-o", "--out", dest="out", help="Output directory", metavar="OUT_DIR") parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, help="Verbose mode") parser.add_option("-c", "--create", dest="create", action="store_true", default=False, help="Create patch files from work dir") (opts, args) = parser.parse_args() requiredOpts = ['bundle', 'ipsw', 'out'] for req in requiredOpts: if not opts.__dict__[req]: print "'%s' argument is mandatory!" % req exit(1) bundleParser = BundleParser( opts.bundle, opts.ipsw, opts.out, opts.verbose ) if opts.create: bundleParser.create_patch_files() else: bundleParser.process_info_plist()
|
def main(): parser = OptionParser() parser.add_option("-b", "--bundle", dest="bundle", help="Bundle directory to use", metavar="BUNDLE_DIR") parser.add_option("-i", "--ipsw", dest="ipsw", help="Unpacked IPSW directory", metavar="IPSW_DIR") parser.add_option("-o", "--out", dest="out", help="Output directory", metavar="OUT_DIR") parser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False, help="Verbose mode") parser.add_option("-c", "--create", dest="create", action="store_true", default=False, help="Create patch files from work dir") parser.add_option("-x", "--llbexploit", dest="x_opt", default=None, help="Type of LLB exploit to use, n8824k or 24k") (opts, args) = parser.parse_args() requiredOpts = ['bundle', 'ipsw', 'out'] for req in requiredOpts: if not opts.__dict__[req]: print "'%s' argument is mandatory!" % req exit(1) bundleParser = BundleParser( opts.bundle, opts.ipsw, opts.out, opts.verbose, opts.x_opt) if opts.create: bundleParser.create_patch_files() else: bundleParser.process_info_plist()
| 476,423
|
def byte_search(image, bytes): for i in range(0, len(image) - len(bytes), 2): if image[i:i+len(bytes)] == bytes: return i return -1
|
def byte_search(image, bytes): for i in range(0, len(image) - len(bytes), 2): if image[i:i+len(bytes)] == bytes: return i return -1
| 476,424
|
def value(self): "preserve volume during the binning" totalVol = 0 for ind,xPt,yPt in zip(range(self.numPts), self.xPts, self.yPts): #get leftOfBox if ind == 0: if self.leftSide < xPt: leftOfBox = self.leftSide else: leftOfBox = xPt else: leftOfBox = xPt[ind-1] #get rightOfBox if ind == (self.numPts-1): if self.rightSide > xPt: rightOfBox = self.rightSide else: rightOfBox = xPt else: rightOfBox=xPt[ind+1] boxLength = rightOfBox-leftOfBox boxVol = boxLength*yPt totalVol += boxVol totalHeight = totalVol/self.spacing return totalHeight
|
def value(self): "preserve volume during the binning" totalVol = 0 for ind,xPt,yPt in zip(range(self.numPts), self.xPts, self.yPts): #get leftOfBox if ind == 0: if self.leftSide < xPt: leftOfBox = self.leftSide else: leftOfBox = xPt else: leftOfBox = self.xPts[ind-1] #get rightOfBox if ind == (self.numPts-1): if self.rightSide > xPt: rightOfBox = self.rightSide else: rightOfBox = xPt else: rightOfBox=xPt[ind+1] boxLength = rightOfBox-leftOfBox boxVol = boxLength*yPt totalVol += boxVol totalHeight = totalVol/self.spacing return totalHeight
| 476,425
|
def value(self): "preserve volume during the binning" totalVol = 0 for ind,xPt,yPt in zip(range(self.numPts), self.xPts, self.yPts): #get leftOfBox if ind == 0: if self.leftSide < xPt: leftOfBox = self.leftSide else: leftOfBox = xPt else: leftOfBox = xPt[ind-1] #get rightOfBox if ind == (self.numPts-1): if self.rightSide > xPt: rightOfBox = self.rightSide else: rightOfBox = xPt else: rightOfBox=xPt[ind+1] boxLength = rightOfBox-leftOfBox boxVol = boxLength*yPt totalVol += boxVol totalHeight = totalVol/self.spacing return totalHeight
|
def value(self): "preserve volume during the binning" totalVol = 0 for ind,xPt,yPt in zip(range(self.numPts), self.xPts, self.yPts): #get leftOfBox if ind == 0: if self.leftSide < xPt: leftOfBox = self.leftSide else: leftOfBox = xPt else: leftOfBox = xPt[ind-1] #get rightOfBox if ind == (self.numPts-1): if self.rightSide > xPt: rightOfBox = self.rightSide else: rightOfBox = xPt else: rightOfBox = self.xPts[ind+1] boxLength = rightOfBox-leftOfBox boxVol = boxLength*yPt totalVol += boxVol totalHeight = totalVol/self.spacing return totalHeight
| 476,426
|
def __init__(self, leftSide=None, spacing=None, numXPointsToBin=None): self.numXPointsToBin = numXPointsToBin self.value = 0.0 self.xPts = [] self.yPts = [] self.leftSide = leftSide self.spacing = spacing
|
def __init__(self, leftSide=None, spacing=None, numXPointsToBin=None): self.numXPointsToBin = numXPointsToBin self.xPts = [] self.yPts = [] self.leftSide = leftSide self.spacing = spacing
| 476,427
|
def __init__(self, xDataP, yDataP, newBins=None, binValue = 'countPoints', format = 'columns'): xData = np.sort(xDataP) sortedInds = np.argsort(xDataP) yData = yDataP[sortedInds] self.bins=[] if type(newBins) is type(1): # this algorithm is for data that has already been binned and we're going over the bins to rebin import math leftOverPts, numXdataInBin = math.modf(len(xData)/len(newBins)) currentBin = Bin(numXPointsToBin = int(numXdataInBin)) for xPt,yPt in zip(xData,yData): if currentBin.getNumPts() >= numXdataInBin: currentBin.spacing = xPt - currentBin.xPts[0] self.bins.append(currentBin) currentBin = Bin(numXPointsToBin = int(numXdataInBin)) currentBin.xPts.append(xPt) if binValue=='countPoints': # then add together all the y axis values that fall within the new bin currentBin.value += yPt elif binValue=='averagePoints': #weight the average numPointsInBin = currentBin.getNumPts() currentBin.value = (numPointsInBin*currentBin.value + yPt)/(numPointsInBin+1) else: #assume newBins are equally spaced binCounter = 0 binSize = newBins[1] - newBins[0] currentBin = Bin(spacing = binSize, leftSide = newBins[binCounter]) for xPt,yPt in zip(xData,yData): if xPt >= currentBin.rightSide: self.bins.append(currentBin) binCounter += 1 currentBin = Bin(spacing = binSize, leftSide = newBins[binCounter]) currentBin.xPts.append(xPt) currentBin.yPts.append(yPt) # but when you plot, plot the y-axis value not at the x-axis pair, but at the midpoint between the x-axis pair # and the one up from it. Assume there is an additional x-axis point at the end with the same spacing as all the others.
|
def __init__(self, xDataP, yDataP, newBins=None, binValue = 'countPoints', format = 'columns'): xData = np.sort(xDataP) sortedInds = np.argsort(xDataP) yData = yDataP[sortedInds] self.bins=[] if type(newBins) is type(1): # this algorithm is for data that has already been binned and we're going over the bins to rebin import math leftOverPts, numXdataInBin = math.modf(len(xData)/len(newBins)) currentBin = Bin(numXPointsToBin = int(numXdataInBin)) for xPt,yPt in zip(xData,yData): if currentBin.getNumPts() >= numXdataInBin: currentBin.spacing = xPt - currentBin.xPts[0] self.bins.append(currentBin) currentBin = Bin(numXPointsToBin = int(numXdataInBin)) currentBin.xPts.append(xPt) if binValue=='countPoints': # then add together all the y axis values that fall within the new bin currentBin.value += yPt elif binValue=='averagePoints': #weight the average numPointsInBin = currentBin.getNumPts() currentBin.value = (numPointsInBin*currentBin.value + yPt)/(numPointsInBin+1) else: #assume newBins are equally spaced binCounter = 0 binSize = newBins[1] - newBins[0] currentBin = Bin(spacing = binSize, leftSide = newBins[binCounter]) for xPt,yPt in zip(xData,yData): while xPt >= currentBin.rightSide: self.bins.append(currentBin) binCounter += 1 currentBin = Bin(spacing = binSize, leftSide = newBins[binCounter]) currentBin.xPts.append(xPt) currentBin.yPts.append(yPt) # but when you plot, plot the y-axis value not at the x-axis pair, but at the midpoint between the x-axis pair # and the one up from it. Assume there is an additional x-axis point at the end with the same spacing as all the others.
| 476,428
|
def onAxis(self, axesGrp, axis, index): #index: index of this axis in the axis array #we need to index that so that axis can be loaded #sequentially. mapper = axis._mapper type = types[mapper.__class__]
|
def onAxis(self, axesGrp, axis, index): #index: index of this axis in the axis array #we need to index that so that axis can be loaded #sequentially. mapper = axis._mapper type = types[mapper.__class__]
| 476,429
|
def onAxis(self, axesGrp, axis, index): #index: index of this axis in the axis array #we need to index that so that axis can be loaded #sequentially. mapper = axis._mapper type = types[mapper.__class__]
|
def onAxis(self, axesGrp, axis, index): #index: index of this axis in the axis array #we need to index that so that axis can be loaded #sequentially. mapper = axis._mapper type = types[mapper.__class__]
| 476,430
|
def onUnit(self, unit): if isinstance(unit, int) or isinstance(unit, float): return unit return unit.tostring()
|
def onUnit(self, unit): if isinstance(unit, int) or isinstance(unit, float) or isinstance(unit, long): return unit return unit.tostring()
| 476,431
|
def addUploadBinariesStep(factory, binaries): for (local_name, remote_name) in binaries.items(): dst = WithProperties('public_html/binaries/' + remote_name + '.bz2', 'got_revision') factory.addStep(FileUpload(slavesrc=local_name, masterdest=dst, mode=0755))
|
def addUploadBinariesStep(factory, binaries): for (local_name, remote_name) in binaries.items(): dst = WithProperties('public_html/binaries/' + remote_name, 'got_revision') factory.addStep(FileUpload(slavesrc=local_name, masterdest=dst, mode=0755))
| 476,432
|
def get_date(s): dt = datetime.strptime(s, '%Y-%m-%d %H:%M:%S') dt -= timedelta(seconds=time.timezone) # sqlite seems to save at GMT... ata :P return pretty_date(dt) # found this online
|
def get_date(s): dt = datetime.strptime(s, '%Y-%m-%d %H:%M:%S') dt -= timedelta(seconds=time.timezone) # sqlite seems to save at GMT... ata :Preturn dt # found this online
| 476,433
|
def connect(self, thread_index): cherrypy.thread_data.db = sqlite3.connect('minitwit.sqlite') self.conn = cherrypy.thread_data.db self.c = self.conn.cursor()
|
def connect(self, thread_index): cherrypy.thread_data.db = sqlite3.connect('minitwit.sqlite') self.conn = cherrypy.thread_data.db self.c = self.conn.cursor()
| 476,434
|
def fetchone(self, query, args=()): self.c.execute(query, args) return self.c.fetchone()
|
def fetchone(self, query, args=()): c = self.get_cur() c.execute(query, args) return c.fetchone()
| 476,435
|
def fetchall(self, query, args=()): self.c.execute(query, args) return self.c.fetchalll()
|
def fetchall(self, query, args=()): c = self.get_cur() c.execute(query, args) return c.fetchall()
| 476,436
|
def query(self, query, args=()): self.c.execute(query, args) self.conn.commit()
|
def query(self, query, args=()): self.c.execute(query, args) self.conn.commit()
| 476,437
|
def login(self, username='', password='', redirect='/'): message = None if len(username) > 0 and len(password) > 0: conn = cherrypy.thread_data.db c = conn.cursor() c.execute("select rowid from users where username = ? and password = ?", (username, md5sum(password))) logged_in = c.fetchone() if logged_in is not None: cherrypy.session['logged_in'] = logged_in[0] raise cherrypy.HTTPRedirect(redirect) else: message = 'Invalid username/password' return templates.get_template('login.html').render(username=username, password=password, message=message)
|
def login(self, username='', password='', redirect='/'): message = None if len(username) > 0 and len(password) > 0: logged_in = db.fetchone("select rowid from users where username = ? and password = ?", (username, md5sum(password))) if logged_in is not None: cherrypy.session['logged_in'] = logged_in[0] raise cherrypy.HTTPRedirect(redirect) else: message = 'Invalid username/password' return templates.get_template('login.html').render(username=username, password=password, message=message)
| 476,438
|
def get_logged_in(self): try: rowid = cherrypy.session.get('logged_in') conn = cherrypy.thread_data.db c = conn.cursor() c.execute('select rowid, username from users where rowid = ?', (rowid,)) r = c.fetchone() return {'id': r[0], 'username': r[1]} except: return None
|
def get_logged_in(self): try: rowid = cherrypy.session.get('logged_in') r = db.fetchone('select rowid, username from users where rowid = ?', (rowid,)) return {'id': r[0], 'username': r[1]} except: return None
| 476,439
|
def default(self, id=None, text=None): logged_in = Session().get_logged_in() conn = cherrypy.thread_data.db c = conn.cursor() m = cherrypy.request.method
|
def default(self, id=None, text=None, last_update=None): logged_in = Session().get_logged_in() conn = cherrypy.thread_data.db c = conn.cursor() m = cherrypy.request.method
| 476,440
|
def default(self, id=None, text=None): logged_in = Session().get_logged_in() conn = cherrypy.thread_data.db c = conn.cursor() m = cherrypy.request.method
|
def default(self, id=None, text=None): logged_in = Session().get_logged_in() m = cherrypy.request.method
| 476,441
|
def default(self, id=None, text=None): logged_in = Session().get_logged_in() conn = cherrypy.thread_data.db c = conn.cursor() m = cherrypy.request.method
|
def default(self, id=None, text=None): logged_in = Session().get_logged_in() conn = cherrypy.thread_data.db c = conn.cursor() m = cherrypy.request.method
| 476,442
|
def default(self, id=None, text=None): logged_in = Session().get_logged_in() conn = cherrypy.thread_data.db c = conn.cursor() m = cherrypy.request.method
|
def default(self, id=None, text=None): logged_in = Session().get_logged_in() conn = cherrypy.thread_data.db c = conn.cursor() m = cherrypy.request.method
| 476,443
|
def default(self, id=None, text=None): logged_in = Session().get_logged_in() conn = cherrypy.thread_data.db c = conn.cursor() m = cherrypy.request.method
|
def default(self, id=None, text=None): logged_in = Session().get_logged_in() conn = cherrypy.thread_data.db c = conn.cursor() m = cherrypy.request.method
| 476,444
|
def index(self): logged_in = Session().get_logged_in() conn = cherrypy.thread_data.db c = conn.cursor() c.execute('select posts.rowid, text, date, username from posts join users on posts.user = users.rowid order by date desc limit 10') posts = [{'id': r[0], 'text': r[1], 'date': get_date(r[2]), 'username': r[3]} for r in c.fetchall()] return templates.get_template('dashboard.html').render(logged_in=logged_in, posts=posts)
|
def index(self): logged_in = Session().get_logged_in() conn = cherrypy.thread_data.db c = conn.cursor() posts = db.fetchall('select posts.rowid, text, date, username from posts join users on posts.user = users.rowid order by date desc limit 10') posts = [{'id': r[0], 'text': r[1], 'date': pretty_date(get_date(r[2])), 'username': r[3]} for r in posts] return templates.get_template('dashboard.html').render(logged_in=logged_in, posts=posts)
| 476,445
|
def register(self, username='', password='', conf_password=''): message = None if len(username) > 0 and len(password) > 0 and password == conf_password: c.execute('insert into users values (?, ?)', username, md5sum(password)) conn.commit() raise cherrypy.HTTPRedirect('/session/login') elif password != conf_password: message = "Passwords don't match" return templates.get_template('register.html').render(username=username, password=password, conf_password=conf_password, message=message)
|
def register(self, username='', password='', conf_password=''): message = None if len(username) > 0 and len(password) > 0 and password == conf_password: db.query('insert into users values (?, ?)', (username, md5sum(password))) raise cherrypy.HTTPRedirect('/session/login') elif password != conf_password: message = "Passwords don't match" return templates.get_template('register.html').render(username=username, password=password, conf_password=conf_password, message=message)
| 476,446
|
def install(self): conn = cherrypy.thread_data.db c = conn.cursor() c.execute("drop table if exists users") c.execute("drop table if exists posts") c.execute("create table users (username text, password text)") c.execute("create unique index username on users (username)") c.execute("create table posts (user int, text text, date text)") c.execute("create index user on posts (user)") c.execute("insert into users values (?, ?)", ('demo', md5sum('demo'))) c.execute("insert into posts values (?, ?, datetime('now'))", (1, 'Hello world')) conn.commit() return "Tables created!"
|
def install(self): db.query("drop table if exists users") db.query("drop table if exists posts") db.query("create table users (username text, password text)") db.query("create unique index username on users (username)") db.query("create table posts (user int, text text, date text)") db.query("create index user on posts (user)") db.query("insert into users values (?, ?)", ('demo', md5sum('demo'))) db.query("insert into posts values (?, ?, datetime('now'))", (1, 'Hello world')) return "Tables created!"
| 476,447
|
def getRequirements(self, jobNum): reqs = Module.getRequirements(self, jobNum) if self.dataSplitter != None: reqs.append((WMS.STORAGE, self.dataSplitter.getSplitInfo(jobNum)[DataSplitter.SEList])) return reqs
|
def getRequirements(self, jobNum): reqs = Module.getRequirements(self, jobNum) if self.dataSplitter != None: reqs.append((WMS.STORAGE, self.dataSplitter.getSplitInfo(jobNum).get(DataSplitter.SEList))) return reqs
| 476,448
|
def canSubmit(self, jobNum): if self.checkSE and (self.dataSplitter != None): return self.dataSplitter.getSplitInfo(jobNum)[DataSplitter.SEList] != [] return True
|
def canSubmit(self, jobNum): if self.checkSE and (self.dataSplitter != None): return self.dataSplitter.getSplitInfo(jobNum).get(DataSplitter.SEList) != [] return True
| 476,449
|
def splitLumiRanges(lumis, off = 0, singlemode = False): # Split into single runs (todel, toadd) = (set(), set()) for (s, e) in lumis: if s[0] and e[0] and s[0] != e[0]: todel.add((s, e)) toadd.add((s, (s[0],None))) toadd.add(((e[0],1),e)) for x in range(s[0] + 1, e[0]): toadd.add(((x, 1), (x, None))) lumis.difference_update(todel) lumis.update(toadd)
|
def splitLumiRanges(lumis, off = 0, singlemode = False): # Split into single runs (todel, toadd) = (set(), set()) for (s, e) in lumis: if s[0] and e[0] and s[0] != e[0]: todel.add((s, e)) toadd.add((s, (s[0],None))) toadd.add(((e[0],1),e)) for x in range(s[0] + 1, e[0]): toadd.add(((x, 1), (x, None))) lumis.difference_update(todel) lumis.update(toadd)
| 476,450
|
def splitLumiRanges(lumis, off = 0, singlemode = False): # Split into single runs (todel, toadd) = (set(), set()) for (s, e) in lumis: if s[0] and e[0] and s[0] != e[0]: todel.add((s, e)) toadd.add((s, (s[0],None))) toadd.add(((e[0],1),e)) for x in range(s[0] + 1, e[0]): toadd.add(((x, 1), (x, None))) lumis.difference_update(todel) lumis.update(toadd)
|
def splitLumiRanges(lumis, off = 0, singlemode = False): # Split into single runs (todel, toadd) = (set(), set()) for (s, e) in lumis: if s[0] and e[0] and s[0] != e[0]: todel.add((s, e)) toadd.add((s, (s[0],None))) toadd.add(((e[0],1),e)) for x in range(s[0] + 1, e[0]): toadd.add(((x, 1), (x, None))) lumis.difference_update(todel) lumis.update(toadd)
| 476,451
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
| 476,452
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
| 476,453
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
| 476,454
|
def parseJobState(self, state): if True in map(lambda x in state, ['h', 's', 'S', 'T', 'w']): return Job.QUEUED if True in map(lambda x in state, ['r', 't']): return Job.RUNNING return Job.READY
|
def parseJobState(self, state): if True in map(lambda x: x in state, ['h', 's', 'S', 'T', 'w']): return Job.QUEUED if True in map(lambda x in state, ['r', 't']): return Job.RUNNING return Job.READY
| 476,455
|
def parseJobState(self, state): if True in map(lambda x in state, ['h', 's', 'S', 'T', 'w']): return Job.QUEUED if True in map(lambda x in state, ['r', 't']): return Job.RUNNING return Job.READY
|
def parseJobState(self, state): if True in map(lambda x in state, ['h', 's', 'S', 'T', 'w']): return Job.QUEUED if True in map(lambda x: x in state, ['r', 't']): return Job.RUNNING return Job.READY
| 476,456
|
def isInstrumented(cfgName): cfg = open(cfgName, 'r').read() for tag in [ "FILE_NAMES", "MAX_EVENTS", "SKIP_EVENTS" ]: if (not "__%s__" % tag in cfg) and (not "@%s@" % tag in cfg): return False return True
|
def isInstrumented(cfgName): cfg = open(cfgName, 'r').read() for tag in [ "FILE_NAMES", "MAX_EVENTS", "SKIP_EVENTS" ]: if (not "__%s__" % tag in cfg) and (not "@%s@" % tag in cfg): return False return True
| 476,457
|
def __init__(self, config, module, submodules): Monitoring.__init__(self, config, module) submodules = map(str.strip, submodules.split(",")) self.submodules = map(lambda x: Monitoring.open(x, config, module), submodules)
|
def __init__(self, config, module, submodules): Monitoring.__init__(self, config, module) submodules = filter(lambda x: x != '', map(str.strip, submodules.split(","))) self.submodules = map(lambda x: Monitoring.open(x, config, module), submodules)
| 476,458
|
def __init__(self, config, datasetExpr, datasetNick, datasetID = 0): DataProvider.__init__(self, config, datasetExpr, datasetNick, datasetID) DataProvider.providers.update({'DBSApiv2': 'dbs'}) if config.getBool('CMSSW', 'dbs blacklist T1', True): T1SEs = ["-srmcms.pic.es", "-ccsrm.in2p3.fr", "-storm-fe-cms.cr.cnaf.infn.it", "-srm-cms.gridpp.rl.ac.uk", "-srm.grid.sinica.edu.tw", "-srm2.grid.sinica.edu.tw"] self.sitefilter.extend(T1SEs)
|
def __init__(self, config, datasetExpr, datasetNick, datasetID = 0): DataProvider.__init__(self, config, datasetExpr, datasetNick, datasetID) DataProvider.providers.update({'DBSApiv2': 'dbs'}) if config.getBool('CMSSW', 'dbs blacklist T1', True): T1SEs = ["-srmcms.pic.es", "-ccsrm.in2p3.fr", "-storm-fe-cms.cr.cnaf.infn.it", "-srm-cms.gridpp.rl.ac.uk", "-srm.grid.sinica.edu.tw", "-srm2.grid.sinica.edu.tw"] self.sitefilter.extend(T1SEs)
| 476,459
|
def __init__(self, config, datasetExpr, datasetNick, datasetID = 0): DataProvider.__init__(self, config, datasetExpr, datasetNick, datasetID) DataProvider.providers.update({'DBSApiv2': 'dbs'}) if config.getBool('CMSSW', 'dbs blacklist T1', True): T1SEs = ["-srmcms.pic.es", "-ccsrm.in2p3.fr", "-storm-fe-cms.cr.cnaf.infn.it", "-srm-cms.gridpp.rl.ac.uk", "-srm.grid.sinica.edu.tw", "-srm2.grid.sinica.edu.tw"] self.sitefilter.extend(T1SEs)
|
def __init__(self, config, datasetExpr, datasetNick, datasetID = 0): DataProvider.__init__(self, config, datasetExpr, datasetNick, datasetID) DataProvider.providers.update({'DBSApiv2': 'dbs'}) if config.getBool('CMSSW', 'dbs blacklist T1', True): T1SEs = ["-srmcms.pic.es", "-ccsrm.in2p3.fr", "-storm-fe-cms.cr.cnaf.infn.it", "-srm-cms.gridpp.rl.ac.uk", "-srm.grid.sinica.edu.tw", "-srm2.grid.sinica.edu.tw"] self.sitefilter.extend(T1SEs)
| 476,460
|
def lumiFilter(lfn): for lumi in listLumiInfo[lfn]: if selectLumi(lumi, self.selectedLumis): return True return self.selectedLumis == None
|
def lumiFilter(lfn): for lumi in listLumiInfo[lfn]: if selectLumi(lumi, self.selectedLumis): return True return self.selectedLumis == None
| 476,461
|
def outputJSON(lumis, stream = sys.stdout): tmp = {} for rlrange in lumis: start, end = rlrange if start[0] != end[0]: raise if start[0] not in tmp: tmp[start[0]] = [] tmp[start[0]].append([start[1], end[1]]) stream.write("{\n") entries = map(lambda run: '\t"%d": %s' % (run, tmp[run]), sorted(tmp.keys())) stream.write("%s\n" % str.join(',\n', entries)) stream.write("}\n")
|
def outputJSON(lumis, stream = sys.stdout): tmp = {} for rlrange in lumis: start, end = rlrange if start[0] != end[0]: raise if start[0] not in tmp: tmp[start[0]] = [] tmp[start[0]].append([start[1], end[1]]) stream.write("{\n") entries = map(lambda run: '\t"%d": %s' % (run, tmp[run]), sorted(tmp.keys())) stream.write("%s\n" % str.join(',\n', entries)) stream.write("}\n")
| 476,462
|
def outputJSON(lumis, stream = sys.stdout): tmp = {} for rlrange in lumis: start, end = rlrange if start[0] != end[0]: raise if start[0] not in tmp: tmp[start[0]] = [] tmp[start[0]].append([start[1], end[1]]) stream.write("{\n") entries = map(lambda run: '\t"%d": %s' % (run, tmp[run]), sorted(tmp.keys())) stream.write("%s\n" % str.join(',\n', entries)) stream.write("}\n")
|
def outputJSON(lumis, stream = sys.stdout): tmp = {} for rlrange in lumis: start, end = rlrange if start[0] != end[0]: raise if start[0] not in tmp: tmp[start[0]] = [] tmp[start[0]].append([start[1], end[1]]) stream.write("{\n") entries = map(lambda run: '\t"%d": %s' % (run, tmp[run]), sorted(tmp.keys())) stream.write("%s\n" % str.join(',\n', entries)) stream.write("}\n")
| 476,463
|
def outputJSON(lumis, stream = sys.stdout): tmp = {} for rlrange in lumis: start, end = rlrange if start[0] != end[0]: raise if start[0] not in tmp: tmp[start[0]] = [] tmp[start[0]].append([start[1], end[1]]) stream.write("{\n") entries = map(lambda run: '\t"%d": %s' % (run, tmp[run]), sorted(tmp.keys())) stream.write("%s\n" % str.join(',\n', entries)) stream.write("}\n")
|
def outputJSON(lumis, stream = sys.stdout): tmp = {} for rlrange in lumis: start, end = rlrange if start[0] != end[0]: raise if start[0] not in tmp: tmp[start[0]] = [] tmp[start[0]].append([start[1], end[1]]) stream.write("{\n") entries = map(lambda run: '\t"%d": %s' % (run, tmp[run]), sorted(tmp.keys())) stream.write("%s\n" % str.join(',\n', entries)) stream.write("}\n")
| 476,464
|
def se_runcmd(cmd, varDict = {}, *urls): runLib = utils.pathGC('share', 'gc-run.lib') args = str.join(' ', map(lambda x: '"%s"' % ensurePrefix(x).replace('dir://', 'file://'), urls)) varString = str.join(' ', map(lambda x: 'export %s="%s";' % (x, varDict[x]), varDict)) return utils.LoggedProcess('source %s || exit 1; %s %s %s' % (runLib, varString, cmd, args))
|
def se_runcmd(cmd, varDict = {}, *urls): runLib = utils.pathGC('share', 'gc-run.lib') args = str.join(' ', map(lambda x: '"%s"' % ensurePrefix(x).replace('dir://', 'file:////'), urls)) varString = str.join(' ', map(lambda x: 'export %s="%s";' % (x, varDict[x]), varDict)) return utils.LoggedProcess('source %s || exit 1; %s %s %s' % (runLib, varString, cmd, args))
| 476,465
|
def getSubmitArguments(self, jobNum, sandbox, stdout, stderr): # Restart jobs = no, job name params = ' -r n -N %s' % self.wms.getJobName(jobNum)
|
def getSubmitArguments(self, jobNum, sandbox, stdout, stderr): # Restart jobs = no, job name params = ' -r n -N %s' % self.wms.getJobName(jobNum)
| 476,466
|
def getFiles(self): for file in ('DashboardAPI.py', 'Logger.py', 'ProcInfo.py', 'apmon.py', 'report.py'): yield utils.pathGC('python', 'grid_control_cms', 'share', 'DashboardAPI', file)
|
def getFiles(self): for file in ('DashboardAPI.py', 'Logger.py', 'ProcInfo.py', 'apmon.py', 'report.py'): yield utils.pathGC('python', 'grid_control_cms', 'share', 'DashboardAPI', file)
| 476,467
|
def __init__(self, config, module, monitor): WMS.__init__(self, config, module, monitor, 'local')
|
def __init__(self, config, module, monitor): WMS.__init__(self, config, module, monitor, 'local')
| 476,468
|
def getOutputDatasets(opts): # Get job numbers, task id, ... log = utils.ActivityLog(' * Reading task info...') jobList = utils.sorted(map(lambda (jobNum, path): jobNum, Job.readJobs(opts.workDir))) taskInfo = utils.PersistentDict(os.path.join(opts.workDir, 'task.dat'), ' = ') del log print " * Reading task info - done" # Get all config and output data log = None configData = {} outputData = {} dbsLog = utils.PersistentDict(os.path.join(opts.workDir, 'dbs.log'), ' = ', False) for jobNum in jobList: if jobNum % 10 == 0: del log log = utils.ActivityLog(' * Reading job logs - [%d / %d]' % (jobNum, jobList[-1])) (output, config) = readDBSJobInfo(opts, opts.workDir, jobNum) # ignore already registed files in incremental mode for lfn in filter(lambda x: not (opts.incremental and x in dbsLog), output): outputData.update({lfn: output[lfn]}) configData.update(config) print " * Reading job logs - done" # Merge parent infos into output file data if os.path.exists(os.path.join(opts.workDir, 'datacache.dat')): # Get parent infos provider = DataProvider.loadState(Config(), opts.workDir, 'datacache.dat') log = utils.ActivityLog(' * Processing parent infos...') blocks = provider.getBlocks() parentMap = {} for block in blocks: blockInfo = (block[DataProvider.Dataset], block[DataProvider.BlockName]) lfns = map(lambda x: (x[DataProvider.lfn], blockInfo), block[DataProvider.FileList]) parentMap.update(dict(lfns)) # Insert parentage infos for lfn in outputData.keys(): for parentLFN in filter(lambda x: x, outputData[lfn][DBS.PARENT_FILES]): if not DBS.PARENT_INFO in outputData[lfn]: outputData[lfn][DBS.PARENT_INFO] = [] if not parentMap[parentLFN] in outputData[lfn][DBS.PARENT_INFO]: outputData[lfn][DBS.PARENT_INFO].append(parentMap[parentLFN]) del log print " * Processing parent infos - done" # Sort output files into blocks log = None metadata = {} datasets = {} datasetInfos = {} for idx, lfn in enumerate(outputData): if idx % 10 == 0: del log log = utils.ActivityLog(' * Dividing output into blocks - [%d / %d]' % (idx, len(outputData))) # Define dataset split criteria def generateDatasetKey(fileInfo): # Split by dataset parent and config hash (+ job config hash) parentDS = map(lambda (ds, b): ds, fileInfo.get(DBS.PARENT_INFO, [])) jobHash = ('', str(fileInfo[DBS.JOBHASH]))[opts.useJobHash] dsKey = utils.md5(str((fileInfo[DBS.CONFIGHASH], jobHash, parentDS))).hexdigest() # Write summary information: if not dsKey in datasetInfos: if parentDS == []: parentDS = ['None'] datasetInfos[dsKey] = ("%15s: %s\n%15s: %s\n" % ( "Config hash", fileInfo[DBS.CONFIGHASH], "Parent datasets", str.join("\n" + 17*" ", parentDS))) annotation = getAnnotation(fileInfo[DBS.CONFIGHASH], configData) if annotation: datasetInfos[dsKey] += "%15s: %s\n" % ("Annotation", annotation) return dsKey # Define block split criteria def generateBlockKey(fileInfo): # Split by SE and block parent (parent is left out in case of merging) key = utils.md5(str(fileInfo[DBS.SE]) + generateDatasetKey(fileInfo)) if not opts.doMerge: key.update(str(map(lambda (ds, b): b, fileInfo.get(DBS.PARENT_INFO, [])))) return key.hexdigest() dsKey = generateDatasetKey(outputData[lfn]) blockKey = generateBlockKey(outputData[lfn]) if not dsKey in datasets: datasets[dsKey] = {} metadata[dsKey] = {DBS.SIZE: 0, DBS.EVENTS: 0} if not blockKey in datasets[dsKey]: datasets[dsKey][blockKey] = [] metadata[blockKey] = {DBS.SIZE: 0, DBS.EVENTS: 0} # Calculate def incStats(x, info): x[DBS.SIZE] += int(info[DBS.SIZE]) x[DBS.EVENTS] += int(info[DBS.EVENTS]) incStats(metadata[dsKey], outputData[lfn]) incStats(metadata[blockKey], outputData[lfn]) datasets[dsKey][blockKey].append(lfn) print " * Dividing output into blocks - done" # Display dataset information print print " => Identified the following output datasets:" for ds in datasets.keys(): print "%4s * Key %s [%d block(s), %d file(s)]" % ("", ds, len(datasets[ds]), sum(map(len, datasets[ds].values()))) print 7*" " + datasetInfos[ds].replace("\n", "\n" + 7*" ") return (taskInfo['task id'], datasets, metadata, outputData, configData)
|
def getOutputDatasets(opts): # Get job numbers, task id, ... log = utils.ActivityLog(' * Reading task info...') jobList = utils.sorted(map(lambda (jobNum, path): jobNum, Job.readJobs(os.path.join(opts.workDir, 'jobs')))) taskInfo = utils.PersistentDict(os.path.join(opts.workDir, 'task.dat'), ' = ') del log print " * Reading task info - done" # Get all config and output data log = None configData = {} outputData = {} dbsLog = utils.PersistentDict(os.path.join(opts.workDir, 'dbs.log'), ' = ', False) for jobNum in jobList: if jobNum % 10 == 0: del log log = utils.ActivityLog(' * Reading job logs - [%d / %d]' % (jobNum, jobList[-1])) (output, config) = readDBSJobInfo(opts, opts.workDir, jobNum) # ignore already registed files in incremental mode for lfn in filter(lambda x: not (opts.incremental and x in dbsLog), output): outputData.update({lfn: output[lfn]}) configData.update(config) print " * Reading job logs - done" # Merge parent infos into output file data if os.path.exists(os.path.join(opts.workDir, 'datacache.dat')): # Get parent infos provider = DataProvider.loadState(Config(), opts.workDir, 'datacache.dat') log = utils.ActivityLog(' * Processing parent infos...') blocks = provider.getBlocks() parentMap = {} for block in blocks: blockInfo = (block[DataProvider.Dataset], block[DataProvider.BlockName]) lfns = map(lambda x: (x[DataProvider.lfn], blockInfo), block[DataProvider.FileList]) parentMap.update(dict(lfns)) # Insert parentage infos for lfn in outputData.keys(): for parentLFN in filter(lambda x: x, outputData[lfn][DBS.PARENT_FILES]): if not DBS.PARENT_INFO in outputData[lfn]: outputData[lfn][DBS.PARENT_INFO] = [] if not parentMap[parentLFN] in outputData[lfn][DBS.PARENT_INFO]: outputData[lfn][DBS.PARENT_INFO].append(parentMap[parentLFN]) del log print " * Processing parent infos - done" # Sort output files into blocks log = None metadata = {} datasets = {} datasetInfos = {} for idx, lfn in enumerate(outputData): if idx % 10 == 0: del log log = utils.ActivityLog(' * Dividing output into blocks - [%d / %d]' % (idx, len(outputData))) # Define dataset split criteria def generateDatasetKey(fileInfo): # Split by dataset parent and config hash (+ job config hash) parentDS = map(lambda (ds, b): ds, fileInfo.get(DBS.PARENT_INFO, [])) jobHash = ('', str(fileInfo[DBS.JOBHASH]))[opts.useJobHash] dsKey = utils.md5(str((fileInfo[DBS.CONFIGHASH], jobHash, parentDS))).hexdigest() # Write summary information: if not dsKey in datasetInfos: if parentDS == []: parentDS = ['None'] datasetInfos[dsKey] = ("%15s: %s\n%15s: %s\n" % ( "Config hash", fileInfo[DBS.CONFIGHASH], "Parent datasets", str.join("\n" + 17*" ", parentDS))) annotation = getAnnotation(fileInfo[DBS.CONFIGHASH], configData) if annotation: datasetInfos[dsKey] += "%15s: %s\n" % ("Annotation", annotation) return dsKey # Define block split criteria def generateBlockKey(fileInfo): # Split by SE and block parent (parent is left out in case of merging) key = utils.md5(str(fileInfo[DBS.SE]) + generateDatasetKey(fileInfo)) if not opts.doMerge: key.update(str(map(lambda (ds, b): b, fileInfo.get(DBS.PARENT_INFO, [])))) return key.hexdigest() dsKey = generateDatasetKey(outputData[lfn]) blockKey = generateBlockKey(outputData[lfn]) if not dsKey in datasets: datasets[dsKey] = {} metadata[dsKey] = {DBS.SIZE: 0, DBS.EVENTS: 0} if not blockKey in datasets[dsKey]: datasets[dsKey][blockKey] = [] metadata[blockKey] = {DBS.SIZE: 0, DBS.EVENTS: 0} # Calculate def incStats(x, info): x[DBS.SIZE] += int(info[DBS.SIZE]) x[DBS.EVENTS] += int(info[DBS.EVENTS]) incStats(metadata[dsKey], outputData[lfn]) incStats(metadata[blockKey], outputData[lfn]) datasets[dsKey][blockKey].append(lfn) print " * Dividing output into blocks - done" # Display dataset information print print " => Identified the following output datasets:" for ds in datasets.keys(): print "%4s * Key %s [%d block(s), %d file(s)]" % ("", ds, len(datasets[ds]), sum(map(len, datasets[ds].values()))) print 7*" " + datasetInfos[ds].replace("\n", "\n" + 7*" ") return (taskInfo['task id'], datasets, metadata, outputData, configData)
| 476,469
|
def cmpLumi(a,b): (start_a_run, start_a_lumi) = a[0] (start_b_run, start_b_lumi) = b[0] if start_a_run == start_b_run: return cmp(start_a_lumi, start_b_lumi) else: return cmp(start_a_run, start_b_run)
|
def cmpLumi(a,b): (start_a_run, start_a_lumi) = a[0] (start_b_run, start_b_lumi) = b[0] if start_a_run == start_b_run: return cmp(start_a_lumi, start_b_lumi) else: return cmp(start_a_run, start_b_run)
| 476,470
|
def processShorthand(optSet): if optSet: parser.parse_args(args = optSet.split() + sys.argv[1:], values = opts)
|
defrealmain(opts, args) processShorthand(optSet):realmain(opts, args) ifrealmain(opts, args) optSet:realmain(opts, args) parser.parse_args(argsrealmain(opts, args) =realmain(opts, args) optSet.split()realmain(opts, args) +realmain(opts, args) sys.argv[1:],realmain(opts, args) valuesrealmain(opts, args) =realmain(opts, args) opts)
| 476,471
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
| 476,472
|
def __init__(self, config, datasetExpr, datasetNick, datasetID = 0): DataProvider.__init__(self, config, datasetExpr, datasetNick, datasetID) DataProvider.providers.update({'DBSApiv2': 'dbs'})
|
def __init__(self, config, datasetExpr, datasetNick, datasetID = 0): DataProvider.__init__(self, config, datasetExpr, datasetNick, datasetID) DataProvider.providers.update({'DBSApiv2': 'dbs'})
| 476,473
|
def __init__(self, config, module, monitor): wmsapi = config.get('local', 'wms', self._guessWMS()) if wmsapi != self._guessWMS(): utils.vprint('Default batch system on this host is: %s' % self._guessWMS(), -1, once = True) self.api = LocalWMSApi.open(wmsapi, config, self) utils.vprint('Using batch system: %s' % self.api.__class__.__name__, -1) self.addAttr = {} if config.parser.has_section(wmsapi): self.addAttr = dict(map(lambda item: (item, config.get(wmsapi, item)), config.parser.options(wmsapi)))
|
def __init__(self, config, module, monitor): wmsapi = config.get('local', 'wms', self._guessWMS()) if wmsapi != self._guessWMS(): utils.vprint('Default batch system on this host is: %s' % self._guessWMS(), -1, once = True) self.api = LocalWMSApi.open(wmsapi, config, self) utils.vprint('Using batch system: %s' % self.api.__class__.__name__, -1) self.addAttr = {} if config.parser.has_section(wmsapi): self.addAttr = dict(map(lambda item: (item, config.get(wmsapi, item)), config.parser.options(wmsapi)))
| 476,474
|
def getSubmissionJobs(self, maxsample): # Determine number of jobs to submit submit = self.nJobs nQueued = len(self.queued) if self.inQueue > 0: submit = min(submit, self.inQueue - nQueued) if self.inFlight > 0: submit = min(submit, self.inFlight - nQueued - len(self.running)) if self.config.opts.continuous: submit = min(submit, maxsample) submit = max(submit, 0)
|
def getSubmissionJobs(self, maxsample): # Determine number of jobs to submit submit = self.nJobs nQueued = len(self.queued) if self.inQueue > 0: submit = min(submit, self.inQueue - nQueued) if self.inFlight > 0: submit = min(submit, self.inFlight - nQueued - len(self.running)) if self.config.opts.continuous: submit = min(submit, maxsample) submit = max(submit, 0)
| 476,475
|
def main(args): help = \
|
def main(args): help = \
| 476,476
|
def main(args): help = \
|
def main(args): help = \
| 476,477
|
def processShorthand(optSet): if optSet: parser.parse_args(args = optSet.split() + sys.argv[1:], values = opts)
|
def processShorthand(optSet): if optSet: parser.parse_args(args = optSet.split() + sys.argv[1:], values = opts)
| 476,478
|
def dlfs_rm(path, msg): procRM = se_utils.se_rm(path) if procRM.wait() != 0: print "\t\tUnable to remove %s!" % msg utils.eprint(procRM.getMessage())
|
def dlfs_rm(path, msg): procRM = se_utils.se_rm(path) if procRM.wait() != 0: print "\t\tUnable to remove %s!" % msg utils.eprint("%s\n\n" % procRM.getMessage())
| 476,479
|
def processSingleJob(jobNum): print "Job %d:" % jobNum,
|
def processSingleJob(jobNum): print "Job %d:" % jobNum,
| 476,480
|
def processSingleJob(jobNum): print "Job %d:" % jobNum,
|
def processSingleJob(jobNum): print "Job %d:" % jobNum,
| 476,481
|
def customise_for_gc(process): try: maxevents = __MAX_EVENTS__ process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(maxevents) ) except: pass # Dataset related setup try: tmp = __SKIP_EVENTS__ process.source = cms.Source("PoolSource", skipEvents = cms.untracked.uint32(__SKIP_EVENTS__), fileNames = cms.untracked.vstring(__FILE_NAMES__) ) try: secondary = __FILE_NAMES2__ process.source.secondaryFileNames = cms.untracked.vstring(secondary) except: pass try: lumirange = __LUMI_RANGE__ process.source.lumisToProcess = cms.untracked.VLuminosityBlockRange(lumirange) except: pass except: pass # Generator related setup try: if hasattr(process, "generator"): process.source.firstLuminosityBlock = cms.untracked.uint32(1+__MY_JOBID__) except: pass if hasattr(process, "RandomNumberGeneratorService"): randSvc = RandomNumberServiceHelper(process.RandomNumberGeneratorService) randSvc.populate() process.AdaptorConfig = cms.Service("AdaptorConfig", enable=cms.untracked.bool(True), stats = cms.untracked.bool(True), ) return (process)
|
def customise_for_gc(process): try: maxevents = __MAX_EVENTS__ process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(maxevents) ) except: pass # Dataset related setup try: tmp = __SKIP_EVENTS__ process.source = cms.Source("PoolSource", skipEvents = cms.untracked.uint32(__SKIP_EVENTS__), fileNames = cms.untracked.vstring(__FILE_NAMES__) ) try: secondary = __FILE_NAMES2__ process.source.secondaryFileNames = cms.untracked.vstring(secondary) except: pass try: lumirange = [__LUMI_RANGE__] process.source.lumisToProcess = cms.untracked.VLuminosityBlockRange(lumirange) except: pass except: pass # Generator related setup try: if hasattr(process, "generator"): process.source.firstLuminosityBlock = cms.untracked.uint32(1+__MY_JOBID__) except: pass if hasattr(process, "RandomNumberGeneratorService"): randSvc = RandomNumberServiceHelper(process.RandomNumberGeneratorService) randSvc.populate() process.AdaptorConfig = cms.Service("AdaptorConfig", enable=cms.untracked.bool(True), stats = cms.untracked.bool(True), ) return (process)
| 476,482
|
def __init__(self, config, module, monitor): wmsapi = config.get('local', 'wms', self._guessWMS()) if wmsapi != self._guessWMS(): utils.vprint('Default batch system on this host is: %s' % self._guessWMS(), -1, once = True) self.api = LocalWMSApi.open(wmsapi, config, self) utils.vprint('Using batch system: %s' % self.api.__class__.__name__, -1) self.addAttr = {} if config.parser.has_section(wmsapi): self.addAttr = dict(map(lambda item: (item, config.get(wmsapi, item)), config.parser.options(wmsapi)))
|
def __init__(self, config, module, monitor): wmsapi = config.get('local', 'wms', self._guessWMS()) if wmsapi != self._guessWMS(): utils.vprint('Default batch system on this host is: %s' % self._guessWMS(), -1, once = True) self.api = LocalWMSApi.open(wmsapi, config, self) utils.vprint('Using batch system: %s' % self.api.__class__.__name__, -1) self.addAttr = {} if config.parser.has_section(wmsapi): self.addAttr = dict(map(lambda item: (item, config.get(wmsapi, item)), config.parser.options(wmsapi)))
| 476,483
|
def getBlocksInternal(self): import urllib2 api = createDBSAPI(self.url) try: listBlockInfo = api.listBlocks(self.datasetPath, nosite=True) # Start thread to retrieve list of files (listFileInfo, seList) = ([], {}) def listFileInfoThread(self, result): result.extend(api.listFiles(self.datasetPath, retriveList=QM(self.selectedLumis, ['retrive_lumi'], []))) tFile = utils.gcStartThread(listFileInfoThread, self, listFileInfo) # Get dataset list from PhEDex (concurrent with listFiles) phedexArgFmt = lambda x: ('block=%s' % x['Name']).replace('/', '%2F').replace('#', '%23') phedexArg = str.join('&', map(phedexArgFmt, listBlockInfo)) phedexData = urllib2.urlopen('https://cmsweb.cern.ch/phedex/datasvc/json/prod/blockreplicas', phedexArg).read() if str(phedexData).lower().find('error') != -1: raise DatasetError("Phedex error '%s'" % phedexData) phedexDict = eval(compile(phedexData.replace('null','None'), '<string>', 'eval'))['phedex']['block'] for phedexBlock in phedexDict: phedexSelector = lambda x: (x['complete'] == 'y') or not self.onlyComplete phedexSites = dict(map(lambda x: (x['node'], x['se']), filter(phedexSelector, phedexBlock['replica']))) phedexSitesOK = utils.doBlackWhiteList(phedexSites.keys(), self.phedexBL) seList[phedexBlock['name']] = map(lambda x: phedexSites[x], phedexSitesOK) tFile.join() except: raise RethrowError('DBS exception')
|
def getBlocksInternal(self): import urllib2 api = createDBSAPI(self.url) try: listBlockInfo = api.listBlocks(self.datasetPath, nosite=True) # Start thread to retrieve list of files (listFileInfo, seList) = ([], {}) def listFileInfoThread(self, result): result.extend(api.listFiles(self.datasetPath, retriveList=QM(self.selectedLumis, ['retrive_lumi'], []))) tFile = utils.gcStartThread(listFileInfoThread, self, listFileInfo) # Get dataset list from PhEDex (concurrent with listFiles) phedexArgFmt = lambda x: ('block=%s' % x['Name']).replace('/', '%2F').replace('#', '%23') phedexArg = str.join('&', map(phedexArgFmt, listBlockInfo)) phedexData = urllib2.urlopen('https://cmsweb.cern.ch/phedex/datasvc/json/prod/blockreplicas', phedexArg).read() if str(phedexData).lower().find('error') != -1: raise DatasetError("Phedex error '%s'" % phedexData) phedexDict = eval(compile(phedexData.replace('null','None'), '<string>', 'eval'))['phedex']['block'] for phedexBlock in phedexDict: phedexSelector = lambda x: (x['complete'] == 'y') or not self.onlyComplete phedexSites = dict(map(lambda x: (x['node'], x['se']), filter(phedexSelector, phedexBlock['replica']))) phedexSitesOK = utils.doBlackWhiteList(phedexSites.keys(), self.phedexBL) seList[phedexBlock['name']] = map(lambda x: phedexSites[x], phedexSitesOK) tFile.join() except: raise RethrowError('DBS exception')
| 476,484
|
def lumiFilter(lumilist): if self.selectedLumis: for lumi in lumilist: if selectLumi((lumi['RunNumber'], lumi['LumiSectionNumber']), self.selectedLumis): return True return self.selectedLumis == None
|
def lumiFilter(lumilist): if self.selectedLumis: for lumi in lumilist: if selectLumi((lumi['RunNumber'], lumi['LumiSectionNumber']), self.selectedLumis): return True return self.selectedLumis == None
| 476,485
|
def getSubmitArguments(self, jobNum, sandbox, stdout, stderr, addAttr): # Job name params = ' -J %s' % self.wms.getJobName(jobNum) # Job requirements reqs = dict(self.wms.getRequirements(jobNum)) if WMS.SITES in reqs: params += ' -q %s' % reqs[WMS.SITES][0] if WMS.WALLTIME in reqs: params += ' -c %d' % ((reqs[WMS.WALLTIME] + 59) / 60) # IO paths params += ' -o %s -e %s' % (stdout, stderr) return params
|
def getSubmitArguments(self, jobNum, sandbox, stdout, stderr, addAttr): # Job name params = ' -J %s' % self.wms.getJobName(jobNum) # Job requirements reqs = dict(self.wms.getRequirements(jobNum)) if WMS.SITES in reqs: params += ' -q %s' % reqs[WMS.SITES][0] if WMS.WALLTIME in reqs: params += ' -W %d' % ((reqs[WMS.WALLTIME] + 59) / 60) if WMS.CPUTIME in reqs: params += ' -c %d' % ((reqs[WMS.CPUTIME] + 59) / 60) # IO paths params += ' -o %s -e %s' % (stdout, stderr) return params
| 476,486
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
| 476,487
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
| 476,488
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
| 476,489
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
| 476,490
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
| 476,491
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
| 476,492
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
| 476,493
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
| 476,494
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
| 476,495
|
def parseFileInt(fn): try: parser.readfp(open(fn, 'r')) except IOError: raise ConfigError("Error while reading configuration file '%s'!" % fn) except cp.Error: print "Configuration file `%s' contains an error:" % fn raise
|
def parseFileInt(fn): try: parser.readfp(open(fn, 'r')) except IOError: raise ConfigError("Error while reading configuration file '%s'!" % fn) except cp.Error: print "Configuration file `%s' contains an error:" % fn raise
| 476,496
|
def se_runcmd(cmd, varDict = {}, *urls): runLib = utils.pathGC('share', 'gc-run.lib') args = str.join(' ', map(lambda x: '"%s"' % ensurePrefix(x).replace('dir://', 'file:////'), urls)) varString = str.join(' ', map(lambda x: 'export %s="%s";' % (x, varDict[x]), varDict)) return utils.LoggedProcess('source %s || exit 1; %s %s %s' % (runLib, varString, cmd, args))
|
def se_runcmd(cmd, varDict = {}, *urls): runLib = utils.pathGC('share', 'gc-run.lib') args = str.join(' ', map(lambda x: '"%s"' % ensurePrefix(x).replace('dir://', 'file://'), urls)) varString = str.join(' ', map(lambda x: 'export %s="%s";' % (x, varDict[x]), varDict)) return utils.LoggedProcess('source %s || exit 1; %s %s %s' % (runLib, varString, cmd, args))
| 476,497
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
|
def incInfo(x): infos[x] = infos.get(x, 0) + 1
| 476,498
|
def se_runcmd(cmd, urls): runLib = utils.pathGC('share', 'gc-run.lib') urlargs = str.join(' ', map(lambda x: '"%s"' % x.replace('dir://', 'file://'), urls)) return 'source %s || exit 1; print_and_eval "%s" %s' % (runLib, cmd, urlargs)
|
def se_runcmd(cmd, urls): runLib = utils.pathGC('share', 'gc-run.lib') urlargs = str.join(' ', map(lambda x: '"%s"' % x.replace('dir://', 'file://'), urls)) return 'source %s || exit 1; print_and_eval "%s" %s' % (runLib, cmd, urlargs)
| 476,499
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.