Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
7,100
def handle(self, *args, **options): # bind host and port if len(args) > 0: host_port = args[0] else: host_port = None if host_port: host, _port = host_port.split(':', 1) port = int(_port) else: host = utils.get_settings_...
ValueError
dataset/ETHPy150Open tokibito/django-ftpserver/src/django_ftpserver/management/commands/ftpserver.py/Command.handle
7,101
def test_project_information(self): project = self.projects['base_test_project'] response = self.api_client.post( '/orchestra/api/project/project_information/', {'project_id': project.id}, format='json') self.assertEquals(response.status_code, 200) ret...
KeyError
dataset/ETHPy150Open unlimitedlabs/orchestra/orchestra/tests/test_project_api.py/ProjectAPITestCase.test_project_information
7,102
@classmethod def _factory(cls, lookup, synchronize_session, *arg): try: klass = lookup[synchronize_session] except __HOLE__: raise sa_exc.ArgumentError( "Valid strategies for session synchronization " "are %s" % (", ".join(sorted(repr(x) ...
KeyError
dataset/ETHPy150Open zzzeek/sqlalchemy/lib/sqlalchemy/orm/persistence.py/BulkUD._factory
7,103
def test_defaultFailure(self): """ Test that log.failure() emits the right data. """ log = TestLogger() try: raise RuntimeError("baloney!") except __HOLE__: log.failure("Whoops") errors = self.flushLoggedErrors(RuntimeError) self.a...
RuntimeError
dataset/ETHPy150Open twisted/twisted/twisted/logger/test/test_logger.py/LoggerTests.test_defaultFailure
7,104
def _fill_form(el, values): counts = {} if hasattr(values, 'mixed'): # For Paste request parameters values = values.mixed() inputs = _input_xpath(el) for input in inputs: name = input.get('name') if not name: continue if _takes_multiple(input): ...
IndexError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/lxml-3.3.6/src/lxml/html/formfill.py/_fill_form
7,105
def _find_form(el, form_id=None, form_index=None): if form_id is None and form_index is None: forms = _forms_xpath(el) for form in forms: return form raise FormNotFound( "No forms in page") if form_id is not None: form = el.get_element_by_id(form_id) ...
IndexError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/lxml-3.3.6/src/lxml/html/formfill.py/_find_form
7,106
def get_data_from_bits(self, **kwargs): result_dict = {} for bit_name, bit_instance in self.bits.items(): if bit_name in self.params: params = self.params[bit_name] else: try: params = bit_instance.params except ...
AttributeError
dataset/ETHPy150Open chibisov/drf-extensions/rest_framework_extensions/key_constructor/constructors.py/KeyConstructor.get_data_from_bits
7,107
def bfs_edges(G, source, reverse=False): """Produce edges in a breadth-first-search starting at source.""" # Based on http://www.ics.uci.edu/~eppstein/PADS/BFS.py # by D. Eppstein, July 2004. if reverse and isinstance(G, nx.DiGraph): neighbors = G.predecessors_iter else: neighbors = ...
StopIteration
dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/algorithms/traversal/breadth_first_search.py/bfs_edges
7,108
def catkin_success(args, env={}): orig_environ = dict(os.environ) try: os.environ.update(env) catkin_main(args) except __HOLE__ as exc: ret = exc.code if ret != 0: import traceback traceback.print_exc() finally: os.environ = orig_environ ...
SystemExit
dataset/ETHPy150Open catkin/catkin_tools/tests/utils.py/catkin_success
7,109
def catkin_failure(args, env={}): orig_environ = dict(os.environ) try: os.environ.update(env) catkin_main(args) except __HOLE__ as exc: ret = exc.code finally: os.environ = orig_environ return ret != 0
SystemExit
dataset/ETHPy150Open catkin/catkin_tools/tests/utils.py/catkin_failure
7,110
def __exit__(self, exc_type, exc_value, tb): if self.expected is None: if exc_type is None: return True else: raise if exc_type is None: try: exc_name = self.expected.__name__ except __HOLE__: ...
AttributeError
dataset/ETHPy150Open catkin/catkin_tools/tests/utils.py/AssertRaisesContext.__exit__
7,111
def __init__(self, servers, debug=0, pickleProtocol=0, pickler=pickle.Pickler, unpickler=pickle.Unpickler, pload=None, pid=None, server_max_key_length=SERVER_MAX_KEY_LENGTH, server_max_value_length=SERVER_MAX_VALUE_LENGTH, dead_retry=_...
TypeError
dataset/ETHPy150Open mozilla/source/vendor-local/lib/python/memcache.py/Client.__init__
7,112
def handle(self, **options): self.verbosity = options['verbosity'] self.interactive = options['interactive'] app_label = options['app_label'] start_migration_name = options['start_migration_name'] migration_name = options['migration_name'] no_optimize = options['no_optim...
ValueError
dataset/ETHPy150Open django/django/django/core/management/commands/squashmigrations.py/Command.handle
7,113
def find_migration(self, loader, app_label, name): try: return loader.get_migration_by_prefix(app_label, name) except AmbiguityError: raise CommandError( "More than one migration matches '%s' in app '%s'. Please be " "more specific." % (name, app_l...
KeyError
dataset/ETHPy150Open django/django/django/core/management/commands/squashmigrations.py/Command.find_migration
7,114
def clean(self, value): """ Value can be either a string in the format XXX.XXX.XXX-XX or an 11-digit number. """ value = super(BRCPFField, self).clean(value) if value in EMPTY_VALUES: return u'' orig_value = value[:] if not value.isdigit(): ...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/contrib/localflavor/br/forms.py/BRCPFField.clean
7,115
def clean(self, value): """ Value can be either a string in the format XX.XXX.XXX/XXXX-XX or a group of 14 characters. """ value = super(BRCNPJField, self).clean(value) if value in EMPTY_VALUES: return u'' orig_value = value[:] if not value.isd...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/contrib/localflavor/br/forms.py/BRCNPJField.clean
7,116
def close(self): """Closes the WebSocket connection.""" self._started = False if not self.server_terminated: if not self.stream.closed(): self._write_frame(True, 0x8, b'') self.server_terminated = True if self.graceful_shutdown: if se...
KeyError
dataset/ETHPy150Open benoitc/gaffer/gaffer/httpclient/websocket.py/WebSocket.close
7,117
def _handle_message(self, opcode, data): if self.client_terminated: return if opcode == 0x1: # UTF-8 data try: decoded = data.decode("utf-8") except __HOLE__: self._abort() return self._async_cal...
UnicodeDecodeError
dataset/ETHPy150Open benoitc/gaffer/gaffer/httpclient/websocket.py/WebSocket._handle_message
7,118
def __init__(self, loop, url, api_key=None, **kwargs): loop = loop try: self.heartbeat_timeout = kwargs.pop('heartbeat') except __HOLE__: self.heartbeat_timeout = 15.0 self.api_key = api_key # define status self.active = False self.close...
KeyError
dataset/ETHPy150Open benoitc/gaffer/gaffer/httpclient/websocket.py/GafferSocket.__init__
7,119
def __getitem__(self, topic): try: channel = self.channels[topic] except __HOLE__: raise KeyError("%s channel isn't subscribed" % topic) return channel
KeyError
dataset/ETHPy150Open benoitc/gaffer/gaffer/httpclient/websocket.py/GafferSocket.__getitem__
7,120
def __init__(self, loop, url, mode=3, api_key=None, **kwargs): loop = loop self.api_key = api_key # initialize the capabilities self.mode = mode self.readable = False self.writable = False if mode & pyuv.UV_READABLE: self.readable = True if m...
KeyError
dataset/ETHPy150Open benoitc/gaffer/gaffer/httpclient/websocket.py/IOChannel.__init__
7,121
def on_message(self, raw): msg = decode_frame(raw) if msg.type in (FRAME_ERROR_TYPE, FRAME_RESPONSE_TYPE): # did we received an error? error = None result = None if msg.type == FRAME_ERROR_TYPE: error = json.loads(msg.body.decode('utf-8')) ...
KeyError
dataset/ETHPy150Open benoitc/gaffer/gaffer/httpclient/websocket.py/IOChannel.on_message
7,122
@sockets.route('/api/cluster_comms') def cluster_comms(ws): """Websocket to communicate with the test clusters Commands are logical actions one end of the socket wishes the other end to take. Responses are follow ups to a command, which there can be multiple, back and forth between client and server ...
OSError
dataset/ETHPy150Open datastax/cstar_perf/frontend/cstar_perf/frontend/server/cluster_api.py/cluster_comms
7,123
def get_magic_type(self): """Checks the volume for its magic bytes and returns the magic.""" with io.open(self.disk.get_fs_path(), "rb") as file: file.seek(self.offset) fheader = file.read(min(self.size, 4096) if self.size else 4096) # TODO fallback to img-cat image -s ...
ImportError
dataset/ETHPy150Open ralphje/imagemounter/imagemounter/volume.py/Volume.get_magic_type
7,124
def mount(self): """Based on the file system type as determined by :func:`determine_fs_type`, the proper mount command is executed for this volume. The volume is mounted in a temporary path (or a pretty path if :attr:`pretty` is enabled) in the mountpoint as specified by :attr:`mountpoint`. ...
TypeError
dataset/ETHPy150Open ralphje/imagemounter/imagemounter/volume.py/Volume.mount
7,125
def _open_bde_container(self): """Mounts a BDE container. Uses key material provided by the :attr:`keys` attribute. The key material should be provided in the same format as to :cmd:`bdemount`, used as follows: k:full volume encryption and tweak key p:passphrase r:recovery passw...
ValueError
dataset/ETHPy150Open ralphje/imagemounter/imagemounter/volume.py/Volume._open_bde_container
7,126
def unmount(self): """Unounts the volume from the filesystem.""" for volume in self.volumes: volume.unmount() if self.loopback and self.volume_group: try: _util.check_call_(["lvm", 'vgchange', '-a', 'n', self.volume_group], stdout=subprocess.PIPE) ...
OSError
dataset/ETHPy150Open ralphje/imagemounter/imagemounter/volume.py/Volume.unmount
7,127
@property def name(self): try: return "-" + self._name() except __HOLE__: return ''
NotImplementedError
dataset/ETHPy150Open niwinz/django-greenqueue/greenqueue/worker/base.py/BaseWorker.name
7,128
def _process_task(self, name, uuid, args, kwargs): try: _task = self.lib.task_by_name(name) except __HOLE__: log.error("greenqueue-worker: received unknown or unregistret method call: %s", name) return task_callable = self.get_callable_for_task(_task) ...
ValueError
dataset/ETHPy150Open niwinz/django-greenqueue/greenqueue/worker/base.py/BaseWorker._process_task
7,129
def run(self): load_modules() self.lib = library while not self.stop_event.is_set(): try: name, uuid, args, kwargs = self.queue_in.get(True) log.debug("greenqueue-worker{0}: received message from queue - {1}:{2}".format(self.name, name, uuid)) ...
KeyboardInterrupt
dataset/ETHPy150Open niwinz/django-greenqueue/greenqueue/worker/base.py/BaseWorker.run
7,130
def _handleClassSetUp(self, test, result): previousClass = getattr(result, '_previousTestClass', None) currentClass = test.__class__ if currentClass == previousClass: return if result._moduleSetUpFailed: return if getattr(currentClass, "__unittest_skip__",...
TypeError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/suite.py/TestSuite._handleClassSetUp
7,131
def _handleModuleFixture(self, test, result): previousModule = self._get_previous_module(result) currentModule = test.__class__.__module__ if currentModule == previousModule: return self._handleModuleTearDown(result) result._moduleSetUpFailed = False try: ...
KeyError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/suite.py/TestSuite._handleModuleFixture
7,132
def _handleModuleTearDown(self, result): previousModule = self._get_previous_module(result) if previousModule is None: return if result._moduleSetUpFailed: return try: module = sys.modules[previousModule] except __HOLE__: return ...
KeyError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/suite.py/TestSuite._handleModuleTearDown
7,133
def _isnotsuite(test): "A crude way to tell apart testcases and suites with duck-typing" try: iter(test) except __HOLE__: return True return False
TypeError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/suite.py/_isnotsuite
7,134
def has(self, node): """ Check if node has heartbeat monitor @param node: Node @type node: L{Node} @return: True or False """ try: m = self._lookup(node) return True except __HOLE__, e: return False
KeyError
dataset/ETHPy150Open selfsk/nodeset.core/src/nodeset/core/heartbeat.py/NodeHeartBeat.has
7,135
def _skip_if_no_lxml(): try: import lxml except __HOLE__: raise nose.SkipTest("no lxml")
ImportError
dataset/ETHPy150Open pydata/pandas/pandas/io/tests/test_data.py/_skip_if_no_lxml
7,136
def _skip_if_no_bs(): try: import bs4 import html5lib except __HOLE__: raise nose.SkipTest("no html5lib/bs4")
ImportError
dataset/ETHPy150Open pydata/pandas/pandas/io/tests/test_data.py/_skip_if_no_bs
7,137
def is_fd_closed(fd): try: os.fstat(fd) return False except __HOLE__: return True
OSError
dataset/ETHPy150Open d11wtq/dockerpty/tests/unit/test_io.py/is_fd_closed
7,138
def upgrade(self, version, name='database_version', pkg=None): """Invokes `do_upgrade(env, version, cursor)` in module `"%s/db%i.py" % (pkg, version)`, for each required version upgrade. :param version: the expected integer database version. :param name: the name of the entry in the SYS...
AttributeError
dataset/ETHPy150Open edgewall/trac/trac/db/api.py/DatabaseManager.upgrade
7,139
def parse_connection_uri(db_str): """Parse the database connection string. The database connection string for an environment is specified through the `database` option in the `[trac]` section of trac.ini. :return: a tuple containing the scheme and a dictionary of attributes: `user`, `pass...
ValueError
dataset/ETHPy150Open edgewall/trac/trac/db/api.py/parse_connection_uri
7,140
def __new__(cls, x=0, base=10): """ From the Py3 int docstring: | int(x=0) -> integer | int(x, base=10) -> integer | | Convert a number or string to an integer, or return 0 if no | arguments are given. If x is a number, return x.__int__(). For | fl...
TypeError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/types/newint.py/newint.__new__
7,141
def emit_rmic_classes(target, source, env): """Create and return lists of Java RMI stub and skeleton class files to be created from a set of class files. """ class_suffix = env.get('JAVACLASSSUFFIX', '.class') classdir = env.get('JAVACLASSDIR') if not classdir: try: s = sour...
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Tool/rmic.py/emit_rmic_classes
7,142
def _start_batch(self): fn = self.options.batch if not fn: return None if fn == '-': f = sys.stdin else: f = open(fn, 'rb') def wrapper(): for l in f.readlines(): l = l.strip() if not l: ...
ValueError
dataset/ETHPy150Open lavr/python-emails/scripts/make_rfc822.py/MakeRFC822._start_batch
7,143
def _setup_environment(environ): import platform # Cygwin requires some special voodoo to set the environment variables # properly so that Oracle will see them. if platform.system().upper().startswith('CYGWIN'): try: import ctypes except __HOLE__ as e: from django...
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/db/backends/oracle/base.py/_setup_environment
7,144
def _cursor(self): cursor = None if not self._valid_connection(): conn_string = convert_unicode(self._connect_string()) conn_params = self.settings_dict['OPTIONS'].copy() if 'use_returning_into' in conn_params: del conn_params['use_returning_into'] ...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/db/backends/oracle/base.py/DatabaseWrapper._cursor
7,145
def executemany(self, query, params=None): # cx_Oracle doesn't support iterators, convert them to lists if params is not None and not isinstance(params, (list, tuple)): params = list(params) try: args = [(':arg%d' % i) for i in range(len(params[0]))] except (__HOL...
IndexError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/db/backends/oracle/base.py/FormatStylePlaceholderCursor.executemany
7,146
def main(): parser = argparse.ArgumentParser() parser.add_argument('dataName', type=str, help='name of python script that produces data to analyze.') parser.add_argument('allocModelName', type=str, help='name of allocation model. {MixModel, DPMixModel}') parser.add_argument('obsModelName', typ...
TypeError
dataset/ETHPy150Open daeilkim/refinery/refinery/bnpy/bnpy-dev/bnpy/viz/PrintTopics.py/main
7,147
def get_language(language_code): for tag in normalize_language_tag(language_code): if tag in _languages: return _languages[tag] try: module = __import__(tag, globals(), locals()) except __HOLE__: continue _languages[tag] = module return mod...
ImportError
dataset/ETHPy150Open adieu/allbuttonspressed/docutils/parsers/rst/languages/__init__.py/get_language
7,148
def obj_make_compatible(self, primitive, target_version): super(ComputeNode, self).obj_make_compatible(primitive, target_version) target_version = versionutils.convert_version_to_tuple(target_version) if target_version < (1, 16): if 'disk_allocation_ratio' in primitive: ...
KeyError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/objects/compute_node.py/ComputeNode.obj_make_compatible
7,149
@staticmethod def _host_from_db_object(compute, db_compute): if (('host' not in db_compute or db_compute['host'] is None) and 'service_id' in db_compute and db_compute['service_id'] is not None): # FIXME(sbauza) : Unconverted compute record, provide compatibility ...
AttributeError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/objects/compute_node.py/ComputeNode._host_from_db_object
7,150
def default (self, obj): try: return obj.__json__() except __HOLE__, e: return json.JSONEncoder.default(self, obj)
AttributeError
dataset/ETHPy150Open fp7-ofelia/ocf/ofam/src/src/foam/core/json.py/APIEncoder.default
7,151
def import_from_string(path): i = path.rfind('.') module, attr = path[:i], path[i + 1:] try: mod = import_module(module) except __HOLE__, e: raise ImproperlyConfigured( 'Error importing module %s: "%s"' % (module, e) ) try: instance = getattr(mod, attr) ...
ImportError
dataset/ETHPy150Open lincolnloop/django-debug-logging/debug_logging/utils.py/import_from_string
7,152
def parse_and_bind(self, string): '''Parse and execute single line of a readline init file.''' try: log('parse_and_bind("%s")' % string) if string.startswith('#'): return if string.startswith('set'): m = re.compile(r'set\s+([-a-zA-Z0-9]...
AttributeError
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/pyreadline/rlmain.py/Readline.parse_and_bind
7,153
@classmethod def _compile_patterns(cls, patterns, field_name="Unknown", spec="Unknown"): compiled_patterns = [] for p in patterns: try: compiled_patterns.append(re.compile(fnmatch_translate_extended(p))) except (__HOLE__, re.error) as e: raise cls.InvalidPatternError( 'In...
TypeError
dataset/ETHPy150Open pantsbuild/pants/src/python/pants/backend/jvm/tasks/unpack_jars.py/UnpackJars._compile_patterns
7,154
def len(obj): try: return _len(obj) except __HOLE__: try: # note: this is an internal undocumented API, # don't rely on it in your own programs return obj.__length_hint__() except AttributeError: raise TypeError
TypeError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_iterlen.py/len
7,155
def tag_model(cls, admin_cls=None, field_name='tags', sort_tags=False, select_field=False, auto_add_admin_field=True, admin_list_display=True): """ tag_model accepts a number of named parameters: admin_cls If set to a subclass of ModelAdmin, will insert the tag ...
ImportError
dataset/ETHPy150Open feincms/feincms/feincms/contrib/tagging.py/tag_model
7,156
def _open(self): # load descriptive fields while 1: offset = self.fp.tell() tag, size = self.field() if not tag or tag == (8,10): break if size: tagdata = self.fp.read(size) else: tagdata = None ...
KeyError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/site-packages/PIL/IptcImagePlugin.py/IptcImageFile._open
7,157
def getiptcinfo(im): import TiffImagePlugin, JpegImagePlugin import StringIO data = None if isinstance(im, IptcImageFile): # return info dictionary right away return im.info elif isinstance(im, JpegImagePlugin.JpegImageFile): # extract the IPTC/NAA resource try: ...
AttributeError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/site-packages/PIL/IptcImagePlugin.py/getiptcinfo
7,158
def validate_input(self, validation_definition): """In this example we are using external validation to verify that the Github repository exists. If validate_input does not raise an Exception, the input is assumed to be valid. Otherwise it prints the exception as an error message when te...
ValueError
dataset/ETHPy150Open splunk/splunk-sdk-python/examples/github_forks/github_forks.py/MyScript.validate_input
7,159
def generator_queue(generator, max_q_size=10, wait_time=0.05, nb_worker=1): '''Builds a threading queue out of a data generator. Used in `fit_generator`, `evaluate_generator`, `predict_generator`. ''' q = queue.Queue() _stop = threading.Event() def data_generator_task(): ...
ValueError
dataset/ETHPy150Open fchollet/keras/keras/engine/training.py/generator_queue
7,160
def _fit_loop(self, f, ins, out_labels=[], batch_size=32, nb_epoch=100, verbose=1, callbacks=[], val_f=None, val_ins=None, shuffle=True, callback_metrics=[]): '''Abstract fit function for f(ins). Assume that f returns a list, labeled by out_labels. ...
TypeError
dataset/ETHPy150Open fchollet/keras/keras/engine/training.py/Model._fit_loop
7,161
def fetchone(self): """ Fetch the next row of a query result set, returning a single sequence, or None when no more data is available. Alias for ``next()``. """ try: return self.next() except __HOLE__: return None
StopIteration
dataset/ETHPy150Open crate/crate-python/src/crate/client/cursor.py/Cursor.fetchone
7,162
def fetchmany(self, count=None): """ Fetch the next set of rows of a query result, returning a sequence of sequences (e.g. a list of tuples). An empty sequence is returned when no more rows are available. """ if count is None: count = self.arraysize if...
StopIteration
dataset/ETHPy150Open crate/crate-python/src/crate/client/cursor.py/Cursor.fetchmany
7,163
def fetchall(self): """ Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples). Note that the cursor's arraysize attribute can affect the performance of this operation. """ result = [] iterate = True ...
StopIteration
dataset/ETHPy150Open crate/crate-python/src/crate/client/cursor.py/Cursor.fetchall
7,164
def __init__(self, *args, **kwds): """ A dictionary which maintains the insertion order of keys. """ if len(args) > 1: raise TypeError('expected at most 1 arguments, got %d' % len(args)) try: self.__end except __HOLE__: self.clear() self.updat...
AttributeError
dataset/ETHPy150Open pycassa/pycassa/pycassa/util.py/OrderedDict.__init__
7,165
def run(self, dataset_slug, upload_id, external_id_field_index=None, *args, **kwargs): """ Execute import. """ from panda.models import Dataset, DataUpload log = logging.getLogger(self.name) log.info('Beginning import, dataset_slug: %s' % dataset_slug) t...
UnicodeDecodeError
dataset/ETHPy150Open pandaproject/panda/panda/tasks/import_csv.py/ImportCSVTask.run
7,166
def __init__(self, user, *args, **kwargs): "Sets choices and initial value" super(SettingsForm, self).__init__(*args, **kwargs) self.fields['default_perspective'].label = _("Default Perspective") self.fields['language'].label = _("Language") self.fields['default_timezone'].label...
IndexError
dataset/ETHPy150Open treeio/treeio/treeio/account/forms.py/SettingsForm.__init__
7,167
def parse_categories(self, headers): kind = action = None mixins = collections.Counter() schemes = collections.defaultdict(list) try: categories = headers["Category"] except KeyError: raise exception.OCCIInvalidSchema("No categories") for ctg in _q...
ValueError
dataset/ETHPy150Open openstack/ooi/ooi/wsgi/parsers.py/TextParser.parse_categories
7,168
def parse_attributes(self, headers): attrs = {} try: header_attrs = headers["X-OCCI-Attribute"] for attr in _quoted_split(header_attrs): l = _split_unquote(attr) attrs[l[0].strip()] = l[1] except __HOLE__: pass return at...
KeyError
dataset/ETHPy150Open openstack/ooi/ooi/wsgi/parsers.py/TextParser.parse_attributes
7,169
def parse_links(self, headers): links = {} try: header_links = headers["Link"] except KeyError: return links for link in _quoted_split(header_links): ll = _quoted_split(link, "; ") # remove the "<" and ">" if ll[0][1] != "<" and...
ValueError
dataset/ETHPy150Open openstack/ooi/ooi/wsgi/parsers.py/TextParser.parse_links
7,170
def __call__(self, request, *args, **kwargs): stage = { '1': 'preview', '2': 'post', }.get(request.POST.get(self.unused_name('stage')), 'preview') self.parse_params(request, *args, **kwargs) try: method = getattr(self, stage + '_' + request.method.lowe...
AttributeError
dataset/ETHPy150Open django/django-formtools/formtools/preview.py/FormPreview.__call__
7,171
def unused_name(self, name): """ Given a first-choice name, adds an underscore to the name until it reaches a name that isn't claimed by any field in the form. This is calculated rather than being hard-coded so that no field names are off-limits for use in the form. """ ...
KeyError
dataset/ETHPy150Open django/django-formtools/formtools/preview.py/FormPreview.unused_name
7,172
def datetime(self): """ Returns a datetime object at the end of the selected (or current) date. This is needed to properly filter transactions that occur during the day we are filtering for """ # note: empty string is parsed as today's date date = self.con...
ValueError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/reports/commtrack/data_sources.py/SimplifiedInventoryDataSource.datetime
7,173
def get(self, key, failobj=None): """Get dictionary item, defaulting to another value if it does not exist. Args: key: Key of item to get. Key is case insensitive, so "d['Key']" is the same as "d['key']". failobj: Value to return if key not in dictionary. """ try: cased_key =...
KeyError
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/api/urlfetch.py/_CaselessDict.get
7,174
def update(self, dict=None, **kwargs): """Update dictionary using values from another dictionary and keywords. Args: dict: Dictionary to update from. kwargs: Keyword arguments to update from. """ if dict: try: keys = dict.keys() except __HOLE__: for k, v in dict...
AttributeError
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/api/urlfetch.py/_CaselessDict.update
7,175
def _indicator_diff(self, calc_name, emitter_names, other_doc): indicators = [] for emitter_name in emitter_names: class NormalizedEmittedValue(object): """Normalize the values to the dictionary form to allow comparison""" def __init__(self, value): ...
KeyError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/ex-submodules/fluff/indicators.py/IndicatorDocument._indicator_diff
7,176
def save_to_sql(self, diff, engine): if not diff: # empty indicator document return default_key = (self.id,) + tuple(diff['group_values']) rows = {} def set_row_val(rowkey, col_name, col_value): row = rows.setdefault(rowkey, {}) row[col_n...
AttributeError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/ex-submodules/fluff/indicators.py/IndicatorDocument.save_to_sql
7,177
def __contains__(self, key): try: o = self.data[key]() except __HOLE__: return False return o is not None
KeyError
dataset/ETHPy150Open Southpaw-TACTIC/TACTIC/src/context/client/tactic-api-python-4.0.api04/Lib/weakref.py/WeakValueDictionary.__contains__
7,178
def has_key(self, key): try: o = self.data[key]() except __HOLE__: return False return o is not None
KeyError
dataset/ETHPy150Open Southpaw-TACTIC/TACTIC/src/context/client/tactic-api-python-4.0.api04/Lib/weakref.py/WeakValueDictionary.has_key
7,179
def get(self, key, default=None): try: wr = self.data[key] except __HOLE__: return default else: o = wr() if o is None: # This should only happen return default else: return o
KeyError
dataset/ETHPy150Open Southpaw-TACTIC/TACTIC/src/context/client/tactic-api-python-4.0.api04/Lib/weakref.py/WeakValueDictionary.get
7,180
def pop(self, key, *args): try: o = self.data.pop(key)() except __HOLE__: if args: return args[0] raise if o is None: raise KeyError, key else: return o
KeyError
dataset/ETHPy150Open Southpaw-TACTIC/TACTIC/src/context/client/tactic-api-python-4.0.api04/Lib/weakref.py/WeakValueDictionary.pop
7,181
def setdefault(self, key, default=None): try: wr = self.data[key] except __HOLE__: self.data[key] = KeyedRef(default, self._remove, key) return default else: return wr()
KeyError
dataset/ETHPy150Open Southpaw-TACTIC/TACTIC/src/context/client/tactic-api-python-4.0.api04/Lib/weakref.py/WeakValueDictionary.setdefault
7,182
def has_key(self, key): try: wr = ref(key) except __HOLE__: return 0 return wr in self.data
TypeError
dataset/ETHPy150Open Southpaw-TACTIC/TACTIC/src/context/client/tactic-api-python-4.0.api04/Lib/weakref.py/WeakKeyDictionary.has_key
7,183
def __contains__(self, key): try: wr = ref(key) except __HOLE__: return 0 return wr in self.data
TypeError
dataset/ETHPy150Open Southpaw-TACTIC/TACTIC/src/context/client/tactic-api-python-4.0.api04/Lib/weakref.py/WeakKeyDictionary.__contains__
7,184
def _get_memory(pid, timestamps=False, include_children=False): # .. only for current process and only on unix.. if pid == -1: pid = os.getpid() # .. cross-platform but but requires psutil .. if has_psutil: process = psutil.Process(pid) try: # avoid useing get_memor...
AttributeError
dataset/ETHPy150Open fabianp/memory_profiler/memory_profiler.py/_get_memory
7,185
def add_function(self, func): """ Record line profiling information for the given Python function. """ try: # func_code does not exist in Python3 code = func.__code__ except __HOLE__: warnings.warn("Could not extract a code object for the object %r" ...
AttributeError
dataset/ETHPy150Open fabianp/memory_profiler/memory_profiler.py/LineProfiler.add_function
7,186
@line_cell_magic def mprun(self, parameter_s='', cell=None): """ Execute a statement under the line-by-line memory profiler from the memory_profiler module. Usage, in line mode: %mprun -f func1 -f func2 <statement> Usage, in cell mode: %%mprun -f func1 -f func2 ...
SystemExit
dataset/ETHPy150Open fabianp/memory_profiler/memory_profiler.py/MemoryProfilerMagics.mprun
7,187
@classmethod def register_magics(cls, ip): from distutils.version import LooseVersion import IPython ipython_version = LooseVersion(IPython.__version__) if ipython_version < '0.13': try: _register_magic = ip.define_magic except __HOLE__: # ip...
AttributeError
dataset/ETHPy150Open fabianp/memory_profiler/memory_profiler.py/MemoryProfilerMagics.register_magics
7,188
def get_version(self, filename=None, version=-1, **kwargs): """Get a file from GridFS by ``"filename"`` or metadata fields. Returns a version of the file in GridFS whose filename matches `filename` and whose metadata fields match the supplied keyword arguments, as an instance of :class:...
StopIteration
dataset/ETHPy150Open mongodb/mongo-python-driver/gridfs/__init__.py/GridFS.get_version
7,189
def open_download_stream_by_name(self, filename, revision=-1): """Opens a Stream from which the application can read the contents of `filename` and optional `revision`. For example:: my_db = MongoClient().test fs = GridFSBucket(my_db) grid_out = fs.open_download_s...
StopIteration
dataset/ETHPy150Open mongodb/mongo-python-driver/gridfs/__init__.py/GridFSBucket.open_download_stream_by_name
7,190
def init(**kwargs): # VCR needs access ot the parent shell for playback global shell try: shell = kwargs['shell'] except __HOLE__: raise RuntimeError('VCR: Unable to initialize', 'RadSSH shell not accessible')
KeyError
dataset/ETHPy150Open radssh/radssh/radssh/core_plugins/vcr.py/init
7,191
def frontendediting_request_processor(page, request): """ Sets the frontend editing state in the cookie depending on the ``frontend_editing`` GET parameter and the user's permissions. """ if 'frontend_editing' not in request.GET: return response = HttpResponseRedirect(request.path) ...
ValueError
dataset/ETHPy150Open django-leonardo/django-leonardo/leonardo/module/web/processors/edit.py/frontendediting_request_processor
7,192
def setUp(self): self.check_for_psutils() try: from pikos.cymonitors.line_memory_monitor import ( LineMemoryMonitor) except __HOLE__: self.skipTest('Cython LineMemoryMonitor is not available') from pikos.cymonitors.line_memory_monitor import LineMe...
ImportError
dataset/ETHPy150Open enthought/pikos/pikos/tests/test_cline_memory_monitor.py/TestLineMemoryMonitor.setUp
7,193
def test_issue2(self): """ Test for issue #2. """ monitor = self.monitor FOO = """ def foo(): a = [] for i in range(20): a.append(i+sum(a)) foo() """ @monitor.attach def boo(): code = compile(FOO, 'foo', 'exec') exec code in glo...
TypeError
dataset/ETHPy150Open enthought/pikos/pikos/tests/test_cline_memory_monitor.py/TestLineMemoryMonitor.test_issue2
7,194
def check_for_psutils(self): try: import psutil # noqa except __HOLE__: self.skipTest('Could not import psutils, skipping test.')
ImportError
dataset/ETHPy150Open enthought/pikos/pikos/tests/test_cline_memory_monitor.py/TestLineMemoryMonitor.check_for_psutils
7,195
def try_save(self, *args, **kw): """Try to save the specified Model instance `obj`. Return `True` on success, `False` if this instance wasn't saved and should be deferred. """ obj = self.object try: """ """ m = getattr(obj, 'before_dump...
ValidationError
dataset/ETHPy150Open lsaffre/lino/lino/utils/dpy.py/FakeDeserializedObject.try_save
7,196
@classmethod def _config_parser(cls, repo, parent_commit, read_only): """:return: Config Parser constrained to our submodule in read or write mode :raise IOError: If the .gitmodules file cannot be found, either locally or in the repository at the given parent commit. Otherwise the except...
ValueError
dataset/ETHPy150Open gitpython-developers/GitPython/git/objects/submodule/base.py/Submodule._config_parser
7,197
def _clear_cache(self): # clear the possibly changed values for name in self._cache_attrs: try: delattr(self, name) except __HOLE__: pass # END try attr deletion # END for each name to delete
AttributeError
dataset/ETHPy150Open gitpython-developers/GitPython/git/objects/submodule/base.py/Submodule._clear_cache
7,198
def _config_parser_constrained(self, read_only): """:return: Config Parser constrained to our submodule in read or write mode""" try: pc = self.parent_commit except __HOLE__: pc = None # end hande empty parent repository parser = self._config_parser(self.r...
ValueError
dataset/ETHPy150Open gitpython-developers/GitPython/git/objects/submodule/base.py/Submodule._config_parser_constrained
7,199
@classmethod def add(cls, repo, name, path, url=None, branch=None, no_checkout=False): """Add a new submodule to the given repository. This will alter the index as well as the .gitmodules file, but will not create a new commit. If the submodule already exists, no matter if the configuration ...
KeyError
dataset/ETHPy150Open gitpython-developers/GitPython/git/objects/submodule/base.py/Submodule.add