Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
5,100
def create_connect_args(self, url): opts = url.translate_connect_args(database='db', username='user', password='passwd') opts.update(url.query) util.coerce_kw_type(opts, 'compress', bool) util.coerce_kw_type(opts, 'connect_timeout', int) ...
AttributeError
dataset/ETHPy150Open zzzeek/sqlalchemy/lib/sqlalchemy/dialects/mysql/mysqldb.py/MySQLDialect_mysqldb.create_connect_args
5,101
def _get_server_version_info(self, connection): dbapi_con = connection.connection version = [] r = re.compile('[.\-]') for n in r.split(dbapi_con.get_server_info()): try: version.append(int(n)) except __HOLE__: version.append(n) ...
ValueError
dataset/ETHPy150Open zzzeek/sqlalchemy/lib/sqlalchemy/dialects/mysql/mysqldb.py/MySQLDialect_mysqldb._get_server_version_info
5,102
def _detect_charset(self, connection): """Sniff out the character set in use for connection results.""" try: # note: the SQL here would be # "SHOW VARIABLES LIKE 'character_set%%'" cset_name = connection.connection.character_set_name except __HOLE__: ...
AttributeError
dataset/ETHPy150Open zzzeek/sqlalchemy/lib/sqlalchemy/dialects/mysql/mysqldb.py/MySQLDialect_mysqldb._detect_charset
5,103
def get_spatial_scale(wcs, assert_square=True): # Code adapted from APLpy wcs = wcs.sub([WCSSUB_CELESTIAL]) cdelt = np.matrix(wcs.wcs.get_cdelt()) pc = np.matrix(wcs.wcs.get_pc()) scale = np.array(cdelt * pc) if assert_square: try: np.testing.assert_almost_equal(abs(cdelt[...
AssertionError
dataset/ETHPy150Open glue-viz/glue/glue/external/pvextractor/utils/wcs_utils.py/get_spatial_scale
5,104
def GetThreadId(thread): try: return thread.__pydevd_id__ except __HOLE__: _nextThreadIdLock.acquire() try: #We do a new check with the lock in place just to be sure that nothing changed if not hasattr(thread, '__pydevd_id__'): try: ...
AttributeError
dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/common/diagnostic/pydevDebug/pydevd_constants.py/GetThreadId
5,105
def hsts(self, name): """Test for HTTP Strict Transport Security header""" headers = requests.get("https://" + name).headers hsts_header = headers.get("strict-transport-security") if not hsts_header: return False # Split directives following RFC6797, section 6.1 ...
ValueError
dataset/ETHPy150Open letsencrypt/letsencrypt/certbot-compatibility-test/certbot_compatibility_test/validator.py/Validator.hsts
5,106
def get_all(type_obj, include_subtypes=True): """Get a list containing all instances of a given type. This will work for the vast majority of types out there. >>> class Ratking(object): pass >>> wiki, hak, sport = Ratking(), Ratking(), Ratking() >>> len(get_all(Ratking)) 3 However, there ...
AttributeError
dataset/ETHPy150Open mahmoud/boltons/boltons/gcutils.py/get_all
5,107
def import_dicts(): data = [] with open('DICTLINE.GEN', encoding="ISO-8859-1") as f: for i, line in enumerate( f ): orth = line[0:19].replace("zzz", "").strip() parts = [orth] if len( line[19:38].strip() ) > 0: parts.append( line[19:38].replace("zzz", "").strip() ) if len( line[38:57].strip() ) >...
ValueError
dataset/ETHPy150Open segetes/open_words/open_words/format_data.py/import_dicts
5,108
def import_stems(): data = [] with open('STEMLIST.GEN') as f: for line in f: if len( line[26:30].strip() ) > 0: n = line[26:30].strip().split(" ") for i, v in enumerate(n): try: n[i] = int(v) except __HOLE__: pass data.append({ 'orth' : line[0:19].strip(), 'pos' : lin...
ValueError
dataset/ETHPy150Open segetes/open_words/open_words/format_data.py/import_stems
5,109
def parse_infl_type(s): if len( s.strip() ) > 0: n = s.strip().split(" ") for i, v in enumerate(n): try: n[i] = int(v) except __HOLE__: pass return n
ValueError
dataset/ETHPy150Open segetes/open_words/open_words/format_data.py/parse_infl_type
5,110
def extract_eliot_from_twisted_log(twisted_log_line): """ Given a line from a Twisted log message, return the text of the Eliot log message that is on that line. If there is no Eliot message on that line, return ``None``. :param str twisted_log_line: A line from a Twisted test.log. :return: A ...
TypeError
dataset/ETHPy150Open ClusterHQ/flocker/flocker/testtools/_base.py/extract_eliot_from_twisted_log
5,111
def check_data_classes(test, classes): import inspect for data_class in classes: test.assert_(data_class.__doc__ is not None, 'The class %s should have a docstring' % data_class) if hasattr(data_class, '_qname'): qname_versions = None if isinstance(data_class._qname, tuple): ...
TypeError
dataset/ETHPy150Open kuri65536/python-for-android/python3-alpha/python-libs/gdata/test_config.py/check_data_classes
5,112
def _import_identity(import_str): try: import_str = _id_type(import_str) full_str = "pyrax.identity.%s" % import_str return utils.import_class(full_str) except __HOLE__: pass return utils.import_class(import_str)
ImportError
dataset/ETHPy150Open rackspace/pyrax/pyrax/__init__.py/_import_identity
5,113
def get(self, key, env=None): """ Returns the config setting for the specified environment. If no environment is specified, the value for the current environment is returned. If an unknown key or environment is passed, None is returned. """ if env is None: env...
KeyError
dataset/ETHPy150Open rackspace/pyrax/pyrax/__init__.py/Settings.get
5,114
def _safe_region(region=None, context=None): """Value to use when no region is specified.""" ret = region or settings.get("region") context = context or identity if not ret: # Nothing specified; get the default from the identity object. if not context: _create_identity() ...
IndexError
dataset/ETHPy150Open rackspace/pyrax/pyrax/__init__.py/_safe_region
5,115
def connect_to_cloudservers(region=None, context=None, verify_ssl=None, **kwargs): """Creates a client for working with cloud servers.""" context = context or identity _cs_auth_plugin.discover_auth_systems() id_type = get_setting("identity_type") if id_type != "keystone": auth_plugin = _cs_a...
AttributeError
dataset/ETHPy150Open rackspace/pyrax/pyrax/__init__.py/connect_to_cloudservers
5,116
@transaction.atomic def import_pages_from_json(modeladmin, request, queryset, template_name='admin/pages/page/import_pages.html'): try: j = request.FILES['json'] except __HOLE__: return render(request, template_name, { 'nofile': True, 'app_label': 'pages', ...
KeyError
dataset/ETHPy150Open batiste/django-page-cms/pages/plugins/jsonexport/actions.py/import_pages_from_json
5,117
def handle(self, *args, **options): skip = options.get('skip') resource_urlhandlers = [] if not args: resource_urlhandlers = URLInfo.objects.filter(auto_update=True) else: resources = [] for arg in args: try: prj, re...
ValueError
dataset/ETHPy150Open rvanlaar/easy-transifex/src/transifex/transifex/addons/autofetch/management/commands/txfetch.py/Command.handle
5,118
def login(request, **credentials): """ If the given credentials are valid, return a User object. """ backend = local.app.auth_backend try: user = backend.login(request, **credentials) except __HOLE__: # This backend doesn't accept these credentials as arguments. # Try the next one. pass re...
TypeError
dataset/ETHPy150Open IanLewis/kay/kay/auth/__init__.py/login
5,119
def create_new_user(user_name, password=None, **kwargs): try: auth_model = import_string(settings.AUTH_USER_MODEL) except (ImportError, __HOLE__), e: logging.warn("Failed importing auth user model: %s." % settings.AUTH_USER_MODEL) return if password: kwargs['password'] = auth_mode...
AttributeError
dataset/ETHPy150Open IanLewis/kay/kay/auth/__init__.py/create_new_user
5,120
def test_idxmapping_key_len_check(self): try: MultiDimensionalMapping(initial_items=self.init_item_odict) raise AssertionError('Invalid key length check failed.') except __HOLE__: pass
KeyError
dataset/ETHPy150Open ioam/holoviews/tests/testndmapping.py/NdIndexableMappingTest.test_idxmapping_key_len_check
5,121
def __init__( self, model, csv_path, mapping, using=None, delimiter=',', null=None, encoding=None, static_mapping=None ): self.model = model self.mapping = mapping if os.path.exists(csv_path): self.csv_path =...
IndexError
dataset/ETHPy150Open california-civic-data-coalition/django-postgres-copy/postgres_copy/__init__.py/CopyMapping.__init__
5,122
def compare_versions(version1, version2): try: return cmp(StrictVersion(version1), StrictVersion(version2)) # in case of abnormal version number, fall back to LooseVersion except __HOLE__: pass try: return cmp(LooseVersion(version1), LooseVersion(version2)) except TypeError: ...
ValueError
dataset/ETHPy150Open cloudaice/simple-data/misc/virtenv/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/commands/search.py/compare_versions
5,123
def run(self): try: algo_config = config_loader.load(os.path.join(os.path.dirname(__file__), '../../config/services.json')) algo_config = algo_config.get(self.plugin_name)['worker_options'] except __HOLE__: return None for service, options in algo_config.iteri...
AttributeError
dataset/ETHPy150Open trademob/anna-molly/lib/plugins/poll_task.py/PollTask.run
5,124
def __init__(self, timeout, scaling=1): super(Timeout, self).__init__() try: self.test_timeout = int(timeout) except __HOLE__: # If timeout value is invalid do not set a timeout. self.test_timeout = 0 if scaling >= 1: self.test_timeout *= s...
ValueError
dataset/ETHPy150Open openstack/nova/nova/tests/fixtures.py/Timeout.__init__
5,125
def get_context_data(self, **kwargs): kwargs = super(DiffView, self).get_context_data(**kwargs) try: before_url = self.request.GET['before'] after_url = self.request.GET['after'] except __HOLE__: raise Http404 before = self.call_view_from_url(before_u...
KeyError
dataset/ETHPy150Open fusionbox/django-widgy/widgy/views/versioning.py/DiffView.get_context_data
5,126
def create_subscription(self, credit_card, amount, start, days=None, months=None, occurrences=None, trial_amount=None, trial_occurrences=None): """ Creates a recurring subscription payment on the CreditCard provided. ``credit_card`` The CreditCard ins...
ValueError
dataset/ETHPy150Open drewisme/authorizesauce/authorize/apis/recurring.py/RecurringAPI.create_subscription
5,127
def GetTestGroupsFromFile(self, file_path): # This needs to be a list instead of a dictionary to preserve order in python < 2.7 TestGroups = [] ConfigFile = FileOperations.open(file_path, 'r').read().splitlines() for line in ConfigFile: if '#' == line[0]: continue #...
ValueError
dataset/ETHPy150Open owtf/owtf/framework/db/plugin_manager.py/PluginDB.GetTestGroupsFromFile
5,128
def LoadFromFileSystem(self): """Loads the plugins from the filesystem and updates their info. Walks through each sub-directory of `PLUGINS_DIR`. For each file, loads it thanks to the imp module. Updates the database with the information for each plugin: + 'title': the title...
AttributeError
dataset/ETHPy150Open owtf/owtf/framework/db/plugin_manager.py/PluginDB.LoadFromFileSystem
5,129
def paginate(wrapped=None, page_size=PAGE_SIZE): """ Decorate a view function, providing basic pagination facilities. Wraps a view function that returns a :py:class:`sqlalchemy.orm.query.Query` object in order to enable basic pagination. Returns a dictionary containing the results for the current p...
KeyError
dataset/ETHPy150Open hypothesis/h/h/paginator.py/paginate
5,130
def make_skipper(module, label=None, version=None): label = label or module try: mod = __import__(module) if version: assert LooseVersion(mod.__version__) >= LooseVersion(version) installed = True except (__HOLE__, AssertionError): installed = False return ins...
ImportError
dataset/ETHPy150Open glue-viz/glue/glue/tests/helpers.py/make_skipper
5,131
def parse_config(self, config_file_path): try: config = ConfigObj(infile=config_file_path, configspec=CONFIG_GRAMMAR.split("\n"), file_error=True) except (ConfigObjError, __HOLE__), error: raise TelesphorusConfigError(...
IOError
dataset/ETHPy150Open columbia/libtrack/libtrack/parser/src/telesphorus/settings.py/Settings.parse_config
5,132
def main(): "Main function. Handles delegation to other functions." # Parse the arguments that parser = argparse.ArgumentParser( description="Run tests on a web app.") parser.add_argument("package", help="The path of the package you're testing") parser.add_argument(...
ValueError
dataset/ETHPy150Open mozilla/app-validator/appvalidator/main.py/main
5,133
def _parse_metrics(self, message): """ Given a raw message of metrics split by newline characters, this will parse the metrics and return an array of metric objects. This will raise a :exc:`ValueError` if any metrics are invalid, unless ``ignore_errors`` is set to True. ...
ValueError
dataset/ETHPy150Open kiip/statsite/statsite/collector.py/Collector._parse_metrics
5,134
def stop(self, callback=None, **kwargs): """Stops this mode. Args: **kwargs: Catch-all since this mode might start from events with who-knows-what keyword arguments. Warning: You can safely call this method, but do not override it in your mode code. If you w...
TypeError
dataset/ETHPy150Open missionpinball/mpf/mpf/media_controller/core/mode.py/Mode.stop
5,135
@retry(9, TypeError, 0.01, 'pypet.retry') def release_lock(self): if self.is_locked and not self.is_open: try: self.lock.release() except (__HOLE__, ThreadError): self._logger.exception('Could not release lock, ' ...
ValueError
dataset/ETHPy150Open SmokinCaterpillar/pypet/pypet/utils/mpwrappers.py/LockAcquisition.release_lock
5,136
def store(self, *args, **kwargs): """Acquires a lock before storage and releases it afterwards.""" try: self.acquire_lock() return self._storage_service.store(*args, **kwargs) finally: if self.lock is not None: try: self.rel...
RuntimeError
dataset/ETHPy150Open SmokinCaterpillar/pypet/pypet/utils/mpwrappers.py/LockWrapper.store
5,137
def load(self, *args, **kwargs): """Acquires a lock before loading and releases it afterwards.""" try: self.acquire_lock() return self._storage_service.load(*args, **kwargs) finally: if self.lock is not None: try: self.relea...
RuntimeError
dataset/ETHPy150Open SmokinCaterpillar/pypet/pypet/utils/mpwrappers.py/LockWrapper.load
5,138
def rmgeneric(path, __func__): try: __func__(path) except __HOLE__, (errno, strerror): pass
OSError
dataset/ETHPy150Open moxie0/sslstrip/setup.py/rmgeneric
5,139
def list_commands(): """ List the commands available. """ commands = [] for f in listdir(_commands_dir): if isdir(join(_commands_dir, f)): continue if not f.endswith('.py'): continue try: commands.append(get_command(f.split('.')[0])) ...
ImportError
dataset/ETHPy150Open robmadole/jig/src/jig/commands/base.py/list_commands
5,140
def add_plugin(pm, plugin, gitdir): """ Adds a plugin by filename or URL. Where ``pm`` is an instance of :py:class:`PluginManager` and ``plugin`` is either the URL to a Git Jig plugin repository or the file name of a Jig plugin. The ``gitdir`` is the path to the Git repository which will be use...
IndexError
dataset/ETHPy150Open robmadole/jig/src/jig/commands/base.py/add_plugin
5,141
def __init__(self, argv): """ Parse the command line arguments and call process with the results. Where argv is a split string. See :py:module:`shlex`. """ args = self.parser.parse_args(argv) # Setup something our command can use to send output self.view = creat...
NotImplementedError
dataset/ETHPy150Open robmadole/jig/src/jig/commands/base.py/BaseCommand.__init__
5,142
def read_from_which_host( client, pref, tag_sets=None, ): """Read from a client with the given Read Preference. Return the 'host:port' which was read from. :Parameters: - `client`: A MongoClient - `mode`: A ReadPreference - `tag_sets`: List of dicts of tags for da...
StopIteration
dataset/ETHPy150Open mongodb/mongo-python-driver/test/utils.py/read_from_which_host
5,143
def perform_destroy(self, instance): user = self.request.user comment = self.get_comment() try: comment.retract_report(user, save=True) except __HOLE__ as error: raise ValidationError(error.message)
ValueError
dataset/ETHPy150Open CenterForOpenScience/osf.io/api/comments/views.py/CommentReportDetail.perform_destroy
5,144
def getAvailablePluginModules(pluginPath = None): """ Determine the available plugin modules on the system. @returns a list of found plugins """ if pluginPath is None: pluginPath = Resource.getPath("plugins", required = True) if pluginPath is None: return [] if not pluginP...
ImportError
dataset/ETHPy150Open skyostil/tracy/src/analyzer/Plugin.py/getAvailablePluginModules
5,145
def _loadPlugins(analyzer, plugin, pluginClass): assert type(plugin) == type(sys) # Check that we fullfil the plugin's project requirements try: if not analyzer.project.config.name.lower().startswith(plugin.requiredLibrary): return [] except AttributeError: pass try: plugins...
AttributeError
dataset/ETHPy150Open skyostil/tracy/src/analyzer/Plugin.py/_loadPlugins
5,146
def check_hexstring(opt): """ Return the calculated CRC sum of a hex string. """ if opt.undefined_crc_parameters: sys.stderr.write("{0:s}: error: undefined parameters\n".format(sys.argv[0])) sys.exit(1) if len(opt.check_string) % 2 != 0: opt.check_string = "0" + opt.check_str...
TypeError
dataset/ETHPy150Open tpircher/pycrc/pycrc.py/check_hexstring
5,147
def check_file(opt): """ Calculate the CRC of a file. This algorithm uses the table_driven CRC algorithm. """ if opt.undefined_crc_parameters: sys.stderr.write("{0:s}: error: undefined parameters\n".format(sys.argv[0])) sys.exit(1) alg = Crc( width=opt.width, poly=opt.pol...
IOError
dataset/ETHPy150Open tpircher/pycrc/pycrc.py/check_file
5,148
def write_file(filename, out_str): """ Write the content of out_str to filename. """ try: out_file = open(filename, "w") out_file.write(out_str) out_file.close() except __HOLE__: sys.stderr.write("{0:s}: error: cannot write to file {1:s}\n".format(sys.argv[0], filenam...
IOError
dataset/ETHPy150Open tpircher/pycrc/pycrc.py/write_file
5,149
@patch def add_braces_to_openid_regex(): try: import openid.urinorm as urinorm except __HOLE__: return if hasattr(urinorm, 'uri_illegal_char_re'): if urinorm.uri_illegal_char_re.search("{"): # Invalid regexp for RedIRIS. Try to avoid it. urinorm.uri_illegal_c...
ImportError
dataset/ETHPy150Open weblabdeusto/weblabdeusto/server/src/voodoo/patcher.py/add_braces_to_openid_regex
5,150
def main(): ''' Store configuration and interfaces into the datastore How to run this from command line: bin/store_interfaces -s system name [ -of filename | -sf filename | -fc true|false] -of Load object definition file -sf Load service definition file -fc Force clean the d...
ValueError
dataset/ETHPy150Open ooici/pyon/scripts/store_interfaces.py/main
5,151
def _weight_by_vector(trajectories, w_vector): r"""weights the values of `trajectories` given a weighting vector `w_vector`. Each value in `trajectories` will be weighted by the 'rate of change' to 'optimal rate of change' ratio. The 'rate of change' of a vector measures how each point in the vecto...
TypeError
dataset/ETHPy150Open biocore/scikit-bio/skbio/stats/gradient.py/_weight_by_vector
5,152
@experimental(as_of="0.4.0") def __init__(self, coords, prop_expl, metadata_map, trajectory_categories=None, sort_category=None, axes=3, weighted=False): if not trajectory_categories: # If trajectory_categories is not provided, use all the categories ...
ValueError
dataset/ETHPy150Open biocore/scikit-bio/skbio/stats/gradient.py/GradientANOVA.__init__
5,153
def _get_group_trajectories(self, group_name, sids): r"""Compute the trajectory results for `group_name` containing the samples `sids`. Weights the data if `self._weighted` is True and ``len(sids) > 1`` Parameters ---------- group_name : str The name of the ...
ValueError
dataset/ETHPy150Open biocore/scikit-bio/skbio/stats/gradient.py/GradientANOVA._get_group_trajectories
5,154
def _fileobj_to_fd(fileobj): """Return a file descriptor from a file object. Parameters: fileobj -- file object or file descriptor Returns: corresponding file descriptor Raises: ValueError if the object is invalid """ if isinstance(fileobj, six.integer_types): fd = fileobj...
TypeError
dataset/ETHPy150Open dpkp/kafka-python/kafka/selectors34.py/_fileobj_to_fd
5,155
def __getitem__(self, fileobj): try: fd = self._selector._fileobj_lookup(fileobj) return self._selector._fd_to_key[fd] except __HOLE__: raise KeyError("{0!r} is not registered".format(fileobj))
KeyError
dataset/ETHPy150Open dpkp/kafka-python/kafka/selectors34.py/_SelectorMapping.__getitem__
5,156
def get_key(self, fileobj): """Return the key associated to a registered file object. Returns: SelectorKey for this file object """ mapping = self.get_map() if mapping is None: raise RuntimeError('Selector is closed') try: return mapping[f...
KeyError
dataset/ETHPy150Open dpkp/kafka-python/kafka/selectors34.py/BaseSelector.get_key
5,157
def _fileobj_lookup(self, fileobj): """Return a file descriptor from a file object. This wraps _fileobj_to_fd() to do an exhaustive search in case the object is invalid but we still have it in our map. This is used by unregister() so we can unregister an object that was previou...
ValueError
dataset/ETHPy150Open dpkp/kafka-python/kafka/selectors34.py/_BaseSelectorImpl._fileobj_lookup
5,158
def unregister(self, fileobj): try: key = self._fd_to_key.pop(self._fileobj_lookup(fileobj)) except __HOLE__: raise KeyError("{0!r} is not registered".format(fileobj)) return key
KeyError
dataset/ETHPy150Open dpkp/kafka-python/kafka/selectors34.py/_BaseSelectorImpl.unregister
5,159
def modify(self, fileobj, events, data=None): # TODO: Subclasses can probably optimize this even further. try: key = self._fd_to_key[self._fileobj_lookup(fileobj)] except __HOLE__: raise KeyError("{0!r} is not registered".format(fileobj)) if events != key.events: ...
KeyError
dataset/ETHPy150Open dpkp/kafka-python/kafka/selectors34.py/_BaseSelectorImpl.modify
5,160
def _key_from_fd(self, fd): """Return the key associated to a given file descriptor. Parameters: fd -- file descriptor Returns: corresponding key, or None if not found """ try: return self._fd_to_key[fd] except __HOLE__: return No...
KeyError
dataset/ETHPy150Open dpkp/kafka-python/kafka/selectors34.py/_BaseSelectorImpl._key_from_fd
5,161
def unregister(self, fileobj): key = super(EpollSelector, self).unregister(fileobj) try: self._epoll.unregister(key.fd) except __HOLE__: # This can happen if the FD was closed since it # was registered. pass ...
IOError
dataset/ETHPy150Open dpkp/kafka-python/kafka/selectors34.py/EpollSelector.unregister
5,162
def select(self, timeout=None): if timeout is None: timeout = -1 elif timeout <= 0: timeout = 0 else: # epoll_wait() has a resolution of 1 millisecond, round away # from zero to wait *at least* timeout seconds. ...
IOError
dataset/ETHPy150Open dpkp/kafka-python/kafka/selectors34.py/EpollSelector.select
5,163
def select(self, timeout=None): if timeout is None: timeout = None elif timeout <= 0: timeout = 0 else: # devpoll() has a resolution of 1 millisecond, round away from # zero to wait *at least* timeout seconds. ...
OSError
dataset/ETHPy150Open dpkp/kafka-python/kafka/selectors34.py/DevpollSelector.select
5,164
def unregister(self, fileobj): key = super(KqueueSelector, self).unregister(fileobj) if key.events & EVENT_READ: kev = select.kevent(key.fd, select.KQ_FILTER_READ, select.KQ_EV_DELETE) try: self._kqueue.contr...
OSError
dataset/ETHPy150Open dpkp/kafka-python/kafka/selectors34.py/KqueueSelector.unregister
5,165
def select(self, timeout=None): timeout = None if timeout is None else max(timeout, 0) max_ev = len(self._fd_to_key) ready = [] try: kev_list = self._kqueue.control(None, max_ev, timeout) except __HOLE__ as exc: if exc.errno == ...
OSError
dataset/ETHPy150Open dpkp/kafka-python/kafka/selectors34.py/KqueueSelector.select
5,166
def __getattr__(self, name): try: return tuple([(self.x, self.y)['xy'.index(c)] \ for c in name]) except __HOLE__: raise AttributeError, name
ValueError
dataset/ETHPy150Open ardekantur/pyglet/contrib/toys/euclid.py/Vector2.__getattr__
5,167
def __setattr__(self, name, value): if len(name) == 1: object.__setattr__(self, name, value) else: try: l = [self.x, self.y] for c, v in map(None, name, value): l['xy'.index(c)] = v ...
ValueError
dataset/ETHPy150Open ardekantur/pyglet/contrib/toys/euclid.py/Vector2.__setattr__
5,168
def __getattr__(self, name): try: return tuple([(self.x, self.y, self.z)['xyz'.index(c)] \ for c in name]) except __HOLE__: raise AttributeError, name
ValueError
dataset/ETHPy150Open ardekantur/pyglet/contrib/toys/euclid.py/Vector3.__getattr__
5,169
def __setattr__(self, name, value): if len(name) == 1: object.__setattr__(self, name, value) else: try: l = [self.x, self.y, self.z] for c, v in map(None, name, value): l['xyz'.index(c)] = v ...
ValueError
dataset/ETHPy150Open ardekantur/pyglet/contrib/toys/euclid.py/Vector3.__setattr__
5,170
def force_bytes(s): try: return s.encode('utf-8') except (AttributeError, __HOLE__): return s
UnicodeDecodeError
dataset/ETHPy150Open gavinwahl/sdb/sdb/util.py/force_bytes
5,171
def _obtain_lock_or_raise(self): """Create a lock file as flag for other instances, mark our instance as lock-holder :raise IOError: if a lock was already present or a lock file could not be written""" if self._has_lock(): return lock_file = self._lock_file_path() if...
OSError
dataset/ETHPy150Open codeinn/vcs/vcs/utils/lockfiles.py/LockFile._obtain_lock_or_raise
5,172
def _release_lock(self): """Release our lock if we have one""" if not self._has_lock(): return # if someone removed our file beforhand, lets just flag this issue # instead of failing, to make it more usable. lfp = self._lock_file_path() try: # on ...
OSError
dataset/ETHPy150Open codeinn/vcs/vcs/utils/lockfiles.py/LockFile._release_lock
5,173
def _supportsSymlinks(self): """ Check for symlink support usable for Twisted's purposes. @return: C{True} if symlinks are supported on the current platform, otherwise C{False}. @rtype: L{bool} """ if self.isWindows(): # We do the isWindows()...
AttributeError
dataset/ETHPy150Open twisted/twisted/twisted/python/runtime.py/Platform._supportsSymlinks
5,174
def supportsThreads(self): """ Can threads be created? @return: C{True} if the threads are supported on the current platform. @rtype: C{bool} """ try: return imp.find_module(_threadModule)[0] is None except __HOLE__: return False
ImportError
dataset/ETHPy150Open twisted/twisted/twisted/python/runtime.py/Platform.supportsThreads
5,175
def supportsINotify(self): """ Return C{True} if we can use the inotify API on this platform. @since: 10.1 """ try: from twisted.python._inotify import INotifyError, init except __HOLE__: return False if self.isDocker(): retur...
ImportError
dataset/ETHPy150Open twisted/twisted/twisted/python/runtime.py/Platform.supportsINotify
5,176
def onVerify(self, verify): try: receivingServer = jid.JID(verify['from']).host originatingServer = jid.JID(verify['to']).host except (__HOLE__, jid.InvalidFormat): raise error.StreamError('improper-addressing') if originatingServer not in self.service.domain...
KeyError
dataset/ETHPy150Open ralphm/wokkel/wokkel/server.py/XMPPServerListenAuthenticator.onVerify
5,177
@jsexpose(body_cls=TriggerTypeAPI, status_code=http_client.CREATED) def post(self, triggertype): """ Create a new triggertype. Handles requests: POST /triggertypes/ """ try: triggertype_db = TriggerTypeAPI.to_model(triggertype) ...
ValidationError
dataset/ETHPy150Open StackStorm/st2/st2api/st2api/controllers/v1/triggers.py/TriggerTypeController.post
5,178
@jsexpose(arg_types=[str], body_cls=TriggerTypeAPI) def put(self, triggertype_ref_or_id, triggertype): triggertype_db = self._get_by_ref_or_id(ref_or_id=triggertype_ref_or_id) triggertype_id = triggertype_db.id try: validate_not_part_of_system_pack(triggertype_db) except...
ValueError
dataset/ETHPy150Open StackStorm/st2/st2api/st2api/controllers/v1/triggers.py/TriggerTypeController.put
5,179
@staticmethod def _create_shadow_trigger(triggertype_db): try: trigger_type_ref = triggertype_db.get_reference().ref trigger = {'name': triggertype_db.name, 'pack': triggertype_db.pack, 'type': trigger_type_ref, 'pa...
ValueError
dataset/ETHPy150Open StackStorm/st2/st2api/st2api/controllers/v1/triggers.py/TriggerTypeController._create_shadow_trigger
5,180
@jsexpose(body_cls=TriggerAPI, status_code=http_client.CREATED) def post(self, trigger): """ Create a new trigger. Handles requests: POST /triggers/ """ try: trigger_db = TriggerService.create_trigger_db(trigger) except (__HOLE__, ...
ValidationError
dataset/ETHPy150Open StackStorm/st2/st2api/st2api/controllers/v1/triggers.py/TriggerController.post
5,181
@jsexpose(arg_types=[str], body_cls=TriggerAPI) def put(self, trigger_id, trigger): trigger_db = TriggerController.__get_by_id(trigger_id) try: if trigger.id is not None and trigger.id is not '' and trigger.id != trigger_id: LOG.warning('Discarding mismatched id=%s found ...
ValidationError
dataset/ETHPy150Open StackStorm/st2/st2api/st2api/controllers/v1/triggers.py/TriggerController.put
5,182
@staticmethod def __get_by_id(trigger_id): try: return Trigger.get_by_id(trigger_id) except (__HOLE__, ValidationError): LOG.exception('Database lookup for id="%s" resulted in exception.', trigger_id) abort(http_client.NOT_FOUND)
ValueError
dataset/ETHPy150Open StackStorm/st2/st2api/st2api/controllers/v1/triggers.py/TriggerController.__get_by_id
5,183
@staticmethod def __get_by_name(trigger_name): try: return [Trigger.get_by_name(trigger_name)] except __HOLE__ as e: LOG.debug('Database lookup for name="%s" resulted in exception : %s.', trigger_name, e) return []
ValueError
dataset/ETHPy150Open StackStorm/st2/st2api/st2api/controllers/v1/triggers.py/TriggerController.__get_by_name
5,184
def savitzky_golay(y, window_size, order=2, deriv=0, rate=1): if window_size % 2 != 1: window_size += 1 try: window_size = np.abs(np.int(window_size)) order = np.abs(np.int(order)) except __HOLE__, msg: raise ValueError("window_size and order have to be of type int") if window_...
ValueError
dataset/ETHPy150Open taoliu/MACS/test/test_callsummits.py/savitzky_golay
5,185
def setUp(self): """ Patch the L{ls} module's time function so the results of L{lsLine} are deterministic. """ self.now = 123456789 def fakeTime(): return self.now self.patch(ls, 'time', fakeTime) # Make sure that the timezone ends up the same...
KeyError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/conch/test/test_cftp.py/ListingTests.setUp
5,186
def send(self, template_name, from_email, recipient_list, context, cc=None, bcc=None, fail_silently=False, headers=None, template_prefix=None, template_suffix=None, template_dir=None, file_extension=None, auth_user=None, auth_password=None, ...
NameError
dataset/ETHPy150Open BradWhittington/django-templated-email/templated_email/backends/vanilla_django.py/TemplateBackend.send
5,187
def recv_message(**kwargs): connection = BrokerConnection('amqp://%(mq_user)s:%(mq_password)s@' '%(mq_host)s:%(mq_port)s//' % kwargs['mq_args']) with connection as conn: try: SomeConsumer(conn, **kwargs).run() except...
KeyboardInterrupt
dataset/ETHPy150Open openstack/entropy/entropy/examples/repair/vmbooter.py/recv_message
5,188
@classmethod def get_date(cls, request, date_type): date_str = cls.get_date_str(request, date_type) if date_str is not None: try: return datetime.datetime.combine( iso_string_to_date(date_str), datetime.time()) except __HOLE__: ...
ValueError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/accounting/filters.py/DateRangeFilter.get_date
5,189
@property def method(self): ''' Returns the zmq method constant. >>> ZeroSetup('pull', 8000).method == zmq.PULL True ''' try: return getattr(zmq, self._method.upper()) except __HOLE__: raise UnsupportedZmqMethod('Unsupported ZMQ method'...
AttributeError
dataset/ETHPy150Open philipbergen/zero/py/zero/__init__.py/ZeroSetup.method
5,190
@property def point(self): ''' Returns the ZMQ socket string. >>> ZeroSetup('pull', 'tcp://other.host.net:9000') ZeroSetup('pull', 'tcp://other.host.net:9000').binding(True) ''' if str(self._point)[:1] == ':': self._point = self._point[1:] try: ...
ValueError
dataset/ETHPy150Open philipbergen/zero/py/zero/__init__.py/ZeroSetup.point
5,191
def zauto(zero, loops, wait=False): 'Keep listening and sending until the loop ends. All received objects are yielded.' try: if zero.setup.replies: for rep, msg in izip(loops, zero): yield msg zero(rep) elif zero.setup.transmits: for msg in...
KeyboardInterrupt
dataset/ETHPy150Open philipbergen/zero/py/zero/__init__.py/zauto
5,192
def handleRequest(self, req): """handles a request by calling the appropriete method the service exposes""" name = req["method"] params = req["params"] id=req["id"] obj=None try: #to get a callable obj obj = getMethodByName(self.service, name) except ...
TypeError
dataset/ETHPy150Open anandology/pyjamas/examples/jsonrpc/public/services/jsonrpc/__init__.py/SimpleServiceHandler.handleRequest
5,193
def decode(self, stream, encoding, fallback=None): if not hasattr(stream, 'decode'): return stream try: return stream.decode(encoding) except UnicodeDecodeError: if fallback: for enc in fallback: try: ...
UnicodeDecodeError
dataset/ETHPy150Open SublimeGit/SublimeGit/sgit/cmd.py/Cmd.decode
5,194
def cmd(self, cmd, stdin=None, cwd=None, ignore_errors=False, encoding=None, fallback=None): command = self.build_command(cmd) environment = self.env() encoding = encoding or get_setting('encoding', 'utf-8') fallback = fallback or get_setting('fallback_encodings', []) try: ...
UnicodeDecodeError
dataset/ETHPy150Open SublimeGit/SublimeGit/sgit/cmd.py/Cmd.cmd
5,195
def cmd_async(self, cmd, cwd=None, **callbacks): command = self.build_command(cmd) environment = self.env() encoding = get_setting('encoding', 'utf-8') fallback = get_setting('fallback_encodings', []) def async_inner(cmd, cwd, encoding, on_data=None, on_complete=None, on_error=N...
UnicodeDecodeError
dataset/ETHPy150Open SublimeGit/SublimeGit/sgit/cmd.py/Cmd.cmd_async
5,196
def get_id(self): """ Return the primary key for the model instance. If the model is unsaved, then this value will be ``None``. """ try: return getattr(self, self._primary_key) except __HOLE__: return None
KeyError
dataset/ETHPy150Open coleifer/walrus/walrus/models.py/Model.get_id
5,197
def delete(self, for_update=False): """ Delete the given model instance. """ hash_key = self.get_hash_id() try: original_instance = self.load(hash_key, convert_key=False) except __HOLE__: return # Remove from the `all` index. all_i...
KeyError
dataset/ETHPy150Open coleifer/walrus/walrus/models.py/Model.delete
5,198
def contains(self, task_id, node_id=None, result=None): try: if result is None and node_id is None: return task_id in self._d elif result is None: return node_id in self._d[task_id] else: return result in self._d[task_id][node_i...
KeyError
dataset/ETHPy150Open BasicWolf/kaylee/kaylee/contrib/storages.py/MemoryTemporalStorage.contains
5,199
def add(self, task_id, result): try: self._d[task_id].append(result) except __HOLE__: self._d[task_id] = [result, ] self._total_count += 1
KeyError
dataset/ETHPy150Open BasicWolf/kaylee/kaylee/contrib/storages.py/MemoryPermanentStorage.add