Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
3,500
def test(): import sys recursive = 0 if sys.argv[1:] and sys.argv[1] == '-r': del sys.argv[1:2] recursive = 1 try: if sys.argv[1:]: testall(sys.argv[1:], recursive, 1) else: testall(['.'], recursive, 1) except __HOLE__: sys.stderr.write...
KeyboardInterrupt
dataset/ETHPy150Open babble/babble/include/jython/Lib/sndhdr.py/test
3,501
def testall(list, recursive, toplevel): import sys import os for filename in list: if os.path.isdir(filename): print filename + '/:', if recursive or toplevel: print 'recursing down:' import glob names = glob.glob(os.path.join(f...
IOError
dataset/ETHPy150Open babble/babble/include/jython/Lib/sndhdr.py/testall
3,502
def program(args, env, log_error): """ The main program without error handling :param args: parsed args (argparse.Namespace) :type env: Environment :param log_error: error log function :return: status code """ exit_status = ExitStatus.OK downloader = None show_traceback = args....
IOError
dataset/ETHPy150Open jkbrzt/httpie/httpie/core.py/program
3,503
def main(args=sys.argv[1:], env=Environment(), custom_log_error=None): """ The main function. Pre-process args, handle some special types of invocations, and run the main program with error handling. Return exit status code. """ args = decode_args(args, env.stdin_encoding) plugin_mana...
KeyboardInterrupt
dataset/ETHPy150Open jkbrzt/httpie/httpie/core.py/main
3,504
def __new__(cls, ctypesArray, shape, dtype=float, strides=None, offset=0, order=None): #some magic (copied from numpy.ctypeslib) to make sure the ctypes array #has the array interface tp = type(ctypesArray) try: tp.__array_interface__ except __HOLE__: ctypeslib...
AttributeError
dataset/ETHPy150Open aheadley/pynemap/shmem.py/shmarray.__new__
3,505
def parse_mapreduce_yaml(contents): """Parses mapreduce.yaml file contents. Args: contents: mapreduce.yaml file contents. Returns: MapReduceYaml object with all the data from original file. Raises: errors.BadYamlError: when contents is not a valid mapreduce.yaml file. """ try: builder = y...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/ext/mapreduce/status.py/parse_mapreduce_yaml
3,506
def __getitem__(self, name): "Returns a BoundField with the given name." try: field = self.fields[name] except __HOLE__: raise KeyError('Key %r not found in Form' % name) return BoundField(self, field, name)
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/newforms/forms.py/BaseForm.__getitem__
3,507
def full_clean(self): """ Cleans all of self.data and populates self.__errors and self.clean_data. """ errors = ErrorDict() if not self.is_bound: # Stop further processing. self.__errors = errors return self.clean_data = {} for name, field ...
ValidationError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/newforms/forms.py/BaseForm.full_clean
3,508
def handle_bot_message(event, server): try: bot = server.slack.server.bots[event["bot_id"]] except __HOLE__: logger.debug("bot_message event {0} has no bot".format(event)) return return "\n".join(run_hook(server.hooks, "bot_message", event, server))
KeyError
dataset/ETHPy150Open serverdensity/sdbot/limbo/handlers/__init__.py/handle_bot_message
3,509
def handle_message(event, server): subtype = event.get("subtype", "") if subtype == "message_changed": return if subtype == "bot_message": return handle_bot_message(event, server) try: msguser = server.slack.server.users[event["user"]] except __HOLE__: logger.debug(...
KeyError
dataset/ETHPy150Open serverdensity/sdbot/limbo/handlers/__init__.py/handle_message
3,510
def collect(self): metrics = {} raw = {} data = self.getData() data = data.split('\n\x00') for d in data: matches = re.search("([A-Z]+)\s+:\s+(.*)$", d) if matches: value = matches.group(2).strip() raw[matches.group(1)] = ...
ValueError
dataset/ETHPy150Open BrightcoveOS/Diamond/src/collectors/apcupsd/apcupsd.py/ApcupsdCollector.collect
3,511
def test_unresolvable_specification_raises(self): try: Specification.from_object(None) except __HOLE__: pass else: assert False, "Failed to raise TypeError."
TypeError
dataset/ETHPy150Open marrow/script/test/test_schema.py/TestSpecification.test_unresolvable_specification_raises
3,512
def _request(self, url, params=None, files=None, method='GET', check_for_errors=True): url = self._resolve_url(url) self.log.info("{method} {url!r} with params {params!r}".format(method=method, url=url, params=params)) if params is None: params = {} if self.access_token: ...
KeyError
dataset/ETHPy150Open hozn/stravalib/stravalib/protocol.py/ApiV3._request
3,513
def _handle_protocol_error(self, response): """ Parses the raw response from the server, raising a :class:`stravalib.exc.Fault` if the server returned an error. :param response: The response object. :raises Fault: If the response contains an error. """ error_str ...
ValueError
dataset/ETHPy150Open hozn/stravalib/stravalib/protocol.py/ApiV3._handle_protocol_error
3,514
def _extract_referenced_vars(self, s): """ Utility method to find the referenced format variables in a string. (Assumes string.format() format vars.) :param s: The string that contains format variables. (e.g. "{foo}-text") :return: The list of referenced variable names. (e.g. ['f...
KeyError
dataset/ETHPy150Open hozn/stravalib/stravalib/protocol.py/ApiV3._extract_referenced_vars
3,515
def _get_settings_from_cmd_line(self): for arg in sys.argv[1:]: for lib_arg in self.COMMAND_LINE_ARGS: if arg.startswith(lib_arg): try: return arg.split('=')[1] except __HOLE__: return ret...
IndexError
dataset/ETHPy150Open drgarcia1986/simple-settings/simple_settings/core.py/LazySettings._get_settings_from_cmd_line
3,516
def __getattr__(self, attr): self.setup() try: return self._dict[attr] except __HOLE__: raise AttributeError('You do not set {} setting'.format(attr))
KeyError
dataset/ETHPy150Open drgarcia1986/simple-settings/simple_settings/core.py/LazySettings.__getattr__
3,517
def get_in(keys, coll, default=None, no_default=False): """ Returns coll[i0][i1]...[iX] where [i0, i1, ..., iX]==keys. If coll[i0][i1]...[iX] cannot be found, returns ``default``, unless ``no_default`` is specified, then it raises KeyError or IndexError. ``get_in`` is a generalization of ``operato...
IndexError
dataset/ETHPy150Open pytoolz/toolz/toolz/dicttoolz.py/get_in
3,518
def __get_raw_model(self, model_id): try: doc = views.model_definitions(self._db, key=model_id).rows[0] return doc.value except __HOLE__: raise backend_exceptions.ModelNotFound(model_id)
IndexError
dataset/ETHPy150Open spiral-project/daybed/daybed/backends/couchdb/__init__.py/CouchDBBackend.__get_raw_model
3,519
def __get_raw_record(self, model_id, record_id): key = u'-'.join((model_id, record_id)) try: return views.records_all(self._db, key=key).rows[0].value except __HOLE__: raise backend_exceptions.RecordNotFound( u'(%s, %s)' % (model_id, record_id) ...
IndexError
dataset/ETHPy150Open spiral-project/daybed/daybed/backends/couchdb/__init__.py/CouchDBBackend.__get_raw_record
3,520
def delete_model(self, model_id): """DELETE ALL THE THINGS""" # Delete the associated data if any. records = self.delete_records(model_id) try: doc = views.model_definitions(self._db, key=model_id).rows[0].value except __HOLE__: raise backend_exceptions....
IndexError
dataset/ETHPy150Open spiral-project/daybed/daybed/backends/couchdb/__init__.py/CouchDBBackend.delete_model
3,521
def __get_raw_token(self, credentials_id): try: return views.tokens(self._db, key=credentials_id).rows[0].value except __HOLE__: raise backend_exceptions.CredentialsNotFound(credentials_id)
IndexError
dataset/ETHPy150Open spiral-project/daybed/daybed/backends/couchdb/__init__.py/CouchDBBackend.__get_raw_token
3,522
def sshagent_run(command, use_sudo=False): """ Helper function. Runs a command with SSH agent forwarding enabled. Note:: Fabric (and paramiko) can't forward your SSH agent. This helper uses your system's ssh to do so. """ if use_sudo: command = 'sudo %s' % command cwd = env.ge...
ValueError
dataset/ETHPy150Open bueda/ops/buedafab/operations.py/sshagent_run
3,523
def register_storage_use(storage_path, hostname): """Identify the id of this instance storage.""" LOCK_PATH = os.path.join(CONF.instances_path, 'locks') @utils.synchronized('storage-registry-lock', external=True, lock_path=LOCK_PATH) def do_register_storage_use(storage_path, ho...
ValueError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/storage_users.py/register_storage_use
3,524
def get_storage_users(storage_path): """Get a list of all the users of this storage path.""" # See comments above method register_storage_use LOCK_PATH = os.path.join(CONF.instances_path, 'locks') @utils.synchronized('storage-registry-lock', external=True, lock_path=LOCK_PATH)...
ValueError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/storage_users.py/get_storage_users
3,525
def lookup(self, key): try: return self.__bindings.get(key) except __HOLE__: return None
KeyError
dataset/ETHPy150Open spinnaker/spinnaker/pylib/spinnaker/transform_old_config.py/Processor.lookup
3,526
def update_remaining_keys(self): stack = [('', self.__bindings.map)] while stack: prefix, root = stack.pop() for name, value in root.items(): key = '{prefix}{child}'.format(prefix=prefix, child=name) if isinstance(value, dict): stack.append((key + '.', value)) ...
ValueError
dataset/ETHPy150Open spinnaker/spinnaker/pylib/spinnaker/transform_old_config.py/Processor.update_remaining_keys
3,527
def datetime_factory(**kwargs): second = kwargs.get('second') if second is not None: f, i = math.modf(second) kwargs['second'] = int(i) kwargs['microsecond'] = int(f * 1000000) try: return datetime.datetime(**kwargs) except __HOLE__ as e: raise DateTimeRangeError(...
ValueError
dataset/ETHPy150Open lugensa/scorched/scorched/dates.py/datetime_factory
3,528
def __lt__(self, other): try: other = other._dt_obj except __HOLE__: pass return self._dt_obj < other
AttributeError
dataset/ETHPy150Open lugensa/scorched/scorched/dates.py/solr_date.__lt__
3,529
def __eq__(self, other): try: other = other._dt_obj except __HOLE__: pass return self._dt_obj == other
AttributeError
dataset/ETHPy150Open lugensa/scorched/scorched/dates.py/solr_date.__eq__
3,530
def _get_plugins(): """ Get list of available host discovery plugin module names """ plugins = [] conf_file = os.path.expanduser('~/.smokercli.yaml') if not os.path.exists(conf_file): conf_file = CONFIG_FILE if not os.path.exists(conf_file): return plugins with open(c...
ImportError
dataset/ETHPy150Open gooddata/smoker/smoker/client/cli.py/_get_plugins
3,531
def _get_plugin_arguments(name): """ Get list of host discovery plugin specific cmdline arguments :param name: plugin module name """ try: plugin = __import__(name, globals(), locals(), ['HostDiscoveryPlugin']) except __HOLE__ as e: lg.error("Can't load module %s: %s" % (name, e...
ImportError
dataset/ETHPy150Open gooddata/smoker/smoker/client/cli.py/_get_plugin_arguments
3,532
def _run_discovery_plugin(name, args): """ Run the host discovery plugin :param name: plugin module name :param args: attribute namespace :return: discovered hosts list """ try: this_plugin = __import__(name, globals(), locals(), ['HostDiscoveryPlugin...
ImportError
dataset/ETHPy150Open gooddata/smoker/smoker/client/cli.py/_run_discovery_plugin
3,533
def release(self, connection): try: self.__active.remove(connection) except __HOLE__: pass if len(self.__passive) < 2: self.__passive.append(connection) else: connection.close()
ValueError
dataset/ETHPy150Open nigelsmall/httpstream/httpstream/http.py/ConnectionPuddle.release
3,534
def submit(method, uri, body, headers): """ Submit one HTTP request. """ for key, value in headers.items(): del headers[key] headers[xstr(key)] = xstr(value) headers["Host"] = xstr(uri.host_port) if uri.user_info: credentials = uri.user_info.encode("UTF-8") value = "B...
ValueError
dataset/ETHPy150Open nigelsmall/httpstream/httpstream/http.py/submit
3,535
@property def reason(self): """ The reason phrase attached to this response. """ if self.__reason: return self.__reason else: try: return responses[self.status_code] except __HOLE__: if self.status_code == 422: ...
KeyError
dataset/ETHPy150Open nigelsmall/httpstream/httpstream/http.py/Response.reason
3,536
@property def content_type(self): """ The type of content as provided by the `Content-Type` header field. """ try: content_type = [ _.strip() for _ in self.__response.getheader("Content-Type").split(";") ] except __HOLE__: ...
AttributeError
dataset/ETHPy150Open nigelsmall/httpstream/httpstream/http.py/Response.content_type
3,537
@property def encoding(self): """ The content character set encoding. """ try: content_type = dict( _.strip().partition("=")[0::2] for _ in self.__response.getheader("Content-Type").split(";") ) except __HOLE__: retu...
AttributeError
dataset/ETHPy150Open nigelsmall/httpstream/httpstream/http.py/Response.encoding
3,538
@property def filename(self): """ The suggested filename from the `Content-Disposition` header field or the final segment of the path name if no such header is available. """ default_filename = self.uri.path.segments[-1] try: content_type = dict( _...
AttributeError
dataset/ETHPy150Open nigelsmall/httpstream/httpstream/http.py/Response.filename
3,539
def chunks(self, chunk_size=None): """ Iterate through the content as chunks of text. Chunk sizes may vary slightly from that specified due to multi-byte characters. If no chunk size is specified, a default of 4096 is used. """ try: if not chunk_size: ...
UnicodeDecodeError
dataset/ETHPy150Open nigelsmall/httpstream/httpstream/http.py/TextResponse.chunks
3,540
@property def __content(self): try: from bs4 import BeautifulSoup except __HOLE__: return super(HTMLResponse, self).content else: return BeautifulSoup(super(HTMLResponse, self).content)
ImportError
dataset/ETHPy150Open nigelsmall/httpstream/httpstream/http.py/HTMLResponse.__content
3,541
def __iter__(self): """ Iterate through the content as individual JSON values. """ try: from jsonstream import JSONStream except __HOLE__: from ..jsonstream import JSONStream return iter(JSONStream(self.chunks()))
ImportError
dataset/ETHPy150Open nigelsmall/httpstream/httpstream/http.py/JSONResponse.__iter__
3,542
def handleNewGraphRequestApply(self, graph): '''Handles a graph submission request and closes the given ticket according to the result of the process. ''' prevTimer = time.time() nodes = self.dispatchTree.registerNewGraph(graph) logging.getLogger('main.dispatcher').info(...
KeyError
dataset/ETHPy150Open mikrosimage/OpenRenderManagement/src/octopus/dispatcher/dispatcher.py/Dispatcher.handleNewGraphRequestApply
3,543
def updateCommandApply(self, dct): ''' Called from a RN with a json desc of a command (ie rendernode info, command info etc). Raise an execption to tell caller to send a HTTP404 response to RN, if not error a HTTP200 will be send instead ''' log = logging.getLogger('main.dispatch...
KeyError
dataset/ETHPy150Open mikrosimage/OpenRenderManagement/src/octopus/dispatcher/dispatcher.py/Dispatcher.updateCommandApply
3,544
def __getattr__(self, name): try: return object.__getattribute__(self, name) except __HOLE__: try: return self.get(name) except: raise AttributeError(name)
AttributeError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/core/configuration.py/ConfigurationObject.__getattr__
3,545
def check_enough_semaphores(): """Check that the system supports enough semaphores to run the test.""" # minimum number of semaphores available according to POSIX nsems_min = 256 try: nsems = os.sysconf("SC_SEM_NSEMS_MAX") except (AttributeError, __HOLE__): # sysconf not available or...
ValueError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_multiprocessing.py/check_enough_semaphores
3,546
def assertReturnsIfImplemented(self, value, func, *args): try: res = func(*args) except __HOLE__: pass else: return self.assertEqual(value, res) # For the sanity of Windows users, rather than crashing or freezing in # multiple ways.
NotImplementedError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_multiprocessing.py/BaseTestCase.assertReturnsIfImplemented
3,547
def get_value(self): try: return self.get_value() except AttributeError: try: return self._Semaphore__value except __HOLE__: try: return self._value except AttributeError: raise NotImplementedError # # Testcases #
AttributeError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_multiprocessing.py/get_value
3,548
def test_cpu_count(self): try: cpus = multiprocessing.cpu_count() except __HOLE__: cpus = 1 self.assertTrue(type(cpus) is int) self.assertTrue(cpus >= 1)
NotImplementedError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_multiprocessing.py/_TestProcess.test_cpu_count
3,549
def test_qsize(self): q = self.Queue() try: self.assertEqual(q.qsize(), 0) except __HOLE__: return q.put(1) self.assertEqual(q.qsize(), 1) q.put(5) self.assertEqual(q.qsize(), 2) q.get() self.assertEqual(q.qsize(), 1) ...
NotImplementedError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_multiprocessing.py/_TestQueue.test_qsize
3,550
def check_invariant(self, cond): # this is only supposed to succeed when there are no sleepers if self.TYPE == 'processes': try: sleepers = (cond._sleeping_count.get_value() - cond._woken_count.get_value()) self.assertEqual(sleepers...
NotImplementedError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_multiprocessing.py/_TestCondition.check_invariant
3,551
def test_notify_all(self): cond = self.Condition() sleeping = self.Semaphore(0) woken = self.Semaphore(0) # start some threads/processes which will timeout for i in range(3): p = self.Process(target=self.f, args=(cond, sleeping, woken, TI...
NotImplementedError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_multiprocessing.py/_TestCondition.test_notify_all
3,552
@classmethod def multipass(cls, barrier, results, n): m = barrier.parties assert m == cls.N for i in range(n): results[0].append(True) assert len(results[1]) == i * m barrier.wait() results[1].append(True) assert len(results[0]) == ...
NotImplementedError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_multiprocessing.py/_TestBarrier.multipass
3,553
@classmethod def _test_abort_f(cls, barrier, results1, results2): try: i = barrier.wait() if i == cls.N//2: raise RuntimeError barrier.wait() results1.append(True) except threading.BrokenBarrierError: results2.append(True) ...
RuntimeError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_multiprocessing.py/_TestBarrier._test_abort_f
3,554
@classmethod def _test_abort_and_reset_f(cls, barrier, barrier2, results1, results2, results3): try: i = barrier.wait() if i == cls.N//2: raise RuntimeError barrier.wait() results1.append(True) except thr...
RuntimeError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_multiprocessing.py/_TestBarrier._test_abort_and_reset_f
3,555
def test_rapid_restart(self): authkey = os.urandom(32) manager = QueueManager( address=(test.support.HOST, 0), authkey=authkey, serializer=SERIALIZER) srvr = manager.get_server() addr = srvr.address # Close the connection.Listener socket which gets opened as a part ...
OSError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_multiprocessing.py/_TestManagerRestart.test_rapid_restart
3,556
@classmethod def _is_fd_assigned(cls, fd): try: os.fstat(fd) except __HOLE__ as e: if e.errno == errno.EBADF: return False raise else: return True
OSError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_multiprocessing.py/_TestConnection._is_fd_assigned
3,557
def setUpModule(): if sys.platform.startswith("linux"): try: lock = multiprocessing.RLock() except __HOLE__: raise unittest.SkipTest("OSError raises on RLock creation, " "see issue 3111!") check_enough_semaphores() util.get_temp_dir...
OSError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_multiprocessing.py/setUpModule
3,558
def add_user_picture(orig_filename, new_prefix, up_dir, image_file): import time import os import tempfile new_filename = "{0}-{1}.jpg".format(new_prefix, time.time()) full_path = os.path.join(up_dir, new_filename) import hashlib skip_seek = False try: image_file.seek(0) ...
AttributeError
dataset/ETHPy150Open sjuxax/raggregate/raggregate/queries/users.py/add_user_picture
3,559
def _parseURL(url): try: url = urinorm.urinorm(url) except __HOLE__: return None proto, netloc, path, params, query, frag = urlparse(url) if not path: # Python <2.4 does not parse URLs with no path properly if not query and '?' in netloc: netloc, query = netlo...
ValueError
dataset/ETHPy150Open openid/python-openid/openid/server/trustroot.py/_parseURL
3,560
def get(self, cmd, args, options): '''Get content blob. Usage: exo [options] content get <model> <id> <file>''' pop = options['pop'] exoconfig = options['config'] ExoException = options['exception'] key = exoconfig.config['vendortoken'] # This should be in the pyonep.provision class. It is not. ...
IOError
dataset/ETHPy150Open exosite/exoline/exoline/plugins/provision.py/Plugin.content.get
3,561
def put(self, cmd, args, options): '''Upload content for a model. Usage: exo [options] content put <model> <id> <file> [--mime=type] [--meta=meta] [--protected=<bool>] Command options: --mime=type Set the mime type of the uploaded data. Will autodetect if omitted --protected=<bool> Set to true to...
IOError
dataset/ETHPy150Open exosite/exoline/exoline/plugins/provision.py/Plugin.content.put
3,562
def add(self, cmd, args, options): '''Add an individual serial number to a model. Usage: exo [options] sn add <model> (--file=<file> | <sn>...)''' pop = options['pop'] exoconfig = options['config'] ExoException = options['exception'] key = exoconfig.config['vendortoken'] if args['--file'] is None: ...
IOError
dataset/ETHPy150Open exosite/exoline/exoline/plugins/provision.py/Plugin.sn.add
3,563
def delete(self, cmd, args, options): '''Delete an individual serial number from a model. Usage: exo [options] sn delete <model> (--file=<file> | <sn>...)''' pop = options['pop'] exoconfig = options['config'] ExoException = options['exception'] key = exoconfig.config['vendortoken'] if args['--fi...
IOError
dataset/ETHPy150Open exosite/exoline/exoline/plugins/provision.py/Plugin.sn.delete
3,564
def run(self, cmd, args, options): cik = options['cik'] rpc = options['rpc'] ProvisionException = options['provision-exception'] ExoException = options['exception'] ExoUtilities = options['utils'] exoconfig = options['config'] options['pop'] = options['provision'] err = "This command requires 'vendor' ...
SystemExit
dataset/ETHPy150Open exosite/exoline/exoline/plugins/provision.py/Plugin.run
3,565
def main(self): try: engine, metadata = sql.get_connection(self.args.connection_string) except __HOLE__: raise ImportError('You don\'t appear to have the necessary database backend installed for connection string you\'re trying to use.. Available backends include:\n\nPostgresql:\...
ImportError
dataset/ETHPy150Open wireservice/csvkit/csvkit/utilities/sql2csv.py/SQL2CSV.main
3,566
@cache_control(must_revalidate=True, max_age=3600, private=True) def page_detail(request, slug, template_name='wiki/page_detail.html'): try: page = Page.objects.filter(slug=slug).get() except __HOLE__: page = Page(title=title(slug), slug=slug) if not page.has_read_permission(request.user): ...
ObjectDoesNotExist
dataset/ETHPy150Open kylef-archive/lithium/lithium/wiki/views.py/page_detail
3,567
def page_edit(request, slug): try: page = Page.objects.filter(slug=slug).get() except __HOLE__: page = Page(title=title(slug), slug=slug) if not page.user_can_edit(request.user): if request.user.is_anonymous(): return HttpResponseRedirect('%s?%s=%s' % (settings.LOGIN...
ObjectDoesNotExist
dataset/ETHPy150Open kylef-archive/lithium/lithium/wiki/views.py/page_edit
3,568
def page_history(request, slug, **kwargs): try: page = Page.objects.filter(slug=slug).get() except __HOLE__: raise Http404, "No page found matching the query" if not page.has_read_permission(request.user): if request.user.is_anonymous(): return HttpResponseRedirect('%s?%...
ObjectDoesNotExist
dataset/ETHPy150Open kylef-archive/lithium/lithium/wiki/views.py/page_history
3,569
def revision_detail(request, slug, pk): try: revision = Revision.objects.filter(page__slug=slug, pk=pk).get() except __HOLE__: raise Http404, "No revision found matching the query" if not revision.page.has_read_permission(request.user): if request.user.is_anonymous(): re...
ObjectDoesNotExist
dataset/ETHPy150Open kylef-archive/lithium/lithium/wiki/views.py/revision_detail
3,570
def revision_revert(request, slug, pk): try: revision = Revision.objects.filter(page__slug=slug, pk=pk).get() except __HOLE__: raise Http404, "No revision found matching the query" if not revision.page.user_can_edit(request.user): if request.user.is_anonymous(): retu...
ObjectDoesNotExist
dataset/ETHPy150Open kylef-archive/lithium/lithium/wiki/views.py/revision_revert
3,571
def revision_diff(request, slug): if request.GET.get('a', '').isdigit() and request.GET.get('b', '').isdigit(): a = int(request.GET.get('a')) b = int(request.GET.get('b')) else: return HttpResponseBadRequest(u'You must select two revisions.') try: page = Page.objects.filter(...
ObjectDoesNotExist
dataset/ETHPy150Open kylef-archive/lithium/lithium/wiki/views.py/revision_diff
3,572
def testFindEntries(self): """ Given a list of users and a starting point, entries should generate a list of all entries for each user from that time until now. """ start = check_entries.Command().find_start() if start.day == 1: start += relativedelta(days=1) ...
StopIteration
dataset/ETHPy150Open caktus/django-timepiece/timepiece/tests/test_management.py/CheckEntries.testFindEntries
3,573
def testCheckEntry(self): """ Given lists of entries from users, check_entry should return all overlapping entries. """ start = check_entries.Command().find_start() all_users = check_entries.Command().find_users() entries = check_entries.Command().find_entries(all...
StopIteration
dataset/ETHPy150Open caktus/django-timepiece/timepiece/tests/test_management.py/CheckEntries.testCheckEntry
3,574
def _get_authz_info(self): try: mtime = os.path.getmtime(self.authz_file) except __HOLE__ as e: if self._authz is not None: self.log.error('Error accessing authz file: %s', exception_to_unicode(e)) self._mtime = mtime = 0...
OSError
dataset/ETHPy150Open edgewall/trac/trac/versioncontrol/svn_authz.py/AuthzSourcePolicy._get_authz_info
3,575
def labeled_neighbor(self, obj, judge, back=False): """Returns the id of the "closest" labeled object to the one provided. Notes: - By "closest", it's mean the distance of the id numbers. - Works both for TextSegment and for IEDocument - If back is True, it's picked t...
ValueError
dataset/ETHPy150Open machinalis/iepy/iepy/data/models.py/Relation.labeled_neighbor
3,576
def get_next_segment_to_label(self, judge): # We'll pick first those Segments having already created questions with empty # answer (label=None). After finishing those, we'll look for # Segments never considered (ie, that doest have any question created). # Finally, those with answers in ...
IndexError
dataset/ETHPy150Open machinalis/iepy/iepy/data/models.py/Relation.get_next_segment_to_label
3,577
def get_commits_by_date(self, d): if str(d) in self.symbol_map: return self.symbol_map[d] else: try: rtn = self.commit_log[str(d)] except __HOLE__: rtn = 'empty' else: if rtn > 9: rtn = 'more' ret...
KeyError
dataset/ETHPy150Open littleq0903/git-calendar/git_calendar/utils.py/GitCalendar.get_commits_by_date
3,578
def fix_call(callable, *args, **kw): """ Call ``callable(*args, **kw)`` fixing any type errors that come out. """ try: val = callable(*args, **kw) except __HOLE__: exc_info = fix_type_error(None, callable, args, kw) reraise(*exc_info) return val
TypeError
dataset/ETHPy150Open galaxyproject/pulsar/pulsar/util/pastescript/loadwsgi.py/fix_call
3,579
def test_class_for_name(self): cls = class_for_name('grizzled.config.Configuration') got_name = '%s.%s' % (cls.__module__, cls.__name__) assert got_name == 'grizzled.config.Configuration' try: class_for_name('grizzled.foo.bar.baz') assert False except Nam...
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/grizzled/grizzled/test/system/Test.py/TestSys.test_class_for_name
3,580
def _session_accessed(self, request): try: return request.session.accessed except __HOLE__: return False
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.3/django/middleware/cache.py/UpdateCacheMiddleware._session_accessed
3,581
def __init__(self, cache_timeout=None, cache_anonymous_only=None, **kwargs): # We need to differentiate between "provided, but using default value", # and "not provided". If the value is provided using a default, then # we fall back to system defaults. If it is not provided at all, # we ...
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.3/django/middleware/cache.py/CacheMiddleware.__init__
3,582
def __getattr__(self, name): try: return self[name] except __HOLE__: raise AttributeError(name)
KeyError
dataset/ETHPy150Open sashka/flask-googleauth/flask_googleauth.py/ObjectDict.__getattr__
3,583
def test_start(self): try: # KeyboardInterrupt will be raised after two iterations self.proxy(reset_master_mock=True).start() except __HOLE__: pass master_calls = self.proxy_start_calls([ mock.call.connection.drain_events(timeout=self.de_period), ...
KeyboardInterrupt
dataset/ETHPy150Open openstack/taskflow/taskflow/tests/unit/worker_based/test_proxy.py/TestProxy.test_start
3,584
def test_start_with_on_wait(self): try: # KeyboardInterrupt will be raised after two iterations self.proxy(reset_master_mock=True, on_wait=self.on_wait_mock).start() except __HOLE__: pass master_calls = self.proxy_start_calls([ ...
KeyboardInterrupt
dataset/ETHPy150Open openstack/taskflow/taskflow/tests/unit/worker_based/test_proxy.py/TestProxy.test_start_with_on_wait
3,585
def test_start_with_on_wait_raises(self): self.on_wait_mock.side_effect = RuntimeError('Woot!') try: # KeyboardInterrupt will be raised after two iterations self.proxy(reset_master_mock=True, on_wait=self.on_wait_mock).start() except __HOLE__: ...
KeyboardInterrupt
dataset/ETHPy150Open openstack/taskflow/taskflow/tests/unit/worker_based/test_proxy.py/TestProxy.test_start_with_on_wait_raises
3,586
def _get_doc_by_id(self, namespace, aliases_dict): try: nid = aliases_dict[namespace][0] kwargs = {namespace:nid, "view":'stats'} doc = self.session.catalog.by_identifier(**kwargs) except (__HOLE__, MendeleyException): doc = None return doc
KeyError
dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/providers/mendeley.py/Mendeley._get_doc_by_id
3,587
def _get_doc_by_title(self, aliases_dict): try: biblio = aliases_dict["biblio"][0] biblio_title = self.remove_punctuation(biblio["title"]).lower() biblio_year = str(biblio["year"]) if biblio_title and biblio_year: doc = self.session.catalog.advance...
KeyError
dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/providers/mendeley.py/Mendeley._get_doc_by_title
3,588
def metrics(self, aliases, provider_url_template=None, # ignore this because multiple url steps cache_enabled=True): metrics_and_drilldown = {} doc = self._get_doc(aliases) if doc: try: drilldown_url = doc.link ...
KeyError
dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/providers/mendeley.py/Mendeley.metrics
3,589
def main(): version = pkg_resources.require("octohatrack")[0].version parser = argparse.ArgumentParser() parser.add_argument("repo_name", help="githubuser/repo") parser.add_argument("-l", "--limit", help="Limit to the last x Issues/Pull Requests", type=int, default=0...
ValueError
dataset/ETHPy150Open LABHR/octohatrack/octohatrack/__init__.py/main
3,590
def render(self, name, value, attrs=None): output = [] if value and getattr(value, "url", None): # defining the size size = '200x200' x, y = [int(x) for x in size.split('x')] try: # defining the filename and the miniature filename ...
IOError
dataset/ETHPy150Open jtuz/django-events-calendar/events/widgets.py/AdminImageWidget.render
3,591
def get_google_access_token(email): # TODO: This should be cacheable try: me = UserSocialAuth.objects.get(uid=email, provider="google-oauth2") return me.extra_data['access_token'] except (UserSocialAuth.DoesNotExist, __HOLE__): raise AccessTokenNotFound
KeyError
dataset/ETHPy150Open coddingtonbear/django-mailbox/django_mailbox/google_utils.py/get_google_access_token
3,592
def update_google_extra_data(email, extra_data): try: me = UserSocialAuth.objects.get(uid=email, provider="google-oauth2") me.extra_data = extra_data me.save() except (UserSocialAuth.DoesNotExist, __HOLE__): raise AccessTokenNotFound
KeyError
dataset/ETHPy150Open coddingtonbear/django-mailbox/django_mailbox/google_utils.py/update_google_extra_data
3,593
def get_google_refresh_token(email): try: me = UserSocialAuth.objects.get(uid=email, provider="google-oauth2") return me.extra_data['refresh_token'] except (UserSocialAuth.DoesNotExist, __HOLE__): raise RefreshTokenNotFound
KeyError
dataset/ETHPy150Open coddingtonbear/django-mailbox/django_mailbox/google_utils.py/get_google_refresh_token
3,594
def google_api_get(email, url): headers = dict( Authorization="Bearer %s" % get_google_access_token(email), ) r = requests.get(url, headers=headers) logger.info("I got a %s", r.status_code) if r.status_code == 401: # Go use the refresh token refresh_authorization(email) ...
ValueError
dataset/ETHPy150Open coddingtonbear/django-mailbox/django_mailbox/google_utils.py/google_api_get
3,595
def google_api_post(email, url, post_data, authorized=True): # TODO: Make this a lot less ugly. especially the 401 handling headers = dict() if authorized is True: headers.update(dict( Authorization="Bearer %s" % get_google_access_token(email), )) r = requests.post(url, heade...
ValueError
dataset/ETHPy150Open coddingtonbear/django-mailbox/django_mailbox/google_utils.py/google_api_post
3,596
def NormalizeAndTypeCheck(arg, types): """Normalizes and type checks the given argument. Args: arg: an instance, tuple, list, iterator, or generator of the given type(s) types: allowed type or tuple of types Returns: A (list, bool) tuple. The list is a normalized, shallow copy of the argument. T...
TypeError
dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/api/datastore.py/NormalizeAndTypeCheck
3,597
@staticmethod def _FromPb(pb, require_valid_key=True): """Static factory method. Returns the Entity representation of the given protocol buffer (datastore_pb.Entity). Not intended to be used by application developers. The Entity PB's key must be complete. If it isn't, an AssertionError is raised....
ValueError
dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/api/datastore.py/Entity._FromPb
3,598
def GetCompiledQuery(self): try: return self.__compiled_query except __HOLE__: raise AssertionError('No cursor available, either this query has not ' 'been executed or there is no compilation ' 'available for this kind of query')
AttributeError
dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/api/datastore.py/Query.GetCompiledQuery
3,599
def _CheckFilter(self, filter, values): """Type check a filter string and list of values. Raises BadFilterError if the filter string is empty, not a string, or invalid. Raises BadValueError if the value type is not supported. Args: filter: String containing the filter text. values: List of...
TypeError
dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/api/datastore.py/Query._CheckFilter