Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
1,400
def on_source_need_data(self, source, length): # Attempt to read data from the stream try: data = self.fd.read(length) except __HOLE__ as err: self.exit("Failed to read data from stream: {0}".format(err)) # If data is empty it's the end of stream if not d...
IOError
dataset/ETHPy150Open chrippa/livestreamer/examples/gst-player.py/LivestreamerPlayer.on_source_need_data
1,401
def test_dtype_errors(): # Try to call theano_expr with a bad label dtype. raised = False fmt = OneHotFormatter(max_labels=50) try: fmt.theano_expr(theano.tensor.vector(dtype=theano.config.floatX)) except __HOLE__: raised = True assert raised # Try to call format with a bad ...
TypeError
dataset/ETHPy150Open lisa-lab/pylearn2/pylearn2/format/tests/test_target_format.py/test_dtype_errors
1,402
def test_bad_arguments(): # Make sure an invalid max_labels raises an error. raised = False try: fmt = OneHotFormatter(max_labels=-10) except ValueError: raised = True assert raised raised = False try: fmt = OneHotFormatter(max_labels='10') except ValueError: ...
ValueError
dataset/ETHPy150Open lisa-lab/pylearn2/pylearn2/format/tests/test_target_format.py/test_bad_arguments
1,403
def upkeep(): """Does upkeep (like flushing, garbage collection, etc.)""" # Just in case, let's clear the exception info. try: sys.exc_clear() except __HOLE__: # Python 3 does not have sys.exc_clear. The except statement clears # the info itself (and we've just entered an except ...
AttributeError
dataset/ETHPy150Open ProgVal/Limnoria/src/world.py/upkeep
1,404
def initialize(self, import_func=__import__): """Attempt to import the config module, if not already imported. This function always sets self._module to a value unequal to None: either the imported module (if imported successfully), or a dummy object() instance (if an ImportError was raised). Other ...
ImportError
dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/api/lib_config.py/LibConfigRegistry.initialize
1,405
def _clear_cache(self): """Clear the cached values.""" for key in self._defaults: try: delattr(self, key) except __HOLE__: pass
AttributeError
dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/api/lib_config.py/ConfigHandle._clear_cache
1,406
def process_queue(q, quiet=False): if not quiet: print("Processing: %s" % q) if q.socks_proxy_type and q.socks_proxy_host and q.socks_proxy_port: try: import socks except __HOLE__: raise ImportError("Queue has been configured with proxy settings, but no socks lib...
ImportError
dataset/ETHPy150Open rossp/django-helpdesk/helpdesk/management/commands/get_email.py/process_queue
1,407
def _test_gen_skeleton(command_name, operation_name): p = aws('%s %s --generate-cli-skeleton' % (command_name, operation_name)) assert_equal(p.rc, 0, 'Received non zero RC (%s) for command: %s %s' % (p.rc, command_name, operation_name)) try: parsed = json.loads(p.stdout) except ...
ValueError
dataset/ETHPy150Open aws/aws-cli/tests/integration/customizations/test_generatecliskeleton.py/_test_gen_skeleton
1,408
def pop(self, k, *args): result = super(OrderedDict, self).pop(k, *args) try: self.keyOrder.remove(k) except __HOLE__: # Key wasn't in the dictionary in the first place. No problem. pass return result
ValueError
dataset/ETHPy150Open dragondjf/QMarkdowner/markdown/odict.py/OrderedDict.pop
1,409
def index(self, key): """ Return the index of a given key. """ try: return self.keyOrder.index(key) except __HOLE__: raise ValueError("Element '%s' was not found in OrderedDict" % key)
ValueError
dataset/ETHPy150Open dragondjf/QMarkdowner/markdown/odict.py/OrderedDict.index
1,410
def enable_plugin(self, pname): try: self.logger.debug("enabling plugin '%s'" % (pname)) try: self.pluginmods[pname] = __import__(pname) except Exception, e: self.logger.error("exception importing '%s' plugin:\n%s" % (pname, shared.indent(trace...
AttributeError
dataset/ETHPy150Open zynga/hiccup/hiccup/PluginManager.py/PluginManager.enable_plugin
1,411
def disable_plugin(self, pname): self.logger.info("disabling plugin '%s'" % (pname)) if (pname in sys.modules): del(sys.modules[pname]) if (pname in self.pluginmods): del(self.pluginmods[pname]) if (pname in self.pluginobjs): del(self.pluginobjs[pname]...
OSError
dataset/ETHPy150Open zynga/hiccup/hiccup/PluginManager.py/PluginManager.disable_plugin
1,412
def test_raise_no_arg(self): r = None try: try: raise RuntimeError("dummy") except __HOLE__: raise except RuntimeError, e: r = str(e) self.assertEquals(r, "dummy")
RuntimeError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_exceptions_jy.py/ExceptionsTestCase.test_raise_no_arg
1,413
def all_query(expression): """Match arrays that contain all elements in the query.""" def _all(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression try: iter(ev) except _...
TypeError
dataset/ETHPy150Open adewes/blitzdb/blitzdb/backends/file/queries.py/all_query
1,414
def in_query(expression): """Match any of the values that exist in an array specified in query.""" def _in(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression try: iter(ev) ...
TypeError
dataset/ETHPy150Open adewes/blitzdb/blitzdb/backends/file/queries.py/in_query
1,415
@classmethod def wrap_iterable(cls, url_or_urls): """Given a string or :class:`Link` or iterable, return an iterable of :class:`Link` objects. :param url_or_urls: A string or :class:`Link` object, or iterable of string or :class:`Link` objects. :returns: A list of :class:`Link` objects. """ ...
ValueError
dataset/ETHPy150Open pantsbuild/pex/pex/link.py/Link.wrap_iterable
1,416
def _call(self, input_str, binary, args=[], verbose=False): """ Call the binary with the given input. :param input_str: A string whose contents are used as stdin. :param binary: The location of the binary to call :param args: A list of command-line arguments. :return: A ...
AttributeError
dataset/ETHPy150Open nltk/nltk/nltk/inference/prover9.py/Prover9Parent._call
1,417
def validate_user(f): try: results = db.query("SELECT * FROM users WHERE username=$username ORDER BY ROWID ASC LIMIT 1", vars={'username': f.username.value}) user = results[0] try: valid_hash = pbkdf2_sha256.verify(f.password.value, user.password) ...
IndexError
dataset/ETHPy150Open ab77/netflix-proxy/auth/auth.py/validate_user
1,418
def _check_imports(): """ Dynamically remove optimizers we don't have """ optlist = ['ALGENCIAN', 'ALHSO', 'ALPSO', 'COBYLA', 'CONMIN', 'FILTERSD', 'FSQP', 'GCMMA', 'KSOPT', 'MIDACO', 'MMA', 'MMFD', 'NLPQL', 'NLPQLP', 'NSGA2', 'PSQP', 'SDPEN', 'SLSQP', 'SNOPT', 'SOLVOPT'] ...
ImportError
dataset/ETHPy150Open OpenMDAO-Plugins/pyopt_driver/src/pyopt_driver/pyopt_driver.py/_check_imports
1,419
def execute(self): """pyOpt execution. Note that pyOpt controls the execution, and the individual optimizers control the iteration.""" self.pyOpt_solution = None self.run_iteration() opt_prob = Optimization(self.title, self.objfunc, var_set={}, ...
ImportError
dataset/ETHPy150Open OpenMDAO-Plugins/pyopt_driver/src/pyopt_driver/pyopt_driver.py/pyOptDriver.execute
1,420
@log_function @defer.inlineCallbacks def do_invite_join(self, target_hosts, room_id, joinee, content): """ Attempts to join the `joinee` to the room `room_id` via the server `target_host`. This first triggers a /make_join/ request that returns a partial event that we can fill ou...
ValueError
dataset/ETHPy150Open matrix-org/synapse/synapse/handlers/federation.py/FederationHandler.do_invite_join
1,421
@defer.inlineCallbacks def do_remotely_reject_invite(self, target_hosts, room_id, user_id): origin, event = yield self._make_and_verify_event( target_hosts, room_id, user_id, "leave" ) signed_event = self._sign_event(event) # Try the h...
ValueError
dataset/ETHPy150Open matrix-org/synapse/synapse/handlers/federation.py/FederationHandler.do_remotely_reject_invite
1,422
@defer.inlineCallbacks def construct_auth_difference(self, local_auth, remote_auth): """ Given a local and remote auth chain, find the differences. This assumes that we have already processed all events in remote_auth Params: local_auth (list) remote_auth (list) ...
ValueError
dataset/ETHPy150Open matrix-org/synapse/synapse/handlers/federation.py/FederationHandler.construct_auth_difference
1,423
def __init__(self, resource, location, name, func): """Initialize the switch.""" super().__init__(resource, location, name) self._func = func request = requests.get('{}/{}'.format(self._resource, self._func), timeout=10) if request.status_code is ...
ValueError
dataset/ETHPy150Open home-assistant/home-assistant/homeassistant/components/switch/arest.py/ArestSwitchFunction.__init__
1,424
@login_required def message_create(request, content_type_id=None, object_id=None, template_name='messages/message_form.html'): """ Handles a new message and displays a form. Template:: ``messages/message_form.html`` Context: form MessageForm object """ n...
ObjectDoesNotExist
dataset/ETHPy150Open nathanborror/django-basic-apps/basic/messages/views.py/message_create
1,425
def load(self, backend, *args, **kwargs): i = backend.rfind('.') module, attr = backend[:i], backend[i+1:] try: __import__(module) mod = sys.modules[module] except ImportError, e: raise ImproperlyConfigured( "Error importing upload hand...
AttributeError
dataset/ETHPy150Open jezdez-archive/django-vcstorage/src/vcstorage/storage.py/VcStorage.load
1,426
def save(self, name, content, message=None): """ Saves the given content with the name and commits to the working dir. """ self.populate() if message is None: message = "Automated commit: adding %s" % name name = super(VcStorage, self).save(name, content) ...
OSError
dataset/ETHPy150Open jezdez-archive/django-vcstorage/src/vcstorage/storage.py/VcStorage.save
1,427
def delete(self, name, message=None): """ Deletes the specified file from the storage system. """ self.populate() if message is None: message = "Automated commit: removing %s" % name full_paths = [smart_str(self.path(name))] try: self.wd.re...
OSError
dataset/ETHPy150Open jezdez-archive/django-vcstorage/src/vcstorage/storage.py/VcStorage.delete
1,428
def test_max_recursion_error(self): """ Overriding a method on a super class and then calling that method on the super class should not trigger infinite recursion. See #17011. """ try: super(ClassDecoratedTestCase, self).test_max_recursion_error() except __HOL...
RuntimeError
dataset/ETHPy150Open django/django/tests/settings_tests/tests.py/ClassDecoratedTestCase.test_max_recursion_error
1,429
@staticmethod def _FindNextOpcode(job, timeout_strategy_factory): """Locates the next opcode to run. @type job: L{_QueuedJob} @param job: Job object @param timeout_strategy_factory: Callable to create new timeout strategy """ # Create some sort of a cache to speed up locating next opcode for...
StopIteration
dataset/ETHPy150Open ganeti/ganeti/lib/jqueue/__init__.py/_JobProcessor._FindNextOpcode
1,430
@staticmethod def _ResolveJobDependencies(resolve_fn, deps): """Resolves relative job IDs in dependencies. @type resolve_fn: callable @param resolve_fn: Function to resolve a relative job ID @type deps: list @param deps: Dependencies @rtype: tuple; (boolean, string or list) @return: If su...
IndexError
dataset/ETHPy150Open ganeti/ganeti/lib/jqueue/__init__.py/JobQueue._ResolveJobDependencies
1,431
@ratelimit(rate='1200/h', method=None, block=True) def surveyform(request, assignment_id): assignment = get_object_or_404(Assignment, form_slug=assignment_id) # This variable is no longer used. It was initially developed # as a reference to the FormRequest for a separate view that would # change th...
AttributeError
dataset/ETHPy150Open newsday/newstools-checkup/checkup/views.py/surveyform
1,432
def _parse_body(self, stream): rows, cols, entries, format, field, symm = (self.rows, self.cols, self.entries, self.format, self.field, self.symmetry) try: from scipy.sparse import coo_ma...
ImportError
dataset/ETHPy150Open scipy/scipy/scipy/io/mmio.py/MMFile._parse_body
1,433
def _is_fromfile_compatible(stream): """ Check whether `stream` is compatible with numpy.fromfile. Passing a gzipped file object to ``fromfile/fromstring`` doesn't work with Python3. """ if sys.version_info[0] < 3: return True bad_cls = [] try: import gzip bad_c...
ImportError
dataset/ETHPy150Open scipy/scipy/scipy/io/mmio.py/_is_fromfile_compatible
1,434
@increment_visitor_counter def survey(request, survey_code, code, page=1): answer = get_object_or_404( SurveyAnswer.objects.select_related('survey'), survey__is_active=True, survey__code=survey_code, code=code) answer.update_status(answer.STARTED) pages = answer.survey.page...
TypeError
dataset/ETHPy150Open matthiask/survey/survey/views.py/survey
1,435
def set(self, ob, **kwargs): self.real_neighbor(ob) if isinstance(ob, NeuronClass): ob_name = ob.name() this_name = self.owner.name() for x in ob.member(): # Get the name for the neighbor # XXX: try: ...
ValueError
dataset/ETHPy150Open openworm/PyOpenWorm/examples/rmgr.py/NC_neighbor.set
1,436
def process(self, definitions_asset, nodes, nvtristrip, materials, effects): # Look at the material to check for geometry requirements need_normals = False need_tangents = False generate_normals = False generate_tangents = False # Assumed to be a graphics geometry ...
OSError
dataset/ETHPy150Open turbulenz/turbulenz_tools/turbulenz_tools/tools/dae2json.py/Dae2Geometry.process
1,437
def parse(input_filename="default.dae", output_filename="default.json", asset_url="", asset_root=".", infiles=None, options=None): """Untility function to convert a Collada file into a JSON file.""" definitions_asset = standard_include(infiles) animations = { } animation_clips = { } geom...
IOError
dataset/ETHPy150Open turbulenz/turbulenz_tools/turbulenz_tools/tools/dae2json.py/parse
1,438
def set_task_flags(self, task_flags): try: flags = int(task_flags) except (__HOLE__, TypeError): flags = self.words_to_flags(task_flags, "TASK_FLAG_") self.task.SetTaskFlags(flags)
ValueError
dataset/ETHPy150Open tjguk/winsys/winsys/scheduled_tasks.py/Task.set_task_flags
1,439
def _intercept(self, env, start_response): import figleaf try: import cPickle as pickle except __HOLE__: import pickle coverage = figleaf.get_info() s = pickle.dumps(coverage) start_response("200 OK", [('Content-type', 'application/x-pickle')]) ...
ImportError
dataset/ETHPy150Open rtyler/Spawning/spawning/spawning_child.py/FigleafCoverage._intercept
1,440
def send_status_to_controller(self): try: child_status = {'pid':os.getpid()} if self.server: child_status['concurrent_requests'] = \ self.server.outstanding_requests else: child_status['error'] = 'Starting...' b...
SystemExit
dataset/ETHPy150Open rtyler/Spawning/spawning/spawning_child.py/ChildStatus.send_status_to_controller
1,441
def warn_controller_of_imminent_death(controller_pid): # The controller responds to a SIGUSR1 by kicking off a new child process. try: os.kill(controller_pid, signal.SIGUSR1) except __HOLE__, e: if not e.errno == errno.ESRCH: raise
OSError
dataset/ETHPy150Open rtyler/Spawning/spawning/spawning_child.py/warn_controller_of_imminent_death
1,442
def serve_from_child(sock, config, controller_pid): threads = config.get('threadpool_workers', 0) wsgi_application = spawning.util.named(config['app_factory'])(config) if config.get('coverage'): wsgi_application = FigleafCoverage(wsgi_application) if config.get('sysinfo'): wsgi_applicat...
KeyboardInterrupt
dataset/ETHPy150Open rtyler/Spawning/spawning/spawning_child.py/serve_from_child
1,443
def test_empty(self): # Raise an ImportWarning if sys.meta_path is empty. module_name = 'nothing' try: del sys.modules[module_name] except __HOLE__: pass with util.import_state(meta_path=[]): with warnings.catch_warnings(record=True) as w: ...
KeyError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_importlib/import_/test_meta_path.py/CallingOrder.test_empty
1,444
def __getattr__(self, attr): try: return self[attr] except __HOLE__: raise AttributeError(r"'JsonDict' object has no attribute '%s'" % attr)
KeyError
dataset/ETHPy150Open michaelliao/sinaweibopy/weibo.py/JsonDict.__getattr__
1,445
def get_provider_or_404(provider_id): try: return current_app.extensions['social'].providers[provider_id] except __HOLE__: abort(404)
KeyError
dataset/ETHPy150Open mattupstate/flask-social/flask_social/utils.py/get_provider_or_404
1,446
def request(self, kvp): """process OAI-PMH request""" kvpout = {'service': 'CSW', 'version': '2.0.2', 'mode': 'oaipmh'} LOGGER.debug('Incoming kvp: %s' % kvp) if 'verb' in kvp: if 'metadataprefix' in kvp: self.metadata_prefix = kvp['metadataprefix'] ...
KeyError
dataset/ETHPy150Open geopython/pycsw/pycsw/oaipmh.py/OAIPMH.request
1,447
def _get_metadata_prefix(self, prefix): """Convenience function to return metadataPrefix as CSW outputschema""" try: outputschema = self.metadata_formats[prefix]['namespace'] except __HOLE__: outputschema = prefix return outputschema
KeyError
dataset/ETHPy150Open geopython/pycsw/pycsw/oaipmh.py/OAIPMH._get_metadata_prefix
1,448
def encode_uid(pk): try: from django.utils.http import urlsafe_base64_encode from django.utils.encoding import force_bytes return urlsafe_base64_encode(force_bytes(pk)).decode() except __HOLE__: from django.utils.http import int_to_base36 return int_to_base36(pk)
ImportError
dataset/ETHPy150Open sunscrapers/djoser/djoser/utils.py/encode_uid
1,449
def decode_uid(pk): try: from django.utils.http import urlsafe_base64_decode from django.utils.encoding import force_text return force_text(urlsafe_base64_decode(pk)) except __HOLE__: from django.utils.http import base36_to_int return base36_to_int(pk)
ImportError
dataset/ETHPy150Open sunscrapers/djoser/djoser/utils.py/decode_uid
1,450
def UserModelString(): try: return settings.AUTH_USER_MODEL except __HOLE__: return 'auth.User'
AttributeError
dataset/ETHPy150Open macropin/django-registration/registration/users.py/UserModelString
1,451
def visit(self, node): if node is None: return None if type(node) is tuple: return tuple([self.visit(n) for n in node]) try: self.blame_stack.append((node.lineno, node.col_offset,)) info = True except __HOLE__: info = False ...
AttributeError
dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/genshi/template/astutil.py/ASTCodeGenerator.visit
1,452
def _clone(self, node): clone = node.__class__() for name in getattr(clone, '_attributes', ()): try: setattr(clone, name, getattr(node, name)) except AttributeError: pass for name in clone._fields: try: value = g...
AttributeError
dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/genshi/template/astutil.py/ASTTransformer._clone
1,453
@inlineCallbacks def _callback(self): """ This will be called repeatedly every `self.interval` seconds. `self.subscriptions` contain tuples of (obj, args, kwargs) for each subscribing object. If overloading, this callback is expected to handle all subscriptions when ...
ObjectDoesNotExist
dataset/ETHPy150Open evennia/evennia/evennia/scripts/tickerhandler.py/Ticker._callback
1,454
def _store_key(self, obj, interval, idstring=""): """ Tries to create a store_key for the object. Returns a tuple (isdb, store_key) where isdb is a boolean True if obj was a database object, False otherwise. Args: obj (Object): Subscribing object. interv...
AttributeError
dataset/ETHPy150Open evennia/evennia/evennia/scripts/tickerhandler.py/TickerHandler._store_key
1,455
def __getitem__(self, key): try: return getattr(self, key) except __HOLE__: raise KeyError(key)
AttributeError
dataset/ETHPy150Open letsencrypt/letsencrypt/acme/acme/jose/util.py/ImmutableMap.__getitem__
1,456
def __getattr__(self, name): try: return self._items[name] except __HOLE__: raise AttributeError(name)
KeyError
dataset/ETHPy150Open letsencrypt/letsencrypt/acme/acme/jose/util.py/frozendict.__getattr__
1,457
def validate ( self, object, name, value ): """ Validates that a specified value is valid for this trait. """ if type(value) is int: return value elif type(value) is long: return int(value) try: int_value = operator.index( value ) exce...
TypeError
dataset/ETHPy150Open enthought/traits/traits/trait_types.py/BaseInt.validate
1,458
def validate ( self, object, name, value ): """ Validates that the values is a valid list. """ if not isinstance( value, list ): try: # Should work for all iterables as well as strings (which do # not define an __iter__ method) value = ...
TypeError
dataset/ETHPy150Open enthought/traits/traits/trait_types.py/CList.validate
1,459
def validate ( self, object, name, value ): """ Validates that the values is a valid list. """ if not isinstance( value, set ): try: # Should work for all iterables as well as strings (which do # not define an __iter__ method) value = s...
TypeError
dataset/ETHPy150Open enthought/traits/traits/trait_types.py/CSet.validate
1,460
def get_one(self, context, name): """ Returns a function if it is registered, the context is ignored. """ try: return self.functions[name] except __HOLE__: raise FunctionNotFound(name)
KeyError
dataset/ETHPy150Open stepank/pyws/src/pyws/functions/managers.py/FixedFunctionManager.get_one
1,461
def _test_impl(self, data, ref): res = [] while True: tok = self.lexer.token() if not tok: break res.append(tok.type) if is_string(ref): ref = split(ref) try: self.assertEqual(res, ref) except __HOLE__: ...
AssertionError
dataset/ETHPy150Open cournape/Bento/bento/parser/tests/test_lexer.py/TestLexer._test_impl
1,462
@register.tag def featured_projects(parser, token): try: tag_name, number = token.split_contents() except __HOLE__: raise template.TemplateSyntaxError("%r tag requires a single argument" % token.contents.split()[0]) try: int(number) except ValueError: raise template.Templ...
ValueError
dataset/ETHPy150Open python/raspberryio/raspberryio/project/templatetags/project_tags.py/featured_projects
1,463
@classmethod def super_key(cls, supertable, default=None): """ Get the name of the key for a super-entity @param supertable: the super-entity table """ if supertable is None and default: return default if isinstance(supertable, str): ...
AttributeError
dataset/ETHPy150Open sahana/eden/modules/s3/s3model.py/S3Model.super_key
1,464
def increment_filename(filename): dirname = os.path.dirname(filename) root, ext = os.path.splitext(os.path.basename(filename)) result = None try: root_start, root_number_end = rx_numbered.match(root).groups() except __HOLE__: pass else: result = "%s%s" % (root_start, st...
AttributeError
dataset/ETHPy150Open Starou/SimpleIDML/src/simple_idml/utils.py/increment_filename
1,465
def hexascii(self, target_data, byte, offset): color = "green" for (fp_i, data_i) in iterator(target_data): diff_count = 0 for (fp_j, data_j) in iterator(target_data): if fp_i == fp_j: continue try: if dat...
IndexError
dataset/ETHPy150Open devttys0/binwalk/src/binwalk/modules/hexdiff.py/HexDiff.hexascii
1,466
@classmethod def setupClass(cls): global numpy global assert_equal global assert_almost_equal try: import numpy from numpy.testing import assert_equal,assert_almost_equal except __HOLE__: raise SkipTest('NumPy not available.')
ImportError
dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/linalg/tests/test_spectrum.py/TestSpectrum.setupClass
1,467
def get_name(self): """Returns a name of this instance""" try: docrule_name = self.doccode.get_title() except (KeyError, __HOLE__): docrule_name = 'No name given' pass return unicode(docrule_name)
AttributeError
dataset/ETHPy150Open adlibre/Adlibre-DMS/adlibre_dms/apps/dms_plugins/models.py/DoccodePluginMapping.get_name
1,468
def to_dot(self): """Render the dot for the recorded execution.""" try: import pygraphviz as pgv except __HOLE__: warnings.warn('Extra requirements for "trace" are not available.') return graph = pgv.AGraph(directed=True, strict=False) hanging...
ImportError
dataset/ETHPy150Open severb/flowy/flowy/tracer.py/ExecutionTracer.to_dot
1,469
def prompt_user(query, results): try: response = None short_respones = 0 while not response: response = input("{}\nYour Response: ".format(query)) if not response or len(response) < 5: short_respones += 1 # Do not ask more than twice to...
KeyboardInterrupt
dataset/ETHPy150Open Cal-CS-61A-Staff/ok-client/client/protocols/hinting.py/prompt_user
1,470
def get_embed(url, max_width=None, finder=None): # Check database try: return Embed.objects.get(url=url, max_width=max_width) except Embed.DoesNotExist: pass # Get/Call finder if not finder: finder = get_default_finder() embed_dict = finder(url, max_width) # Make su...
TypeError
dataset/ETHPy150Open torchbox/wagtail/wagtail/wagtailembeds/embeds.py/get_embed
1,471
def testLogic(self): x = 0 or None self.assertEqual(x, None, "0 or None should be None not %s" % repr(x) ) x = None and None self.assertEqual(x, None, "None or None should be None not %s" % repr(x) ) x = False or None self.assertEqual(x, None, "False or None should...
TypeError
dataset/ETHPy150Open anandology/pyjamas/examples/libtest/BoolTest.py/BoolTest.testLogic
1,472
def createsuperuser(username=None, email=None, password=None): """ Helper function for creating a superuser from the command line. All arguments are optional and will be prompted-for if invalid or not given. """ try: import pwd except ImportError: default_username = '' else: ...
KeyboardInterrupt
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/contrib/auth/create_superuser.py/createsuperuser
1,473
def process_request(self, request): locale, path = utils.strip_path(request.path_info) if localeurl_settings.USE_SESSION and not locale: slocale = request.session.get('django_language') if slocale and utils.supported_language(slocale): locale = slocale if ...
AttributeError
dataset/ETHPy150Open carljm/django-localeurl/localeurl/middleware.py/LocaleURLMiddleware.process_request
1,474
def main(): # bring our logging stuff up as early as possible debug = ('-d' in sys.argv or '--debug' in sys.argv) _init_logger(debug) extension_mgr = _init_extensions() baseline_formatters = [f.name for f in filter(lambda x: hasattr(x.plugin, ...
ValueError
dataset/ETHPy150Open openstack/bandit/bandit/cli/main.py/main
1,475
def handle(self, fn_name, action, *args, **kwds): self.parent.calls.append((self, fn_name, args, kwds)) if action is None: return None elif action == "return self": return self elif action == "return response": res = MockResponse(200, "OK", {}, "") ...
ValueError
dataset/ETHPy150Open francelabs/datafari/windows/python/Lib/test/test_urllib2.py/MockHandler.handle
1,476
def test_file(self): import rfc822, socket h = urllib2.FileHandler() o = h.parent = MockOpener() TESTFN = test_support.TESTFN urlpath = sanepathname2url(os.path.abspath(TESTFN)) towrite = "hello, world\n" urls = [ "file://localhost%s" % urlpath, ...
OSError
dataset/ETHPy150Open francelabs/datafari/windows/python/Lib/test/test_urllib2.py/HandlerTests.test_file
1,477
def test_redirect(self): from_url = "http://example.com/a.html" to_url = "http://example.com/b.html" h = urllib2.HTTPRedirectHandler() o = h.parent = MockOpener() # ordinary redirect behaviour for code in 301, 302, 303, 307: for data in None, "blah\nblah\n": ...
AttributeError
dataset/ETHPy150Open francelabs/datafari/windows/python/Lib/test/test_urllib2.py/HandlerTests.test_redirect
1,478
def test_HTTPError_interface_call(self): """ Issue 15701= - HTTPError interface has info method available from URLError. """ err = urllib2.HTTPError(msg='something bad happened', url=None, code=None, hdrs='Content-Length:42', fp=None) self.assertTr...
AttributeError
dataset/ETHPy150Open francelabs/datafari/windows/python/Lib/test/test_urllib2.py/RequestTests.test_HTTPError_interface_call
1,479
def __init__(self, addr, conf, log, fd=None): if fd is None: try: st = os.stat(addr) except __HOLE__ as e: if e.args[0] != errno.ENOENT: raise else: if stat.S_ISSOCK(st.st_mode): os.remove...
OSError
dataset/ETHPy150Open chalasr/Flask-P2P/venv/lib/python2.7/site-packages/gunicorn/sock.py/UnixSocket.__init__
1,480
def process_request(self, request): try: auth = request.GET.get('auth') except __HOLE__: # Django can throw an IOError when trying to read the GET # data. return if auth is None or (request.user and request.user.is_authenticated()): re...
IOError
dataset/ETHPy150Open mozilla/kitsune/kitsune/users/middleware.py/TokenLoginMiddleware.process_request
1,481
def chunk(self): if not self.iter: return b"" try: return six.next(self.iter) except __HOLE__: self.iter = None return b""
StopIteration
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/gunicorn/http/unreader.py/IterUnreader.chunk
1,482
def __getitem__(self, key): # This is a workaround to make TaskResource non-iterable # over simple index-based iteration try: int(key) raise StopIteration except __HOLE__: pass if key not in self._data: self._data[key] = self._dese...
ValueError
dataset/ETHPy150Open robgolding63/tasklib/tasklib/task.py/TaskResource.__getitem__
1,483
def __bool__(self): if self._result_cache is not None: return bool(self._result_cache) try: next(iter(self)) except __HOLE__: return False return True
StopIteration
dataset/ETHPy150Open robgolding63/tasklib/tasklib/task.py/TaskQuerySet.__bool__
1,484
def test_options(self): finish = rdbms_conf.DATABASES['sqlitee'].OPTIONS.set_for_testing({'nonsensical': None}) try: self.client.get(reverse('rdbms:api_tables', args=['sqlitee', self.database])) except __HOLE__, e: assert_true('nonsensical' in str(e), e) finish()
TypeError
dataset/ETHPy150Open cloudera/hue/apps/rdbms/src/rdbms/tests.py/TestAPI.test_options
1,485
def _class_count(objects): """List the most common object classes""" totals = {} for obj in objects: try: cls = obj.__class__ except __HOLE__: cls = type(obj) name = "%s.%s" % (cls.__module__, cls.__name__) try: totals[name].append(obj) ...
AttributeError
dataset/ETHPy150Open marineam/nagcat/python/nagcat/monitor_api.py/_class_count
1,486
def main(): while True: task = socket.recv_json() # Convert the JSON dict we got into a Task object. try: task = to_task(task) except __HOLE__ as e: # sisyphus is only exposed to internal components within Galah. # This is a very serious error sig...
RuntimeError
dataset/ETHPy150Open ucrcsedept/galah/galah/sisyphus/sisyphus.py/main
1,487
def check_proxy_setting(): """ If the environmental variable 'HTTP_PROXY' is set, it will most likely be in one of these forms: proxyhost:8080 http://proxyhost:8080 urlllib2 requires the proxy URL to start with 'http://' This routine does that, and returns the transport for xml...
KeyError
dataset/ETHPy150Open cakebread/yolk/yolk/pypi.py/check_proxy_setting
1,488
def get_xmlrpc_server(self): """ Returns PyPI's XML-RPC server instance """ check_proxy_setting() if os.environ.has_key('XMLRPC_DEBUG'): debug = 1 else: debug = 0 try: return xmlrpclib.Server(XML_RPC_SERVER, transport=ProxyTrans...
IOError
dataset/ETHPy150Open cakebread/yolk/yolk/pypi.py/CheeseShop.get_xmlrpc_server
1,489
def rfc3339(date, utc=False, use_system_timezone=True): ''' Return a string formatted according to the :RFC:`3339`. If called with `utc=True`, it normalizes `date` to the UTC date. If `date` does not have any timezone information, uses the local timezone:: >>> d = datetime.datetime(2008, 4, 2, ...
TypeError
dataset/ETHPy150Open eugenkiss/Simblin/simblin/lib/rfc3339.py/rfc3339
1,490
def run_mercurial_command(hg_command): hg_executable = os.environ.get("HG", "hg") hg_command_tuple = hg_command.split() hg_command_tuple.insert(0, hg_executable) # If you install your own mercurial version in your home # hg_executable does not always have execution permission. if not os.access(h...
OSError
dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/misc/hooks/check_whitespace.py/run_mercurial_command
1,491
def delete(self): dir = os.path.dirname(os.path.join(settings.MEDIA_ROOT, self.fileobject.name)) try: self.fileobject.delete() except __HOLE__: pass try: os.rmdir(dir) except OSError: pass return Model.delete(self)
OSError
dataset/ETHPy150Open peterkuma/fileshackproject/fileshack/models.py/Item.delete
1,492
def name(self): try: return os.path.basename(self.fileobject.name) except (OSError,__HOLE__): return None
ValueError
dataset/ETHPy150Open peterkuma/fileshackproject/fileshack/models.py/Item.name
1,493
def as_scalar(x, name=None): from ..tensor import TensorType, scalar_from_tensor if isinstance(x, gof.Apply): if len(x.outputs) != 1: raise ValueError("It is ambiguous which output of a multi-output" " Op has to be fetched.", x) else: x = x.ou...
TypeError
dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/scalar/basic.py/as_scalar
1,494
def dtype_specs(self): try: # To help debug dtype/typenum problem, here is code to get # the list of numpy typenum. This list change between 32 # and 64 bit platform and probably also also between # Windows and Linux. # NOTE: equivalent type on a plat...
KeyError
dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/scalar/basic.py/Scalar.dtype_specs
1,495
def init_name(self): """ Return a readable string representation of self.fgraph. """ try: rval = self.name except __HOLE__: if 0: l = [] for n in self.fgraph.toposort(): if hasattr(n.op, "name") and n.op...
AttributeError
dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/scalar/basic.py/Composite.init_name
1,496
def __getitem__(self, idx): """Return :class:`Mat` block with row and column given by ``idx`` or a given row of blocks.""" try: i, j = idx return self.blocks[i][j] except __HOLE__: return self.blocks[idx]
TypeError
dataset/ETHPy150Open OP2/PyOP2/pyop2/petsc_base.py/Mat.__getitem__
1,497
@collective def _solve(self, A, x, b): self._set_parameters() # Set up the operator only if it has changed if not self.getOperators()[0] == A.handle: self.setOperators(A.handle) if self.parameters['pc_type'] == 'fieldsplit' and A.sparsity.shape != (1, 1): ...
ImportError
dataset/ETHPy150Open OP2/PyOP2/pyop2/petsc_base.py/Solver._solve
1,498
def string_to_datetime(datetimestring, date_formats=None): date_formats = date_formats or [ '%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%dT%H:%M:%S.%fZ', '%Y-%m-%dT%H:%M:%S.%f', "%Y-%m-%dT%H:%M:%SZ", "%Y-%m-%dT%H:%M:%S"] for dateformat in date_formats: try: return da...
ValueError
dataset/ETHPy150Open openstack/python-barbicanclient/functionaltests/utils.py/string_to_datetime
1,499
def isImageLibAvailable(): try: from ConvertPackage.ConvertFile import convertFile return True except __HOLE__: return False
ImportError
dataset/ETHPy150Open jiaweihli/manga_downloader/src/util.py/isImageLibAvailable