Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
1,100
def to_signum(signum): """Resolves the signal number from arbitrary signal representation. Supported formats: 10 - plain integers '10' - integers as a strings 'KILL' - signal names 'SIGKILL' - signal names with SIG prefix 'SIGRTMIN+1' - signal names with offsets """...
KeyError
dataset/ETHPy150Open circus-tent/circus/circus/util.py/to_signum
1,101
def to_uid(name): # NOQA """Return an uid, given a user name. If the name is an integer, make sure it's an existing uid. If the user name is unknown, raises a ValueError. """ try: name = int(name) except __HOLE__: pass if isinstance(name...
ValueError
dataset/ETHPy150Open circus-tent/circus/circus/util.py/to_uid
1,102
def to_gid(name): # NOQA """Return a gid, given a group name If the group name is unknown, raises a ValueError. """ try: name = int(name) except __HOLE__: pass if isinstance(name, int): try: grp.getgrgid(name) ...
ValueError
dataset/ETHPy150Open circus-tent/circus/circus/util.py/to_gid
1,103
def resolve_name(import_name, silent=False, reload=False): """Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (``xml.sax.saxutils.escape``) or with a colon as object delimit...
AttributeError
dataset/ETHPy150Open circus-tent/circus/circus/util.py/resolve_name
1,104
def _read(self, fp, fpname): cursect = None # None, or a dictionary optname = None lineno = 0 e = None # None, or an exception while True: line = fp.readline() if not line: break ...
AttributeError
dataset/ETHPy150Open circus-tent/circus/circus/util.py/StrictConfigParser._read
1,105
def get_connection(socket, endpoint, ssh_server=None, ssh_keyfile=None): if ssh_server is None: socket.connect(endpoint) else: try: try: ssh.tunnel_connection(socket, endpoint, ssh_server, keyfile=ssh_keyfile) except I...
ImportError
dataset/ETHPy150Open circus-tent/circus/circus/util.py/get_connection
1,106
def load_virtualenv(watcher, py_ver=None): if not watcher.copy_env: raise ValueError('copy_env must be True to to use virtualenv') if not py_ver: py_ver = sys.version.split()[0][:3] # XXX Posix scheme - need to add others sitedir = os.path.join(watcher.virtualenv, 'lib', 'python' + py_...
OSError
dataset/ETHPy150Open circus-tent/circus/circus/util.py/load_virtualenv
1,107
def create_udp_socket(mcast_addr, mcast_port): """Create an udp multicast socket for circusd cluster auto-discovery. mcast_addr must be between 224.0.0.0 and 239.255.255.255 """ try: ip_splitted = list(map(int, mcast_addr.split('.'))) mcast_port = int(mcast_port) except __HOLE__: ...
ValueError
dataset/ETHPy150Open circus-tent/circus/circus/util.py/create_udp_socket
1,108
def foo(): try: test() except __HOLE__: raise RuntimeError("Accessing a undefined name should raise a NameError")
ValueError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/except_in_raising_code.py/foo
1,109
def FilterGenerator(): class PrintPmPerceptualError(PrintFilter): def __init__(self): super(PrintPmPerceptualError, self).__init__('print_pm_perceptual_error', 'Prints perceptual error at different levels of a progressive mesh compared to full resolution') ...
IOError
dataset/ETHPy150Open pycollada/meshtool/meshtool/filters/print_filters/print_pm_perceptual_error.py/FilterGenerator
1,110
def daemonize(self): """ do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 """ try: pid = os.fork() if pid > 0: ...
OSError
dataset/ETHPy150Open CacheBrowser/cachebrowser/cachebrowser/daemon.py/Daemon.daemonize
1,111
def start(self): """ Start the daemon """ # Check for a pidfile to see if the daemon already runs try: pf = file(self.pidfile, 'r') pid = int(pf.read().strip()) pf.close() except __HOLE__: pid = None if pid: ...
IOError
dataset/ETHPy150Open CacheBrowser/cachebrowser/cachebrowser/daemon.py/Daemon.start
1,112
def stop(self): """ Stop the daemon """ # Get the pid from the pidfile try: pf = file(self.pidfile, 'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if not pid: message = "pidfile ...
OSError
dataset/ETHPy150Open CacheBrowser/cachebrowser/cachebrowser/daemon.py/Daemon.stop
1,113
def main(): try: f = open('.git', 'r') subgitdir = f.read() f.close() except (__HOLE__, OSError): raise SystemExit(1) subgitdir = subgitdir.replace('gitdir: ', '').strip() p = subprocess.Popen(['git','update-server-info'], cwd=subgitdir) p.communicate()
IOError
dataset/ETHPy150Open trebuchet-deploy/trigger/trigger/utils/submodule_update.py/main
1,114
def get_page_count(self): super(Python, self).get_page_count() page_count = 1 if self.mime_type == 'application/pdf' or self.soffice_file: # If file is a PDF open it with slate to determine the page count if self.soffice_file: file_object = IteratorIO(se...
IOError
dataset/ETHPy150Open mayan-edms/mayan-edms/mayan/apps/converter/backends/python.py/Python.get_page_count
1,115
def _izip_longest(*args, **kwds): """Taken from Python docs http://docs.python.org/library/itertools.html#itertools.izip """ fillvalue = kwds.get('fillvalue') def sentinel(counter = ([fillvalue]*(len(args)-1)).pop): yield counter() # yields the fillvalue, or raises IndexError fillers = ...
IndexError
dataset/ETHPy150Open cloudkick/libcloud/libcloud/compute/drivers/linode.py/_izip_longest
1,116
def _get_plugins_module(self, package_name): """ Import 'plugins.py' from the package with the given name. If the package does not exist, or does not contain 'plugins.py' then return None. """ try: module = __import__(package_name + '.plugins', fromlist=['plugins']...
ImportError
dataset/ETHPy150Open enthought/envisage/envisage/package_plugin_manager.py/PackagePluginManager._get_plugins_module
1,117
def test_no_init_kwargs(self): """ Test that a view can't be accidentally instantiated before deployment """ try: view = SimpleView(key='value').as_view() self.fail('Should not be able to instantiate a view') except __HOLE__: pass
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/tests/regressiontests/generic_views/base.py/ViewTest.test_no_init_kwargs
1,118
def test_no_init_args(self): """ Test that a view can't be accidentally instantiated before deployment """ try: view = SimpleView.as_view('value') self.fail('Should not be able to use non-keyword arguments instantiating a view') except __HOLE__: ...
TypeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/tests/regressiontests/generic_views/base.py/ViewTest.test_no_init_args
1,119
def get_next_sibling(self): """ Returns this model instance's next sibling in the tree, or ``None`` if it doesn't have a next sibling. """ opts = self._meta if self.is_root_node(): filters = { '%s__isnull' % opts.parent_attr: True, '%s__gt' % opts.tree_id...
IndexError
dataset/ETHPy150Open agiliq/django-socialnews/socialnews/mptt/models.py/get_next_sibling
1,120
def get_previous_sibling(self): """ Returns this model instance's previous sibling in the tree, or ``None`` if it doesn't have a previous sibling. """ opts = self._meta if self.is_root_node(): filters = { '%s__isnull' % opts.parent_attr: True, '%s__lt' % ...
IndexError
dataset/ETHPy150Open agiliq/django-socialnews/socialnews/mptt/models.py/get_previous_sibling
1,121
def has_changed(self, initial, data): # noqa if initial is None: initial = ['' for x in range(0, len(data))] else: if not isinstance(initial, list): initial = self.widget.decompress(initial) amount_field, currency_field = self.fields amount_initi...
IndexError
dataset/ETHPy150Open django-money/django-money/djmoney/forms/fields.py/MoneyField.has_changed
1,122
def test_ndarray_compat_properties(self): for o in self.objs: # check that we work for p in ['shape', 'dtype', 'flags', 'T', 'strides', 'itemsize', 'nbytes']: self.assertIsNotNone(getattr(o, p, None)) self.assertTrue(hasattr(o, 'base'))...
ValueError
dataset/ETHPy150Open pydata/pandas/pandas/tests/test_base.py/TestIndexOps.test_ndarray_compat_properties
1,123
def test_ops(self): for op in ['max', 'min']: for o in self.objs: result = getattr(o, op)() if not isinstance(o, PeriodIndex): expected = getattr(o.values, op)() else: expected = pd.Period(ordinal=getattr(o.value...
TypeError
dataset/ETHPy150Open pydata/pandas/pandas/tests/test_base.py/TestIndexOps.test_ops
1,124
@staticmethod def parse_rpm_output(output, tags, separator=';'): """ Parse output of the rpm query. :param output: list, decoded output (str) from the rpm subprocess :param tags: list, str fields used for query output :return: list, dicts describing each rpm package ...
ValueError
dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/plugins/exit_koji_promote.py/KojiPromotePlugin.parse_rpm_output
1,125
def get_rpms(self): """ Build a list of installed RPMs in the format required for the metadata. """ tags = [ 'NAME', 'VERSION', 'RELEASE', 'ARCH', 'EPOCH', 'SIGMD5', 'SIGPGP:pgpsig', ...
AttributeError
dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/plugins/exit_koji_promote.py/KojiPromotePlugin.get_rpms
1,126
def get_builder_image_id(self): """ Find out the docker ID of the buildroot image we are in. """ try: buildroot_tag = os.environ["OPENSHIFT_CUSTOM_BUILD_BASE_IMAGE"] except __HOLE__: return '' try: pod = self.osbs.get_pod_for_build(se...
KeyError
dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/plugins/exit_koji_promote.py/KojiPromotePlugin.get_builder_image_id
1,127
def get_image_components(self): """ Re-package the output of the rpmqa plugin into the format required for the metadata. """ try: output = self.workflow.postbuild_results[PostBuildRPMqaPlugin.key] except __HOLE__: self.log.error("%s plugin did not...
KeyError
dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/plugins/exit_koji_promote.py/KojiPromotePlugin.get_image_components
1,128
def get_build(self, metadata): build_start_time = metadata["creationTimestamp"] try: # Decode UTC RFC3339 date with no fractional seconds # (the format we expect) start_time_struct = time.strptime(build_start_time, '%Y-%m-...
ValueError
dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/plugins/exit_koji_promote.py/KojiPromotePlugin.get_build
1,129
def get_metadata(self): """ Build the metadata needed for importing the build :return: tuple, the metadata and the list of Output instances """ try: metadata = get_build_json()["metadata"] self.build_id = metadata["name"] except __HOLE__: ...
KeyError
dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/plugins/exit_koji_promote.py/KojiPromotePlugin.get_metadata
1,130
def present(name, **kwargs): ''' Ensure that an account is present and properly configured name The email address associated with the Stormpath account directory_id The ID of a directory which the account belongs to. Required. password Required when creating a new account....
HTTPError
dataset/ETHPy150Open saltstack/salt/salt/states/stormpath_account.py/present
1,131
def absent(name, directory_id=None): ''' Ensure that an account associated with the given email address is absent. Will search all directories for the account, unless a directory_id is specified. name The email address of the account to delete. directory_id Optional. The ID of ...
HTTPError
dataset/ETHPy150Open saltstack/salt/salt/states/stormpath_account.py/absent
1,132
def save(self): """ Attempts to save the current file, prompting for a path if necessary. Returns whether the file was saved. """ editor = self.window.central_pane.editor try: editor.save() except __HOLE__: # If you are trying to save to a file...
IOError
dataset/ETHPy150Open enthought/pyface/examples/tasks/basic/example_task.py/ExampleTask.save
1,133
def test_failstub(): failstub = StubCallable(throw=NotImplementedError('foo')) try: failstub('sanity') assert False except __HOLE__: pass assert 1 == len(failstub.calls) assert "(('sanity',), {})" == str(failstub.calls[0])
NotImplementedError
dataset/ETHPy150Open probcomp/bayeslite/tests/test_loggers.py/test_failstub
1,134
def test_logged_query_fail(): # If the query itself fails, we should not impede that floating to top. failstub = StubCallable(throw=NotImplementedError('foo')) okstub = StubCallable() lgr = loggers.CallHomeStatusLogger(post=okstub) try: with loggers.logged_query(logger=lgr, **THE_USUAL): ...
NotImplementedError
dataset/ETHPy150Open probcomp/bayeslite/tests/test_loggers.py/test_logged_query_fail
1,135
def refresh_file_mapping(self): ''' Override the default refresh_file_mapping to look for nova files recursively, rather than only in a top-level directory ''' # map of suffix to description for imp self.suffix_map = {} suffix_order = [] # local list to determine...
OSError
dataset/ETHPy150Open HubbleStack/Nova/_modules/hubble.py/NovaLazyLoader.refresh_file_mapping
1,136
def _load_module(self, name): ''' Override the module load code ''' mod = None fpath, suffix = self.file_mapping[name] self.loaded_files.add(name) if suffix == '.yaml': try: with open(fpath) as fh_: data = yaml.safe_...
TypeError
dataset/ETHPy150Open HubbleStack/Nova/_modules/hubble.py/NovaLazyLoader._load_module
1,137
def fetch_issues(self): try: iterator = self.repo.iter_issues except __HOLE__: iterator = self.repo.issues for issue in iterator(state='all'): # is this a pull request ? if getattr(issue, 'pull_request', None): msg = 'Skipping pull ...
AttributeError
dataset/ETHPy150Open redhat-cip/software-factory/tools/sfmigration/sfmigration/issues/github.py/GithubImporter.fetch_issues
1,138
def fetch_versions(self): try: iterator = self.repo.iter_milestones except __HOLE__: iterator = self.repo.milestones for version in iterator(): logger.debug("Fetching version %s: %s" % (version.number, vers...
AttributeError
dataset/ETHPy150Open redhat-cip/software-factory/tools/sfmigration/sfmigration/issues/github.py/GithubImporter.fetch_versions
1,139
def process(self, lookup_type, value, connection): """ Returns a tuple of data suitable for inclusion in a WhereNode instance. """ # Because of circular imports, we need to import this here. from django.db.models.base import ObjectDoesNotExist try: if ...
ObjectDoesNotExist
dataset/ETHPy150Open daoluan/decode-Django/Django-1.5.1/django/db/models/sql/where.py/Constraint.process
1,140
def tearDown(self): typepad.client = self.typepad_client del self.typepad_client for x in ('headers', 'body'): try: delattr(self, x) except __HOLE__: pass
AttributeError
dataset/ETHPy150Open typepad/python-typepad-api/tests/test_tpobject.py/ClientTestCase.tearDown
1,141
def __init__(self, session=None, verify_ssl=False, **credentials): self.verify_ssl = verify_ssl if session: if isinstance(session, dict): logger.info('Trying to recover OpenStack session.') self.session = OpenStackSession.recover(session, verify_ssl=verify_ssl...
AttributeError
dataset/ETHPy150Open opennode/nodeconductor/nodeconductor/openstack/backend.py/OpenStackClient.__init__
1,142
def get_instance(self, instance_id): try: nova = self.nova_client cinder = self.cinder_client instance = nova.servers.get(instance_id) try: attached_volume_ids = [v.volumeId for v in nova.volumes.get_server_volumes(instance_id)] if...
KeyError
dataset/ETHPy150Open opennode/nodeconductor/nodeconductor/openstack/backend.py/OpenStackBackend.get_instance
1,143
def provision_instance(self, instance, backend_flavor_id=None, backend_image_id=None, system_volume_id=None, data_volume_id=None, skip_external_ip_assignment=False, public_key=None): logger.info('About to provision instance %s', instance.uuid) try: ...
KeyError
dataset/ETHPy150Open opennode/nodeconductor/nodeconductor/openstack/backend.py/OpenStackBackend.provision_instance
1,144
def push_floating_ip_to_instance(self, instance, server): if not instance.external_ips or not instance.internal_ips: return logger.debug('About to add external ip %s to instance %s', instance.external_ips, instance.uuid) service_project_link = instance.service_...
ObjectDoesNotExist
dataset/ETHPy150Open opennode/nodeconductor/nodeconductor/openstack/backend.py/OpenStackBackend.push_floating_ip_to_instance
1,145
def test_integrity(self): Group.objects.create(name='jack') try: Team.objects.convert_from_user(self.jack) except __HOLE__: pass else: self.fail("Cannot allow to convert user into team if there is " "a group with same name already...
ValidationError
dataset/ETHPy150Open lukaszb/django-projector/projector/tests/test_user2team_conversion.py/UserToTeamConversion.test_integrity
1,146
def test_anonymous(self): user = AnonymousUser() try: Team.objects.convert_from_user(user) except __HOLE__: pass else: self.fail("Cannot allow to convert anonymous user to team")
ValidationError
dataset/ETHPy150Open lukaszb/django-projector/projector/tests/test_user2team_conversion.py/UserToTeamConversion.test_anonymous
1,147
def test_staff(self): self.jack.is_staff = True self.jack.save() try: Team.objects.convert_from_user(self.jack) except __HOLE__: pass else: self.fail("Cannot allow to convert staff member to team")
ValidationError
dataset/ETHPy150Open lukaszb/django-projector/projector/tests/test_user2team_conversion.py/UserToTeamConversion.test_staff
1,148
def test_superuser(self): self.jack.is_superuser = True self.jack.save() try: Team.objects.convert_from_user(self.jack) except __HOLE__: pass else: self.fail("Cannot allow to convert superuser to team")
ValidationError
dataset/ETHPy150Open lukaszb/django-projector/projector/tests/test_user2team_conversion.py/UserToTeamConversion.test_superuser
1,149
def test_non_active(self): self.jack.is_active = False self.jack.save() try: Team.objects.convert_from_user(self.jack) except __HOLE__: pass else: self.fail("Cannot allow to convert inactive user to team")
ValidationError
dataset/ETHPy150Open lukaszb/django-projector/projector/tests/test_user2team_conversion.py/UserToTeamConversion.test_non_active
1,150
def astnode(self, s): """Return a Python2 ast Node compiled from a string.""" try: import compiler except __HOLE__: # Fallback to eval when compiler package is not available, # e.g. IronPython 1.0. return eval(s) p = compiler.parse...
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/lib/reprconf.py/_Builder2.astnode
1,151
def build_Name(self, o): name = o.name if name == 'None': return None if name == 'True': return True if name == 'False': return False # See if the Name is a package or module. If it is, import it. try: return module...
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/lib/reprconf.py/_Builder2.build_Name
1,152
def astnode(self, s): """Return a Python3 ast Node compiled from a string.""" try: import ast except __HOLE__: # Fallback to eval when ast package is not available, # e.g. IronPython 1.0. return eval(s) p = ast.parse("__tempvalue__ = " + s...
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/lib/reprconf.py/_Builder3.astnode
1,153
def build_Name(self, o): name = o.id if name == 'None': return None if name == 'True': return True if name == 'False': return False # See if the Name is a package or module. If it is, import it. try: return modules(...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/lib/reprconf.py/_Builder3.build_Name
1,154
def modules(modulePath): """Load a module and retrieve a reference to that module.""" try: mod = sys.modules[modulePath] if mod is None: raise KeyError() except __HOLE__: # The last [''] is important. mod = __import__(modulePath, globals(), locals(), ['']) ret...
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/lib/reprconf.py/modules
1,155
def attributes(full_attribute_name): """Load a module and retrieve an attribute of that module.""" # Parse out the path, module, and attribute last_dot = full_attribute_name.rfind(".") attr_name = full_attribute_name[last_dot + 1:] mod_path = full_attribute_name[:last_dot] mod = module...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/lib/reprconf.py/attributes
1,156
def main(func, modification_callback, *args, **kwargs): """Run the given function and restart any time modules are changed.""" if os.environ.get('RUN_MAIN'): exit_code = [] def main_thread(): try: func(*args, **kwargs) exit_code.append(None) ...
SystemExit
dataset/ETHPy150Open edgewall/trac/trac/util/autoreload.py/main
1,157
@requires_system_grains def test_pip_installed_weird_install(self, grains=None): # First, check to see if this is running on CentOS 5. If so, skip this test. if grains['os'] in ('CentOS',) and grains['osrelease_info'][0] in (5,): self.skipTest('This test does not run reliably on CentOS 5...
OSError
dataset/ETHPy150Open saltstack/salt/tests/integration/states/pip.py/PipStateTest.test_pip_installed_weird_install
1,158
def test_issue_6833_pip_upgrade_pip(self): # Create the testing virtualenv venv_dir = os.path.join( integration.TMP, '6833-pip-upgrade-pip' ) ret = self.run_function('virtualenv.create', [venv_dir]) try: try: self.assertEqual(ret['retcode']...
AssertionError
dataset/ETHPy150Open saltstack/salt/tests/integration/states/pip.py/PipStateTest.test_issue_6833_pip_upgrade_pip
1,159
def sanitize_url(self, url): if url.startswith("http"): return url else: try: image = Image.objects.get(pk=int(url)) return image.image_path.url except Image.DoesNotExist: pass except __HOLE__: ...
ValueError
dataset/ETHPy150Open pinax/pinax-blog/pinax/blog/parsers/markdown_parser.py/ImageLookupImagePattern.sanitize_url
1,160
def do_open(self, http_class, req): proxy_authorization = None for header in req.headers: if header.lower() == "proxy-authorization": proxy_authorization = req.headers[header] break # Intentionally very specific so as to opt for false negatives # rather than false positives. t...
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/fancy_urllib/fancy_urllib/__init__.py/FancyHTTPSHandler.do_open
1,161
def render(self, name, value, attrs=None): # Update the template parameters with any attributes passed in. if attrs: self.params.update(attrs) # Defaulting the WKT value to a blank string -- this # will be tested in the JavaScript and the appropriate # interface will be construc...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/contrib/gis/admin/widgets.py/OpenLayersWidget.render
1,162
def to_python(self, value): if value == "": return None try: if isinstance(value, basestring): return json.loads(value) elif isinstance(value, bytes): return json.loads(value.decode('utf8')) except __HOLE__: pass ...
ValueError
dataset/ETHPy150Open skorokithakis/django-annoying/annoying/fields.py/JSONField.to_python
1,163
def login(self, username, password): try: request_data = {'postUserLogin': { 'login': username, 'password': password, 'remember': 1, }} response = self.request(s...
KeyError
dataset/ETHPy150Open comoga/gooddata-python/gooddataclient/connection.py/Connection.login
1,164
def create_directory(self, directory_path): """Create a directory if it does not already exist. :param str directory_name: A fully qualified path of the to create. :returns: bool """ try: if os.path.exists(directory_path): return True ...
OSError
dataset/ETHPy150Open jmathai/elodie/elodie/filesystem.py/FileSystem.create_directory
1,165
def delete_directory_if_empty(self, directory_path): """Delete a directory only if it's empty. Instead of checking first using `len([name for name in os.listdir(directory_path)]) == 0`, we catch the OSError exception. :param str directory_name: A fully qualified path of the directory ...
OSError
dataset/ETHPy150Open jmathai/elodie/elodie/filesystem.py/FileSystem.delete_directory_if_empty
1,166
def load_tests(loader, tests, ignore): try: import sklearn except __HOLE__: pass else: tests.addTests(doctest.DocTestSuite()) return tests
ImportError
dataset/ETHPy150Open Twangist/log_calls/log_calls/tests/test_with_sklearn/test_decorate_sklearn_KMeans.py/load_tests
1,167
def call(*args, **kwargs): if logging.getLogger().getEffectiveLevel() == logging.DEBUG: stderr = PIPE else: stderr = DEVNULL kwargs.setdefault('stderr', stderr) kwargs.setdefault('stdout', PIPE) kwargs.setdefault('stdin', PIPE) kwargs.setdefault('shell', False) kwargs_input ...
AttributeError
dataset/ETHPy150Open marcwebbie/passpie/passpie/process.py/call
1,168
def getcaps(): """Return a dictionary containing the mailcap database. The dictionary maps a MIME type (in all lowercase, e.g. 'text/plain') to a list of dictionaries corresponding to mailcap entries. The list collects all the entries for that MIME type from all available mailcap files. Each dict...
IOError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/mailcap.py/getcaps
1,169
def _get_llas(self, gw_ifname, ns_name): try: return self.intf_driver.get_ipv6_llas(gw_ifname, ns_name) except __HOLE__: # The error message was printed as part of the driver call # This could happen if the gw_ifname was removed # simply return and exit th...
RuntimeError
dataset/ETHPy150Open openstack/neutron/neutron/agent/linux/pd.py/PrefixDelegation._get_llas
1,170
def _delete_lla(self, router, lla_with_mask): if lla_with_mask and router['gw_interface']: try: self.intf_driver.delete_ipv6_addr(router['gw_interface'], lla_with_mask, router['ns_name...
RuntimeError
dataset/ETHPy150Open openstack/neutron/neutron/agent/linux/pd.py/PrefixDelegation._delete_lla
1,171
def make_changed_file(path, env): """ Given the path to a template file, write a new file with: * The same filename, except without '.template' at the end. * A placeholder in the new file changed to the latest installable version of Flocker. This new file will be deleted on build ...
OSError
dataset/ETHPy150Open ClusterHQ/flocker/flocker/docs/version_extensions.py/make_changed_file
1,172
def string_to_country(self, value): try: return CountryContainer(value) except __HOLE__: raise ValidationError( self.error_messages['invalid_country'], code='invalid_country', params={'name': value} )
KeyError
dataset/ETHPy150Open django-bmf/django-bmf/djangobmf/fields/country.py/CountryField.string_to_country
1,173
def Run(self, max_age=60 * 60 * 24 * 7): """Run the report.""" counts = {} self.fields.append("count") self.results = [] for client in self._QueryResults(max_age): version = client.get("GRR client") try: counts[version] += 1 except __HOLE__: counts[version] = 1 ...
KeyError
dataset/ETHPy150Open google/grr/grr/lib/aff4_objects/reports.py/VersionBreakdownReport.Run
1,174
def IterFunction(self, client, out_queue, unused_token): """Extract report attributes.""" result = {} for attr in self.report_attrs: # Do some special formatting for certain fields. if attr.name == "subject": result[attr.name] = client.Get(attr).Basename() elif attr.name == "GRR cl...
AttributeError
dataset/ETHPy150Open google/grr/grr/lib/aff4_objects/reports.py/ClientReportIterator.IterFunction
1,175
def get_user_from_uid(uid): if uid is None: raise ValidationError(_("uid is required!")) try: uid = urlsafe_base64_decode(uid) user = User.objects.get(pk=uid) except (TypeError, __HOLE__, OverflowError, User.DoesNotExist): raise ValidationError(_(u"Invalid uid %s") % uid) ...
ValueError
dataset/ETHPy150Open kobotoolbox/kobocat/onadata/libs/serializers/password_reset_serializer.py/get_user_from_uid
1,176
def __getstate__(self): d = self.__dict__.copy() for attr in ('reader', 'writer'): method = getattr(self, attr) try: # if instance method, pickle instance and method name d[attr] = method.__self__, method.__func__.__name__ except __HOLE...
AttributeError
dataset/ETHPy150Open spotify/luigi/luigi/contrib/hdfs/format.py/CompatibleHdfsFormat.__getstate__
1,177
def __setstate__(self, d): self.__dict__ = d for attr in ('reader', 'writer'): try: method_self, method_name = d[attr] except __HOLE__: continue method = getattr(method_self, method_name) setattr(self, attr, method)
ValueError
dataset/ETHPy150Open spotify/luigi/luigi/contrib/hdfs/format.py/CompatibleHdfsFormat.__setstate__
1,178
def create_directory(path): if not os.path.isdir(path): if os.path.exists(path): raise RuntimeError('{0} is not a directory.'.format(path)) try: os.makedirs(path, mode=0o750) except __HOLE__ as error: logger.fatal('failed to create {0}: {1}'.format(path, e...
OSError
dataset/ETHPy150Open pimutils/khal/khal/khalendar/khalendar.py/create_directory
1,179
def splitport(port): port = port.split('/',1) proto = None if len(port) == 2: port, proto = port else: port = port[0] try: port = int(port) except __HOLE__: proto = port port = None return port, proto
ValueError
dataset/ETHPy150Open bonsaiviking/NfSpy/nfspy/nfspy.py/splitport
1,180
def _gethandle(self, path): fh = None fattr = None try: if path == "" or path == "/" or path == "/.." or path == "/.": fh = self.rootdh fattr = self.rootattr else: fh, fattr, cachetime = self.handles[path] # chec...
KeyError
dataset/ETHPy150Open bonsaiviking/NfSpy/nfspy/nfspy.py/NfSpy._gethandle
1,181
def start(host, port, profile_stats, dont_start_browser): """Starts HTTP server with specified parameters. Args: host: Server hostname. port: Server port. profile_stats: Dict with collected progran stats. dont_start_browser: Whether to start browser after profiling. """ ...
KeyboardInterrupt
dataset/ETHPy150Open nvdv/vprof/vprof/stats_server.py/start
1,182
def get_response(self, request): """ Overrides the base implementation with object-oriented hooks. Adapted from django.core.handlers.base.BaseHandler. """ resolver = self.get_resolver(request) try: return self.process_response( ...
SystemExit
dataset/ETHPy150Open skibblenybbles/django-daydreamer/daydreamer/core/handlers/base.py/Handler.get_response
1,183
def get_glance_client(context, image_href): """Get the correct glance client and id for the given image_href. The image_href param can be an href of the form http://myglanceserver:9292/images/42, or just an int such as 42. If the image_href is an int, then flags are used to create the default glanc...
ValueError
dataset/ETHPy150Open nii-cloud/dodai-compute/nova/image/glance.py/get_glance_client
1,184
def _fetch_images(self, fetch_func, **kwargs): """Paginate through results from glance server""" images = fetch_func(**kwargs) if not images: # break out of recursive loop to end pagination return for image in images: yield image try: ...
KeyError
dataset/ETHPy150Open nii-cloud/dodai-compute/nova/image/glance.py/GlanceImageService._fetch_images
1,185
def _parse_glance_iso8601_timestamp(timestamp): """Parse a subset of iso8601 timestamps into datetime objects.""" iso_formats = ['%Y-%m-%dT%H:%M:%S.%f', '%Y-%m-%dT%H:%M:%S'] for iso_format in iso_formats: try: return datetime.datetime.strptime(timestamp, iso_format) except __HOL...
ValueError
dataset/ETHPy150Open nii-cloud/dodai-compute/nova/image/glance.py/_parse_glance_iso8601_timestamp
1,186
def regenerate_memmap(self): """Delete internal memmap and create a new one, to save memory.""" try: del self._mm except __HOLE__: pass self._mm = np.memmap(\ self.filename, dtype='h', mode='r', offset=self.header.Header, shape...
AttributeError
dataset/ETHPy150Open NeuralEnsemble/python-neo/neo/io/blackrockio_deprecated.py/Loader.regenerate_memmap
1,187
def _get_channel(self, channel_number): """Returns slice into internal memmap for requested channel""" try: mm_index = self.header.Channel_ID.index(channel_number) except __HOLE__: logging.info( "Channel number %d does not exist" % channel_number) return np.ar...
ValueError
dataset/ETHPy150Open NeuralEnsemble/python-neo/neo/io/blackrockio_deprecated.py/Loader._get_channel
1,188
def get_date_status(value): """ For date values that are tomorrow, today or yesterday compared to present day returns representing string. Otherwise, returns an empty string or overdue string if date value is late. """ try: value = date(value.year, value.month...
AttributeError
dataset/ETHPy150Open zorna/zorna/zorna/calendars/api.py/get_date_status
1,189
def add(self, num1, num2): """ :param num1: list of digits in reverse order :param num2: list of digits in reverse order :return: list of digits in reverse order """ num1 = list(num1) # NOTICE: local copy num2 = list(num2) # NOTICE: local copy if...
IndexError
dataset/ETHPy150Open algorhythms/LeetCode/042 Multiply Strings.py/Solution.add
1,190
def ordinal(value): """ Converts an integer to its ordinal as a string. 1 is '1st', 2 is '2nd', 3 is '3rd', etc. Works for any integer. """ try: value = int(value) except __HOLE__: return value t = (_('th'), _('st'), _('nd'), _('rd'), _('th'), _('th'), _('th'), _('th'), _('th...
ValueError
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/contrib/humanize/templatetags/humanize.py/ordinal
1,191
def apnumber(value): """ For numbers 1-9, returns the number spelled out. Otherwise, returns the number. This follows Associated Press style. """ try: value = int(value) except __HOLE__: return value if not 0 < value < 10: return value return (_('one'), _('two'), ...
ValueError
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/contrib/humanize/templatetags/humanize.py/apnumber
1,192
def naturalday(value, arg=None): """ For date values that are tomorrow, today or yesterday compared to present day returns representing string. Otherwise, returns a string formatted according to settings.DATE_FORMAT. """ try: value = date(value.year, value.month, value.day) except _...
AttributeError
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/contrib/humanize/templatetags/humanize.py/naturalday
1,193
def GetFacterFacts(): """Return facter contents. Returns: dict, facter contents """ return_code, stdout, unused_stderr = Exec( FACTER_CMD, timeout=300, waitfor=0.5) if return_code != 0: return {} # Iterate over the facter output and create a dictionary of the contents. facts = {} for lin...
ValueError
dataset/ETHPy150Open google/simian/src/simian/mac/client/flight_common.py/GetFacterFacts
1,194
def GetSystemUptime(): """Returns the system uptime. Returns: float seconds of uptime Raises: Error: if an error occurs in calculating uptime """ libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('c')) # 2 integers returned, might be 4 or 8 bytes each l = ctypes.c_int(16) buf = ctypes.cr...
AttributeError
dataset/ETHPy150Open google/simian/src/simian/mac/client/flight_common.py/GetSystemUptime
1,195
def GetDiskFree(path=None): """Return the bytes of free space. Args: path: str, optional, default '/' Returns: int, bytes in free space available """ if path is None: path = '/' try: st = os.statvfs(path) except __HOLE__ as e: raise Error(str(e)) return st.f_frsize * st.f_bavail #...
OSError
dataset/ETHPy150Open google/simian/src/simian/mac/client/flight_common.py/GetDiskFree
1,196
def GetClientIdentifier(runtype=None): """Assembles the client identifier based on information collected by facter. Args: runtype: str, optional, Munki runtype. i.e. auto, custom, manual, etc. Returns: dict client identifier. """ facts = GetFacterFacts() uuid = (facts.get('certname', None) or ...
IOError
dataset/ETHPy150Open google/simian/src/simian/mac/client/flight_common.py/GetClientIdentifier
1,197
def UploadAllManagedInstallReports(client, on_corp): """Uploads any installs, updates, uninstalls back to Simian server. Args: client: A SimianAuthClient. on_corp: str, on_corp status from GetClientIdentifier. """ # Report installs from the ManagedInstallsReport archives. archives_dir = os.path.join(...
IOError
dataset/ETHPy150Open google/simian/src/simian/mac/client/flight_common.py/UploadAllManagedInstallReports
1,198
def KillHungManagedSoftwareUpdate(): """Kill hung managedsoftwareupdate instances, if any can be found. Returns: True if a managedsoftwareupdate instance was killed, False otherwise. """ rc, stdout, stderr = Exec(['/bin/ps', '-eo', 'pid,ppid,lstart,command']) if rc != 0 or not stdout or stderr: retur...
OSError
dataset/ETHPy150Open google/simian/src/simian/mac/client/flight_common.py/KillHungManagedSoftwareUpdate
1,199
def main(): 'Manage the OSM DB during development.' from optparse import OptionParser parser = OptionParser(usage=usage, prog=toolname, version='%prog ' + toolversion) parser.add_option('-b', '--buffering', dest='buffering', metavar="NUMBER", default=64, ...
ImportError
dataset/ETHPy150Open MapQuest/mapquest-osm-server/src/python/dbmgr/__main__.py/main