Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
2,600
def pytest_configure(config): mode = config.getvalue("assertmode") if config.getvalue("noassert") or config.getvalue("nomagic"): mode = "plain" if mode == "rewrite": try: import ast # noqa except __HOLE__: mode = "reinterp" else: # Both Jy...
ImportError
dataset/ETHPy150Open pytest-dev/pytest/_pytest/assertion/__init__.py/pytest_configure
2,601
def warn_about_missing_assertion(mode): try: assert False except __HOLE__: pass else: if mode == "rewrite": specifically = ("assertions which are not in test modules " "will be ignored") else: specifically = "failing tests m...
AssertionError
dataset/ETHPy150Open pytest-dev/pytest/_pytest/assertion/__init__.py/warn_about_missing_assertion
2,602
def _write(self, str): """Write a string to the modem.""" self._log(repr(str), "write") try: self.device.write(str) # if the device couldn't be written to, # wrap the error in something that can # sensibly be caught at a higher level except ...
OSError
dataset/ETHPy150Open sahana/eden/modules/pygsm/gsmmodem.py/GsmModem._write
2,603
def test_noPermission(self): """ Check it keeps working when permission on dir changes. """ log = logfile.LogFile(self.name, self.dir) log.write("abc") # change permissions so rotation would fail os.chmod(self.dir, 0555) # if this succeeds, chmod doesn't...
IOError
dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/test/test_logfile.py/LogFileTestCase.test_noPermission
2,604
def main(): import sys, re args = sys.argv[1:] iptfile = args and args[0] or "Python/graminit.c" if len(args) > 1: optfile = args[1] else: optfile = "Lib/keyword.py" # scan the source file for keywords with open(iptfile) as fp: strprog = re.compile('"([^"]+)"') lines = [] ...
ValueError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/keyword.py/main
2,605
def __new__(cls, *args, **kw): error = BotoServerError(*args, **kw) try: newclass = globals()[error.error_code] except __HOLE__: newclass = ResponseError obj = newclass.__new__(newclass, *args, **kw) obj.__dict__.update(error.__dict__) return obj
KeyError
dataset/ETHPy150Open darcyliu/storyboard/boto/mws/exception.py/ResponseErrorFactory.__new__
2,606
def post(self, step_id): jobstep = JobStep.query.options( joinedload('project', innerjoin=True), ).get(step_id) if jobstep is None: return '', 404 args = self.post_parser.parse_args() current_datetime = args.date or datetime.utcnow() if args.res...
ValueError
dataset/ETHPy150Open dropbox/changes/changes/api/jobstep_details.py/JobStepDetailsAPIView.post
2,607
def read_raw_gpsd_data(self): """Read the newest data from gpsd and return it""" try: if self.session.waiting(): report = self.session.next() return report else: return None except __HOLE__: raise GPSDError()
StopIteration
dataset/ETHPy150Open FishPi/FishPi-POCV---Command---Control/fishpi/sensor/gpsd/gpsd_interface.py/gpsdInterface.read_raw_gpsd_data
2,608
def _convert_to_number_without_precision(self, item): try: if utils.is_jython: item = self._handle_java_numbers(item) return float(item) except: error = utils.get_error_message() try: return float(self._convert_to_integer(it...
RuntimeError
dataset/ETHPy150Open shellderp/sublime-robot-plugin/lib/robot/libraries/BuiltIn.py/_Converter._convert_to_number_without_precision
2,609
def _get_var_name(self, orig): name = self._resolve_possible_variable(orig) try: return self._unescape_variable_if_needed(name) except __HOLE__: raise RuntimeError("Invalid variable syntax '%s'" % orig)
ValueError
dataset/ETHPy150Open shellderp/sublime-robot-plugin/lib/robot/libraries/BuiltIn.py/_Variables._get_var_name
2,610
def _resolve_possible_variable(self, name): try: resolved = self._variables[name] return self._unescape_variable_if_needed(resolved) except (KeyError, __HOLE__, DataError): return name
ValueError
dataset/ETHPy150Open shellderp/sublime-robot-plugin/lib/robot/libraries/BuiltIn.py/_Variables._resolve_possible_variable
2,611
def call_method(self, object, method_name, *args): """Calls the named method of the given object with the provided arguments. The possible return value from the method is returned and can be assigned to a variable. Keyword fails both if the object does not have a method with the given n...
AttributeError
dataset/ETHPy150Open shellderp/sublime-robot-plugin/lib/robot/libraries/BuiltIn.py/_Misc.call_method
2,612
def test_RowSetTable(): row_set_json = { 'etag': 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee', 'headers': [ {'columnType': 'STRING', 'id': '353', 'name': 'name'}, {'columnType': 'DOUBLE', 'id': '355', 'name': 'x'}, {'columnType': 'DOUBLE', 'id': '3020', 'name': 'y'}, {'...
ImportError
dataset/ETHPy150Open Sage-Bionetworks/synapsePythonClient/tests/unit/unit_test_tables.py/test_RowSetTable
2,613
def test_as_table_columns(): try: import pandas as pd df = pd.DataFrame({ 'foobar' : ("foo", "bar", "baz", "qux", "asdf"), 'x' : tuple(math.pi*i for i in range(5)), 'n' : (101, 202, 303, 404, 505), 'really' : (False, True, False, True, False), ...
ImportError
dataset/ETHPy150Open Sage-Bionetworks/synapsePythonClient/tests/unit/unit_test_tables.py/test_as_table_columns
2,614
def test_pandas_to_table(): try: import pandas as pd df = pd.DataFrame(dict(a=[1,2,3], b=["c", "d", "e"])) schema = Schema(name="Baz", parent="syn12345", columns=as_table_columns(df)) print("\n", df, "\n\n") ## A dataframe with no row id and version table = Table(sc...
ImportError
dataset/ETHPy150Open Sage-Bionetworks/synapsePythonClient/tests/unit/unit_test_tables.py/test_pandas_to_table
2,615
def test_csv_table(): ## Maybe not truly a unit test, but here because it doesn't do ## network IO to synapse data = [["1", "1", "John Coltrane", 1926, 8.65, False], ["2", "1", "Miles Davis", 1926, 9.87, False], ["3", "1", "Bill Evans", 1929, 7.65, False], ["4", "...
ImportError
dataset/ETHPy150Open Sage-Bionetworks/synapsePythonClient/tests/unit/unit_test_tables.py/test_csv_table
2,616
def test_list_of_rows_table(): data = [["John Coltrane", 1926, 8.65, False], ["Miles Davis", 1926, 9.87, False], ["Bill Evans", 1929, 7.65, False], ["Paul Chambers", 1935, 5.14, False], ["Jimmy Cobb", 1929, 5.78, True], ["Scott LaFaro", 1936...
ImportError
dataset/ETHPy150Open Sage-Bionetworks/synapsePythonClient/tests/unit/unit_test_tables.py/test_list_of_rows_table
2,617
def test_aggregate_query_result_to_data_frame(): try: import pandas as pd class MockSynapse(object): def _queryTable(self, query, limit=None, offset=None, isConsistent=True, partMask=None): return {'concreteType': 'org.sagebionetworks.repo.model.table.QueryResultBundle'...
ImportError
dataset/ETHPy150Open Sage-Bionetworks/synapsePythonClient/tests/unit/unit_test_tables.py/test_aggregate_query_result_to_data_frame
2,618
@classmethod def Open(cls, fd, component, pathspec=None, progress_callback=None, full_pathspec=None): """Try to correct the casing of component. This method is called when we failed to open the component directly. We try to transform the component into something which is likely to work. I...
IOError
dataset/ETHPy150Open google/grr/grr/client/vfs.py/VFSHandler.Open
2,619
def Run(self): VFS_HANDLERS.clear() for handler in VFSHandler.classes.values(): if handler.auto_register: VFS_HANDLERS[handler.supported_pathtype] = handler VFS_VIRTUALROOTS.clear() vfs_virtualroots = config_lib.CONFIG["Client.vfs_virtualroots"] for vfs_virtualroot in vfs_virtualroots...
ValueError
dataset/ETHPy150Open google/grr/grr/client/vfs.py/VFSInit.Run
2,620
def VFSOpen(pathspec, progress_callback=None): """Expands pathspec to return an expanded Path. A pathspec is a specification of how to access the file by recursively opening each part of the path by different drivers. For example the following pathspec: pathtype: OS path: "/dev/sda1" nested_path { p...
IOError
dataset/ETHPy150Open google/grr/grr/client/vfs.py/VFSOpen
2,621
def subclass_iterator(cls, _seen=None): """ Generator over all subclasses of a given class, in depth first order. Source: http://code.activestate.com/recipes/576949-find-all-subclasses-of-a-given-class/ """ if not isinstance(cls, type): raise TypeError('_subclass_iterator must be called wi...
TypeError
dataset/ETHPy150Open Stiivi/brewery/brewery/utils.py/subclass_iterator
2,622
def __init__(self, file_name='-', read_values=False, debug=False): self._debug = debug self._read_values = read_values if file_name == '-': fh = sys.stdin else: try: fh = open(file_name) except __HOLE__ as ex: raise Thri...
IOError
dataset/ETHPy150Open pinterest/thrift-tools/thrift_tools/thrift_file.py/ThriftFile.__init__
2,623
def upgrade(): op.create_table('file', sa.Column('key', sa.Integer(), nullable=False), sa.Column('revision_key', sa.Integer(), nullable=False, index=True), sa.Column('path', sa.Text(), nullable=False, index=True), sa.Column('old_path', sa.Text(), index=True), sa.Column('status', sa.String(length...
ValueError
dataset/ETHPy150Open openstack/gertty/gertty/alembic/versions/50344aecd1c2_add_files_table.py/upgrade
2,624
def _from_native_list(self, condition_list): ''' These arrive in one of three formats: - ["content-length-range", 1048579, 10485760] - ["content-length-range", 1024] - ["starts-with", "$key", "user/eric/"] Returns an object with these attributes set: - op...
IndexError
dataset/ETHPy150Open bodylabs/drf-to-s3/drf_to_s3/naive_serializers.py/NaivePolicyConditionField._from_native_list
2,625
def validate(self, attrs): ''' 1. Disallow multiple conditions with the same element name 2. Use introspection to validate individual conditions which are present. ''' from .util import duplicates_in conditions = attrs.get('conditions', []) errors = {} all...
ValidationError
dataset/ETHPy150Open bodylabs/drf-to-s3/drf_to_s3/naive_serializers.py/NaivePolicySerializer.validate
2,626
@webapi_check_local_site @webapi_login_required @webapi_request_fields( required=dict({ 'screenshot_id': { 'type': int, 'description': 'The ID of the screenshot being commented on.', }, 'x': { 'type': int, ...
ObjectDoesNotExist
dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/webapi/resources/review_screenshot_comment.py/ReviewScreenshotCommentResource.create
2,627
@webapi_check_local_site @webapi_login_required @webapi_response_errors(DOES_NOT_EXIST, NOT_LOGGED_IN, PERMISSION_DENIED) @webapi_request_fields( optional=dict({ 'x': { 'type': int, 'description': 'The X location for the comment.', }, ...
ObjectDoesNotExist
dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/webapi/resources/review_screenshot_comment.py/ReviewScreenshotCommentResource.update
2,628
def is_matching(self, name): """Match given name with the step name.""" try: return bool(self.parser.parse(name)) except __HOLE__: return False
ValueError
dataset/ETHPy150Open pytest-dev/pytest-bdd/pytest_bdd/parsers.py/parse.is_matching
2,629
def __write_read(self, write_fn, read_fn, ep, length = 8): intf = self.backend.get_interface_descriptor(self.dev, 0, 0, 0).bInterfaceNumber for data in (utils.get_array_data1(length), utils.get_array_data2(length)): length = len(data) * data.itemsize try: ret = w...
NotImplementedError
dataset/ETHPy150Open walac/pyusb/tests/test_backend.py/BackendTest.__write_read
2,630
def run(self, batch): """ Execute a collection of jobs and return all results. :param batch: A :class:`.Batch` of jobs. :rtype: :class:`list` """ response = self.post(batch) try: results = [] for result_data in response.content: re...
ValueError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/ext/batman/batch.py/BatchRunner.run
2,631
def make_zipfile (base_name, base_dir, verbose=0, dry_run=0): """Create a zip file from all the files under 'base_dir'. The output zip file will be named 'base_dir' + ".zip". Uses either the "zipfile" Python module (if available) or the InfoZIP "zip" utility (if installed and found on the default sear...
ImportError
dataset/ETHPy150Open babble/babble/include/jython/Lib/distutils/archive_util.py/make_zipfile
2,632
def make_archive (base_name, format, root_dir=None, base_dir=None, verbose=0, dry_run=0): """Create an archive file (eg. zip or tar). 'base_name' is the name of the file to create, minus any format-specific extension; 'format' is the archive format: one of "zip", "tar", ...
KeyError
dataset/ETHPy150Open babble/babble/include/jython/Lib/distutils/archive_util.py/make_archive
2,633
def reset(self): codecs.StreamReader.reset(self) try: del self.decode except __HOLE__: pass
AttributeError
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/encodings/utf_32.py/StreamReader.reset
2,634
def _build_contest_kwargs(self, race): office = race.attrib['RaceTitle'].split(', ')[0].strip() try: district = race.attrib['District'] except __HOLE__: if 'District' in race.attrib['RaceTitle']: district = race.attrib['RaceTitle'].split(', ')[1].split('Di...
KeyError
dataset/ETHPy150Open openelections/openelections-core/openelex/us/nv/load.py/NVXmlLoader._build_contest_kwargs
2,635
def pop(self, nbytes): """ pops packets with _at least_ nbytes of payload """ size = 0 popped = [] with self._lock_packets: while size < nbytes: try: packet = self._packets.pop(0) size += len(packet.data.data) ...
IndexError
dataset/ETHPy150Open pinterest/thrift-tools/thrift_tools/sniffer.py/Stream.pop
2,636
def _handle_packet(self, packet): try: ip_p = get_ip_packet(packet.load, 0, self._port) except __HOLE__: return ip_data = getattr(ip_p, 'data', None) if ip_data is None: return if ip_data.sport != self._port and ip_data.dport != self._port: ...
ValueError
dataset/ETHPy150Open pinterest/thrift-tools/thrift_tools/sniffer.py/Sniffer._handle_packet
2,637
def __getattr__(self, attr): try: return self[self.attrs.index(attr)] except __HOLE__: raise AttributeError
ValueError
dataset/ETHPy150Open babble/babble/include/jython/Lib/pwd.py/struct_passwd.__getattr__
2,638
def get_context(self, page, range_gap=5): try: page = int(page) except (ValueError, __HOLE__), exc: raise InvalidPage, exc try: paginator = self.page(page) except EmptyPage: return { 'EMPTY_PAGE': True, ...
TypeError
dataset/ETHPy150Open dcramer/django-paging/paging/paginators.py/BetterPaginator.get_context
2,639
def page(self, number): "Returns a Page object for the given 1-based page number." try: number = int(number) except ValueError: raise PageNotAnInteger('That page number is not an integer') bottom = (number - 1) * self.per_page top = bottom + self.per_page ...
AssertionError
dataset/ETHPy150Open dcramer/django-paging/paging/paginators.py/EndlessPaginator.page
2,640
@task @runs_once # do this once, locally def compile_redis(): "Compile redis locally" tempdir = tempfile.mkdtemp() try: os.remove('redis-server') except __HOLE__: pass try: os.remove('redis-cli') except OSError: pass with lcd(tempdir): local('wget ht...
OSError
dataset/ETHPy150Open PaulMcMillan/toorcon_2013/configurator/fabfile/master.py/compile_redis
2,641
def __call__(self): dirname = os.path.dirname(self._filename.dest) try: if not os.path.isdir(dirname): try: os.makedirs(dirname) except __HOLE__: # It's possible that between the if check and the makedirs ...
OSError
dataset/ETHPy150Open aws/aws-cli/awscli/customizations/s3/tasks.py/CreateLocalFileTask.__call__
2,642
def fetch(args): """ %prog fetch "query" OR %prog fetch queries.txt Please provide a UniProt compatible `query` to retrieve data. If `query` contains spaces, please remember to "quote" it. You can also specify a `filename` which contains queries, one per line. Follow this syntax <...
KeyError
dataset/ETHPy150Open tanghaibao/jcvi/apps/uniprot.py/fetch
2,643
def _generate_dispatch(cls): """Return an optimized visit dispatch function for the cls for use by the compiler. """ if '__visit_name__' in cls.__dict__: visit_name = cls.__visit_name__ if isinstance(visit_name, str): # There is an optimization opportunity here because the ...
AttributeError
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/sql/visitors.py/_generate_dispatch
2,644
def get_filter_bbox(self, request): bbox_string = request.query_params.get(self.bbox_param, None) if not bbox_string: return None try: p1x, p1y, p2x, p2y = (float(n) for n in bbox_string.split(',')) except __HOLE__: raise ParseError('Invalid bbox stri...
ValueError
dataset/ETHPy150Open djangonauts/django-rest-framework-gis/rest_framework_gis/filters.py/InBBoxFilter.get_filter_bbox
2,645
def get_filter_bbox(self, request): tile_string = request.query_params.get(self.tile_param, None) if not tile_string: return None try: z, x, y = (int(n) for n in tile_string.split('/')) except __HOLE__: raise ParseError('Invalid tile string supplied f...
ValueError
dataset/ETHPy150Open djangonauts/django-rest-framework-gis/rest_framework_gis/filters.py/TMSTileFilter.get_filter_bbox
2,646
def get_filter_point(self, request): point_string = request.query_params.get(self.point_param, None) if not point_string: return None try: (x, y) = (float(n) for n in point_string.split(',')) except __HOLE__: raise ParseError('Invalid geometry string ...
ValueError
dataset/ETHPy150Open djangonauts/django-rest-framework-gis/rest_framework_gis/filters.py/DistanceToPointFilter.get_filter_point
2,647
def filter_queryset(self, request, queryset, view): filter_field = getattr(view, 'distance_filter_field', None) convert_distance_input = getattr(view, 'distance_filter_convert_meters', False) geoDjango_filter = 'dwithin' # use dwithin for points if not filter_field: return ...
ValueError
dataset/ETHPy150Open djangonauts/django-rest-framework-gis/rest_framework_gis/filters.py/DistanceToPointFilter.filter_queryset
2,648
def __new__(cls, *args): # pylint: disable=W0613, E1002 ''' We override `__new__` in our logging logger class in order to provide some additional features like expand the module name padding if length is being used, and also some Unicode fixes. This code overhead will only be e...
ValueError
dataset/ETHPy150Open saltstack/salt/salt/log/setup.py/SaltLoggingClass.__new__
2,649
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None): # Let's remove exc_info_on_loglevel from extra exc_info_on_loglevel = extra.pop('exc_info_on_loglevel') if not extra: # If nothing else is in extra, make it None ...
UnicodeDecodeError
dataset/ETHPy150Open saltstack/salt/salt/log/setup.py/SaltLoggingClass.makeRecord
2,650
def setup_logfile_logger(log_path, log_level='error', log_format=None, date_format=None): ''' Setup the logfile logger Since version 0.10.6 we support logging to syslog, some examples: tcp://localhost:514/LOG_USER tcp://localhost/LOG_DAEMON udp://localhost:...
IOError
dataset/ETHPy150Open saltstack/salt/salt/log/setup.py/setup_logfile_logger
2,651
def shutdown_multiprocessing_logging_listener(daemonizing=False): global __MP_LOGGING_QUEUE global __MP_LOGGING_QUEUE_PROCESS global __MP_LOGGING_LISTENER_CONFIGURED if daemonizing is False and __MP_IN_MAINPROCESS is True: # We're in the MainProcess and we're not daemonizing, return! # ...
IOError
dataset/ETHPy150Open saltstack/salt/salt/log/setup.py/shutdown_multiprocessing_logging_listener
2,652
def __process_multiprocessing_logging_queue(opts, queue): import salt.utils salt.utils.appendproctitle('MultiprocessingLoggingQueue') if salt.utils.is_windows(): # On Windows, creating a new process doesn't fork (copy the parent # process image). Due to this, we need to setup extended loggin...
KeyboardInterrupt
dataset/ETHPy150Open saltstack/salt/salt/log/setup.py/__process_multiprocessing_logging_queue
2,653
def _restoreConfig(self, cs, configRestoreList): # config files are cached, so we don't have to worry about not # restoring the same fileId/pathId twice for (pathId, newFileId, sha1, oldfile, newFileId, oldVersion, oldFileId, restoreContents) in configRestoreList: if cs....
KeyError
dataset/ETHPy150Open sassoftware/conary/conary/repository/repository.py/ChangeSetJob._restoreConfig
2,654
def _restoreNormal(self, cs, normalRestoreList, preRestored): ptrRestores = [] ptrRefsAdded = {} lastRestore = None # restore each pathId,fileId combo once while normalRestoreList: (pathId, fileId, sha1, restoreContents) = normalRestoreList.pop(0) if preRe...
KeyError
dataset/ETHPy150Open sassoftware/conary/conary/repository/repository.py/ChangeSetJob._restoreNormal
2,655
def users_filter(doc, users): try: return doc['form']['meta']['userID'] in users except __HOLE__: return False
KeyError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/reports/util.py/users_filter
2,656
def numcell(text, value=None, convert='int', raw=None): if value is None: try: value = int(text) if convert == 'int' else float(text) if math.isnan(value): text = '---' elif not convert == 'int': # assume this is a percentage column text = ...
ValueError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/reports/util.py/numcell
2,657
def get_max_age(response): """ Returns the max-age from the response Cache-Control header as an integer (or ``None`` if it wasn't found or wasn't an integer. """ if not response.has_header('Cache-Control'): return cc = dict([_to_tuple(el) for el in cc_delim_re.split(response['Cac...
TypeError
dataset/ETHPy150Open splunk/splunk-webframework/contrib/django/django/utils/cache.py/get_max_age
2,658
def set_to_cache(self): """ Add widget object to Django's cache. You may need to overwrite this method, to pickle all information that is required to serve your JSON response view. """ try: cache.set(self._get_cache_key(), { 'widget': self, ...
AttributeError
dataset/ETHPy150Open applegrew/django-select2/django_select2/forms.py/HeavySelect2Mixin.set_to_cache
2,659
def render_options(self, *args): """Render only selected options.""" try: selected_choices, = args except __HOLE__: # Signature contained `choices` prior to Django 1.10 choices, selected_choices = args choices = chain(self.choices, choices) else: ...
ValueError
dataset/ETHPy150Open applegrew/django-select2/django_select2/forms.py/HeavySelect2Mixin.render_options
2,660
def render_options(self, *args): """Render only selected options and set QuerySet from :class:`ModelChoicesIterator`.""" try: selected_choices, = args except __HOLE__: choices, selected_choices = args choices = chain(self.choices, choices) else: ...
ValueError
dataset/ETHPy150Open applegrew/django-select2/django_select2/forms.py/ModelSelect2Mixin.render_options
2,661
def test_compare_results(self): """Test that `compare` tests results correctly.""" with mock.patch.object(self, 'run_comparator') as comparator: MSG = {'id': (), 'context': (), 'file': 'file.js', 'signing_severity': 'low'} EXPECTED = {'matched': MSG, 'ignored'...
AssertionError
dataset/ETHPy150Open mozilla/addons-server/src/olympia/devhub/tests/test_utils.py/TestValidationComparator.test_compare_results
2,662
def code(): # file monitor server observer = Observer() # py yml file monitor patterns = ['*.py', '*demo.yml'] # '*' is necessary, and must in the first. restart_processor = ServerStarter([ {'cmd': 'rm -rf %s/*.log' % os.path.join(workspace, 'log'), 'is_daemon': False}, ...
KeyboardInterrupt
dataset/ETHPy150Open remyzane/flask-http-api/example/run.py/code
2,663
def __getattribute__(self, key): if key == "__dict__": return object.__getattribute__(self, key) try: # check the local cache first, overrides persistent storage return self.__dict__["_cache"].__getitem__(key) except __HOLE__: pass try: ...
KeyError
dataset/ETHPy150Open kdart/pycopia/QA/pycopia/QA/config.py/RootContainer.__getattribute__
2,664
def __delattr__(self, key): try: self.__dict__["_cache"].__delitem__(key) except __HOLE__: object.__delattr__(self, key)
KeyError
dataset/ETHPy150Open kdart/pycopia/QA/pycopia/QA/config.py/RootContainer.__delattr__
2,665
def __getitem__(self, key): try: return getattr(self._cache, key) except (AttributeError, __HOLE__, NameError): try: return self.get_userconfig().__getitem__(key) except KeyError: pass return super(RootContainer, self).__getitem...
KeyError
dataset/ETHPy150Open kdart/pycopia/QA/pycopia/QA/config.py/RootContainer.__getitem__
2,666
def __delitem__(self, key): try: del self._cache[key] except __HOLE__: super(RootContainer, self).__delitem__(key)
KeyError
dataset/ETHPy150Open kdart/pycopia/QA/pycopia/QA/config.py/RootContainer.__delitem__
2,667
def get(self, key, default=None): try: rv = self.__getitem__(key) except __HOLE__: rv = default return rv
KeyError
dataset/ETHPy150Open kdart/pycopia/QA/pycopia/QA/config.py/RootContainer.get
2,668
def _build_userconfig(self): try: #username = self.__getitem__("username") username = self._cache["username"] except __HOLE__: username = os.environ["USER"] try: cont = self.get_container(username) except config.NoResultFound: s...
KeyError
dataset/ETHPy150Open kdart/pycopia/QA/pycopia/QA/config.py/RootContainer._build_userconfig
2,669
def _get_DUT(self): try: return self._eqcache["DUT"] except __HOLE__: pass eq = EquipmentRuntime( self._environment.get_DUT(self._session), "DUT", self.logfile, self._session) self._eqcache["DUT"] = e...
KeyError
dataset/ETHPy150Open kdart/pycopia/QA/pycopia/QA/config.py/EnvironmentRuntime._get_DUT
2,670
def get_role(self, rolename): try: return self._eqcache[rolename] except __HOLE__: pass eq = self._environment.get_equipment_with_role(self._session, rolename) eq = EquipmentRuntime(eq, rolename, self.logfile, self._session) self._eqcache[rolename] = eq ...
KeyError
dataset/ETHPy150Open kdart/pycopia/QA/pycopia/QA/config.py/EnvironmentRuntime.get_role
2,671
def get_comments_from_parent(doc): try: _comments = frappe.db.get_value(doc.reference_doctype, doc.reference_name, "_comments") or "[]" except Exception, e: if e.args[0] in (1146, 1054): # 1146 = no table # 1054 = missing column _comments = "[]" else: raise try: return json.loads(_comments) e...
ValueError
dataset/ETHPy150Open frappe/frappe/frappe/core/doctype/communication/comment.py/get_comments_from_parent
2,672
def _get_name(self): """ Dynamically defines new partition name depending on the partition subtype. """ try: return getattr(self, '_get_{0}_name'.format(self.subtype))() except __HOLE__: import re expression = '_get_(\w+)_name' rais...
AttributeError
dataset/ETHPy150Open maxtepkeev/architect/architect/databases/mysql/partition.py/RangePartition._get_name
2,673
def _get_date_name(self): """ Defines name for a new partition for date partition subtype. """ patterns = { 'day': {'real': 'y%Yd%j', 'none': 'y0000d000'}, 'week': {'real': 'y%Yw%V', 'none': 'y0000w00'}, 'month': {'real': 'y%Ym%m', 'none': 'y0000m00'},...
KeyError
dataset/ETHPy150Open maxtepkeev/architect/architect/databases/mysql/partition.py/RangePartition._get_date_name
2,674
def _get_function(self): """ Returns correct partition function depending on the MySQL column type. """ functions = { 'date': 'TO_DAYS', 'datetime': 'TO_DAYS', 'timestamp': 'UNIX_TIMESTAMP', } column_type = self._get_column_type() ...
KeyError
dataset/ETHPy150Open maxtepkeev/architect/architect/databases/mysql/partition.py/RangePartition._get_function
2,675
def test_restart_workers(self): from gevent import sleep with start_wsgi_server(num_workers=4) as server: assert server.num_workers == 4 workers = server._workers assert len(workers) == server.num_workers worker = workers[2] os.kill(worker, si...
OSError
dataset/ETHPy150Open momyc/gevent-fastcgi/tests/server/test_server.py/ServerTests.test_restart_workers
2,676
def add_default_headers(self, headers): try: headers['Authorization'] = 'OAuth ' + self.token except __HOLE__: self.token = self._fetch_oauth_token() headers['Authorization'] = 'OAuth ' + self.token return headers
AttributeError
dataset/ETHPy150Open cloudkick/libcloud/libcloud/compute/drivers/brightbox.py/BrightboxConnection.add_default_headers
2,677
@stay_put def _compile(args): path = args.path os.chdir(path) if os.getcwd() not in sys.path: sys.path.insert(0, os.getcwd()) import settings SETTINGS = {k:v for k,v in vars(settings).items() \ if not k.startswith('__')} import handlers if os.path.isfile('ap...
IOError
dataset/ETHPy150Open ContinuumIO/ashiba/ashiba/main.py/_compile
2,678
def compile_check(args): path = args.path app_path = os.path.abspath(os.path.join(path, 'app')) mtimes = get_mtimes(path) mtime_fname = os.path.abspath(os.path.join(path, '.modified.json')) try: old_mtimes = json.load(open(mtime_fname)) except (IOError, __HOLE__): old_mtimes = {...
ValueError
dataset/ETHPy150Open ContinuumIO/ashiba/ashiba/main.py/compile_check
2,679
def browse(url, name='', icon=''): from PySide.QtGui import QApplication, QIcon from PySide.QtCore import QUrl from PySide.QtWebKit import QWebView for try_ in range(10): try: assert urllib2.urlopen(url).code == 200 except (__HOLE__, urllib2.URLError): time.sleep...
AssertionError
dataset/ETHPy150Open ContinuumIO/ashiba/ashiba/main.py/browse
2,680
def set_details(self, details=True): if not details: try: del self._data['details'] except __HOLE__: pass else: self._data['details'] = 1 return self
KeyError
dataset/ETHPy150Open smsapi/smsapi-python-client/smsapi/actions/sms.py/SendAction.set_details
2,681
def set_date_validate(self, date_validate=True): if not date_validate: try: del self._data['date_validate'] except __HOLE__: pass else: self._data['date_validate'] = 1 return self
KeyError
dataset/ETHPy150Open smsapi/smsapi-python-client/smsapi/actions/sms.py/SendAction.set_date_validate
2,682
def set_eco(self, eco=True): if not eco: try: del self._data['eco'] except __HOLE__: pass else: self._data['eco'] = 1 return self
KeyError
dataset/ETHPy150Open smsapi/smsapi-python-client/smsapi/actions/sms.py/SendAction.set_eco
2,683
def set_nounicode(self, nounicode=True): if not nounicode: try: del self._data['nounicode'] except __HOLE__: pass else: self._data['nounicode'] = 1 return self
KeyError
dataset/ETHPy150Open smsapi/smsapi-python-client/smsapi/actions/sms.py/SendAction.set_nounicode
2,684
def set_normalize(self, normalize=True): if not normalize: try: del self._data['normalize'] except __HOLE__: pass else: self._data['normalize'] = 1 return self
KeyError
dataset/ETHPy150Open smsapi/smsapi-python-client/smsapi/actions/sms.py/SendAction.set_normalize
2,685
def set_fast(self, fast=True): if not fast: try: del self._data['fast'] except __HOLE__: pass else: self._data['fast'] = 1 return self
KeyError
dataset/ETHPy150Open smsapi/smsapi-python-client/smsapi/actions/sms.py/SendAction.set_fast
2,686
def get_file_path(self, filepath, token): try: encoded_path, _, user = self.updown_auth_manager.get_resource_info(token) if not self._valid_path(filepath, encoded_path): logger.info("Invalid path file!! %s: %s" % (user, filepath)) raise NotFoundException("...
AttributeError
dataset/ETHPy150Open conan-io/conan/conans/server/service/service.py/FileUploadDownloadService.get_file_path
2,687
def put_file(self, file_saver, abs_filepath, token, upload_size): """ file_saver is an object with the save() method without parameters """ try: encoded_path, filesize, user = self.updown_auth_manager.get_resource_info(token) # Check size if upload_siz...
AttributeError
dataset/ETHPy150Open conan-io/conan/conans/server/service/service.py/FileUploadDownloadService.put_file
2,688
def start(self, track, setup, metrics_store): configured_host_list = self.cfg.opts("launcher", "external.target.hosts") hosts = [] try: for authority in configured_host_list: host, port = authority.split(":") hosts.append({"host": host, "port": port}) ...
ValueError
dataset/ETHPy150Open elastic/rally/esrally/mechanic/launcher.py/ExternalLauncher.start
2,689
def stop(self, cluster): logger.info("Shutting down ES cluster") # Ask all nodes to shutdown: stop_watch = self._clock.stop_watch() stop_watch.start() for node in cluster.nodes: process = node.process node.telemetry.detach_from_node(node) os....
OSError
dataset/ETHPy150Open elastic/rally/esrally/mechanic/launcher.py/InProcessLauncher.stop
2,690
def previous(self, cli): """ Return the previously focussed :class:`.Buffer` or `None`. """ if len(self.focus_stack) > 1: try: return self[self.focus_stack[-2]] except __HOLE__: pass
KeyError
dataset/ETHPy150Open jonathanslenders/python-prompt-toolkit/prompt_toolkit/buffer_mapping.py/BufferMapping.previous
2,691
def __setitem__(self, key, value): try: super(CaseInsensitiveDict, self).__setitem__(key.lower(), value) except __HOLE__: super(CaseInsensitiveDict, self).__setitem__(key, value)
AttributeError
dataset/ETHPy150Open missionpinball/mpf/mpf/system/config.py/CaseInsensitiveDict.__setitem__
2,692
def __getitem__(self, key): try: return super(CaseInsensitiveDict, self).__getitem__(key.lower()) except __HOLE__: return super(CaseInsensitiveDict, self).__getitem__(key)
AttributeError
dataset/ETHPy150Open missionpinball/mpf/mpf/system/config.py/CaseInsensitiveDict.__getitem__
2,693
def __contains__(self, key): try: return super(CaseInsensitiveDict, self).__contains__(key.lower()) except __HOLE__: return super(CaseInsensitiveDict, self).__contains__(key)
AttributeError
dataset/ETHPy150Open missionpinball/mpf/mpf/system/config.py/CaseInsensitiveDict.__contains__
2,694
def __delitem__(self, key): try: return super(CaseInsensitiveDict, self).__delitem__(key.lower()) except __HOLE__: return super(CaseInsensitiveDict, self).__delitem__(key)
AttributeError
dataset/ETHPy150Open missionpinball/mpf/mpf/system/config.py/CaseInsensitiveDict.__delitem__
2,695
@staticmethod def validate_config_item(spec, item='item not in config!@#'): try: if item.lower() == 'none': item = None except AttributeError: pass default = 'default required!@#' if '|' in spec: item_type, default = spec.split('...
TypeError
dataset/ETHPy150Open missionpinball/mpf/mpf/system/config.py/Config.validate_config_item
2,696
def validate_item(self, item, validator, validation_failure_info): try: if item.lower() == 'none': item = None except AttributeError: pass if ':' in validator: validator = validator.split(':') # item could be str, list, or list of...
TypeError
dataset/ETHPy150Open missionpinball/mpf/mpf/system/config.py/Config.validate_item
2,697
@need_db_opened def prepare(self, params=None): try: # mandatory if not passed by method self._cluster_name = params[0] # mandatory if not passed by method self.set_cluster_type( params[1] ) self._cluster_location = params[2] self._da...
ValueError
dataset/ETHPy150Open mogui/pyorient/pyorient/messages/cluster.py/DataClusterAddMessage.prepare
2,698
@need_db_opened def prepare(self, params=None): if isinstance( params, tuple ) or isinstance( params, list ): try: # mandatory if not passed by method # raise Exception if None if isinstance( params[0], tuple ) or isinstance( params[0], list ): ...
IndexError
dataset/ETHPy150Open mogui/pyorient/pyorient/messages/cluster.py/DataClusterCountMessage.prepare
2,699
def is_distributed_router(router): """Return True if router to be handled is distributed.""" try: # See if router is a DB object first requested_router_type = router.extra_attributes.distributed except __HOLE__: # if not, try to see if it is a request body requested_router_ty...
AttributeError
dataset/ETHPy150Open openstack/neutron/neutron/db/l3_dvr_db.py/is_distributed_router