Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
3,400
def import_app_sitetree_module(app): """Imports sitetree module from a given app.""" module_name = settings.APP_MODULE_NAME module = import_module(app) try: sub_module = import_module('%s.%s' % (app, module_name)) return sub_module except __HOLE__: if module_has_submodule(mod...
ImportError
dataset/ETHPy150Open idlesign/django-sitetree/sitetree/utils.py/import_app_sitetree_module
3,401
def get_app_n_model(settings_entry_name): """Returns tuple with application and tree[item] model class names.""" try: app_name, model_name = getattr(settings, settings_entry_name).split('.') except __HOLE__: raise ImproperlyConfigured('`SITETREE_%s` must have the following format: `app_name....
ValueError
dataset/ETHPy150Open idlesign/django-sitetree/sitetree/utils.py/get_app_n_model
3,402
def get_model_class(settings_entry_name): """Returns a certain sitetree model as defined in the project settings.""" app_name, model_name = get_app_n_model(settings_entry_name) if apps_get_model is None: model = get_model(app_name, model_name) else: try: model = apps_get_mode...
ValueError
dataset/ETHPy150Open idlesign/django-sitetree/sitetree/utils.py/get_model_class
3,403
def _call(self, name, *args): # In the future (once we don't pass any weird arg, such as SessionId and so on), use JSON # First, serialize the data provided in the client side try: request_data = pickle.dumps(args) except: _, exc_instance, _ = sys.exc_info() ...
TypeError
dataset/ETHPy150Open weblabdeusto/weblabdeusto/server/src/voodoo/gen/clients.py/HttpClient._call
3,404
def _raise_for_status(response): status = response.status_code if 400 <= response.status_code < 500: try: body = response.json() response.reason = body['errorMessage'] return response.raise_for_status() except (__HOLE__, ValueError): pass ...
KeyError
dataset/ETHPy150Open MarSoft/PebbleNotes/gae/pypebbleapi.repo/pypebbleapi/timeline.py/_raise_for_status
3,405
def create_folders(folders): for folder in folders: try: new_folder = os.path.join(current_dir, 'devel', folder) print "Creating %s" % new_folder os.makedirs(new_folder) except __HOLE__: continue
OSError
dataset/ETHPy150Open comodit/synapse-agent/develop.py/create_folders
3,406
def get_message(self): data = self.message if st_version == 3: return HTMLParser().unescape(data) else: try: data = data.decode('utf-8') except __HOLE__: data = data.decode(sublime.active_window().active_view().settings().get('...
UnicodeDecodeError
dataset/ETHPy150Open benmatselby/sublime-phpcs/phpcs.py/CheckstyleError.get_message
3,407
@staticmethod def import_json(): """Import a module for JSON""" try: import json except __HOLE__: import simplejson as json else: return json
ImportError
dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-extensions/build/lib/django_extensions/management/commands/print_settings.py/Command.import_json
3,408
def load_file(self, filename): try: with io.open(filename, 'r', encoding=config.get('encoding')) as f: return f.read() except __HOLE__ as e: raise I18nFileLoadError("error loading file {0}: {1}".format(filename, e.strerror))
IOError
dataset/ETHPy150Open tuvistavie/python-i18n/i18n/loaders/loader.py/Loader.load_file
3,409
def test_validation(self): obj = ValidatingDocument() try: obj.full_clean() except ValidationError as error: self.assertFalse('allow_null' in error.message_dict) else: self.fail('Validation is broken') obj.with_choices = 'c' ob...
ValidationError
dataset/ETHPy150Open zbyte64/django-dockit/dockit/tests/schema/schema_tests.py/DocumentValidationTestChase.test_validation
3,410
def get(self, name=None, arg=None): """Handle GET.""" if name == 'summary': summary = summary_module.GetComputerSummary() models.ReportsCache.SetStatsSummary(summary) elif name == 'installcounts': _GenerateInstallCounts() elif name == 'trendinginstalls': if arg: try: ...
ValueError
dataset/ETHPy150Open google/simian/src/simian/mac/cron/reports_cache.py/ReportsCache.get
3,411
def acquire_next(self): """Return the next waiting request, if any. In-page requests are returned first. """ try: request = self._wait_inpage_queue.popleft() except __HOLE__: try: request = self._wait_queue.popleft() except In...
IndexError
dataset/ETHPy150Open brandicted/scrapy-webdriver/scrapy_webdriver/manager.py/WebdriverManager.acquire_next
3,412
def using_git(cwd): """Test whether the directory cwd is contained in a git repository.""" try: git_log = shell_out(["git", "log"], cwd=cwd) return True except (CalledProcessError, __HOLE__): # pragma: no cover return False
OSError
dataset/ETHPy150Open hayd/pep8radius/pep8radius/vcs.py/using_git
3,413
def using_hg(cwd): """Test whether the directory cwd is contained in a mercurial repository.""" try: hg_log = shell_out(["hg", "log"], cwd=cwd) return True except (CalledProcessError, __HOLE__): return False
OSError
dataset/ETHPy150Open hayd/pep8radius/pep8radius/vcs.py/using_hg
3,414
def using_bzr(cwd): """Test whether the directory cwd is contained in a bazaar repository.""" try: bzr_log = shell_out(["bzr", "log"], cwd=cwd) return True except (CalledProcessError, __HOLE__): return False
OSError
dataset/ETHPy150Open hayd/pep8radius/pep8radius/vcs.py/using_bzr
3,415
@staticmethod def from_string(vc): """Return the VersionControl superclass from a string, for example VersionControl.from_string('git') will return Git.""" try: # Note: this means all version controls must have # a title naming convention (!) vc = globals(...
AssertionError
dataset/ETHPy150Open hayd/pep8radius/pep8radius/vcs.py/VersionControl.from_string
3,416
def form(self): fields = OrderedDict(( ('required_css_class', 'required'), ('error_css_class', 'error'), )) for field in self.fields.all(): field.add_formfield(fields, self) validators = [] cfg = dict(self.CONFIG_OPTIONS) for key, con...
KeyError
dataset/ETHPy150Open feincms/form_designer/form_designer/models.py/Form.form
3,417
def process(self, form, request): ret = {} cfg = dict(self.CONFIG_OPTIONS) for key, config in self.config.items(): try: process = cfg[key]['process'] except __HOLE__: # ignore configs without process methods continue ...
KeyError
dataset/ETHPy150Open feincms/form_designer/form_designer/models.py/Form.process
3,418
def main(): """ %prog [-c] filename username %prog -b[c] filename username password %prog -D filename username """ # For now, we only care about the use cases that affect tests/functional.py parser = optparse.OptionParser(usage=main.__doc__) parser.add_option('-b', action='st...
IOError
dataset/ETHPy150Open edgewall/trac/contrib/htpasswd.py/main
3,419
def install(show = False, force = False): git_exec_path = subprocess.Popen(["git", "--exec-path"], stdout = subprocess.PIPE).communicate()[0].strip() installed_link_path = os.path.join(git_exec_path, 'git-sap') if show: print(os.path.realpath(installed_link_path)) retur...
OSError
dataset/ETHPy150Open jsirois/sapling/sapling.py/install
3,420
def main(): (options, args, ferror) = parse_args() if options.subcommand is "install": if len(args) != 0: ferror("list takes no arguments") install(options.show, options.force) return # Fail fast if we're not in a repo repo = open_repo(options.native) if options.debug: print("repo\t[%...
KeyError
dataset/ETHPy150Open jsirois/sapling/sapling.py/main
3,421
def __eq__(self, other): try: other = Point(other).value except __HOLE__: pass return self.value.__eq__(other)
ValueError
dataset/ETHPy150Open jerith/depixel/depixel/bspline.py/Point.__eq__
3,422
def _source(b, r, dirname, old_cwd): tmpname = os.path.join(os.getcwd(), dirname[1:].replace('/', '-')) exclude = [] pattern_pip = re.compile(r'\.egg-info/installed-files.txt$') pattern_egg = re.compile(r'\.egg(?:-info)?(?:/|$)') pattern_pth = re.compile( r'lib/python[^/]+/(?:dist|site)-pa...
OSError
dataset/ETHPy150Open devstructure/blueprint/blueprint/backend/sources.py/_source
3,423
def sources(b, r): logging.info('searching for software built from source') for pathname, negate in r['source']: if negate and os.path.isdir(pathname) \ and not r.ignore_source(pathname): # Note before creating a working directory within pathname what # it's atime and mt...
OSError
dataset/ETHPy150Open devstructure/blueprint/blueprint/backend/sources.py/sources
3,424
def generate_qitest_json(self): """ The qitest.cmake is written from CMake """ qitest_cmake_path = os.path.join(self.build_directory, "qitest.cmake") tests = list() if os.path.exists(qitest_cmake_path): with open(qitest_cmake_path, "r") as fp: lines = fp.readl...
SystemExit
dataset/ETHPy150Open aldebaran/qibuild/python/qibuild/project.py/BuildProject.generate_qitest_json
3,425
def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None): """Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar* filename is the timezone tarball from ftp.iana.org/tz. """ tmpdir = tempfile.mkdtemp() zonedir = os.path.join(tmpdir, "zoneinfo") moduledir = os....
OSError
dataset/ETHPy150Open SickRage/SickRage/lib/dateutil/zoneinfo/rebuild.py/rebuild
3,426
def set_key(target, key, value=None): ctx = get_context() # clearing key if value is None: try: del target.metadata[key] target.user_set_metadata.remove(key) except (KeyError, __HOLE__): pass # setting key else: target.metadata[key] = val...
ValueError
dataset/ETHPy150Open mammon-ircd/mammon/mammon/core/ircv3/metadata.py/set_key
3,427
def testLock(): LOOPS = 50 # The import lock may already be held, e.g. if the test suite is run # via "import test.autotest". lock_held_at_start = imp.lock_held() verify_lock_state(lock_held_at_start) for i in range(LOOPS): imp.acquire_lock() verify_lock_state(True) for i ...
RuntimeError
dataset/ETHPy150Open babble/babble/include/jython/Lib/test/test_imp.py/testLock
3,428
def _have_module(module_name): try: import_module(module_name) return True except __HOLE__: return False
ImportError
dataset/ETHPy150Open pydata/pandas/pandas/io/tests/test_html.py/_have_module
3,429
@network def test_invalid_url(self): try: with tm.assertRaises(URLError): self.read_html('http://www.a23950sdfa908sd.com', match='.*Water.*') except __HOLE__ as e: tm.assert_equal(str(e), 'No tables found')
ValueError
dataset/ETHPy150Open pydata/pandas/pandas/io/tests/test_html.py/TestReadHtml.test_invalid_url
3,430
@slow def test_banklist_header(self): from pandas.io.html import _remove_whitespace def try_remove_ws(x): try: return _remove_whitespace(x) except __HOLE__: return x df = self.read_html(self.banklist_data, 'Metcalf', ...
AttributeError
dataset/ETHPy150Open pydata/pandas/pandas/io/tests/test_html.py/TestReadHtml.test_banklist_header
3,431
def GetAPIScope(api_name): """Retrieves the scope for the given API name. Args: api_name: A string identifying the name of the API we want to retrieve a scope for. Returns: A string that is the scope for the given API name. Raises: GoogleAdsValueError: If the given api_name is invalid; ac...
KeyError
dataset/ETHPy150Open googleads/googleads-python-lib/googleads/oauth2.py/GetAPIScope
3,432
def __init__(self, scope, client_email, key_file, private_key_password='notasecret', sub=None, proxy_info=None, disable_ssl_certificate_validation=False, ca_certs=None): """Initializes a GoogleServiceAccountClient. Args: scope: The scope of the API you're authorizing for. ...
IOError
dataset/ETHPy150Open googleads/googleads-python-lib/googleads/oauth2.py/GoogleServiceAccountClient.__init__
3,433
def open(self): ''' Build the base query object for this wrapper, then add all of the counters required for the query. Raise a QueryError if we can't complete the functions. If we are already open, then do nothing. ''' if not self.active: # to prevent having multiple open queries # curpaths are made ac...
NameError
dataset/ETHPy150Open eBay/restcommander/play-1.2.4/python/Lib/site-packages/win32/lib/win32pdhquery.py/BaseQuery.open
3,434
def close(self): ''' Makes certain that the underlying query object has been closed, and that all counters have been removed from it. This is important for reference counting. You should only need to call close if you have previously called open. The collectdata methods all can handle opening and closin...
AttributeError
dataset/ETHPy150Open eBay/restcommander/play-1.2.4/python/Lib/site-packages/win32/lib/win32pdhquery.py/BaseQuery.close
3,435
def getinstpaths(self,object,counter,machine=None,objtype='Process',format = win32pdh.PDH_FMT_LONG): ''' ### Not an end-user function Calculate the paths for an instance object. Should alter to allow processing for lists of object-counter pairs. ''' items, instances = win32pdh.EnumObjectItems(None,None,objt...
ValueError
dataset/ETHPy150Open eBay/restcommander/play-1.2.4/python/Lib/site-packages/win32/lib/win32pdhquery.py/Query.getinstpaths
3,436
@click.command() @click.argument('message_file_path') def commit_msg(message_file_path): """ This hook is invoked by git commit, and can be bypassed with --no-verify option. It takes a single parameter, the name of the file that holds the proposed commit log message. Exiting with non-zero status causes ...
ValueError
dataset/ETHPy150Open zalando/turnstile/turnstile/commit_msg.py/commit_msg
3,437
def __getitem__(self, key): try: return dict.__getitem__(self, key) except __HOLE__: return self.default
KeyError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descrtut.py/defaultdict.__getitem__
3,438
def __getitem__(self, key): try: return dict.__getitem__(self, key) except __HOLE__: return self.default
KeyError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_descrtut.py/defaultdict2.__getitem__
3,439
def convert_data(_data): map = { DBAnnotation.vtType: Annotation, DBAbstraction.vtType: Abstraction, DBConnection.vtType: Connection, DBLocation.vtType: Location, DBModule.vtType: Module, DBFunction.vtType: ModuleFunction, DBGroup.vtType: Group, DBPara...
KeyError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/core/vistrail/operation.py/convert_data
3,440
def choices_from_params(self): out = [] for p in self.params.getlist(self.query_param): try: choice = self.choice_from_param(p) out.append(choice) except __HOLE__: pass for p in self.params.getlist(self.query_param + '--isnu...
ValueError
dataset/ETHPy150Open ionelmc/django-easyfilters/src/django_easyfilters/filters.py/Filter.choices_from_params
3,441
def choice_from_param(self, param): """ Returns a native Python object representing something that has been chosen for a filter, converted from the string value in param. """ try: return self.field_obj.to_python(param) except __HOLE__: raise ValueE...
ValidationError
dataset/ETHPy150Open ionelmc/django-easyfilters/src/django_easyfilters/filters.py/Filter.choice_from_param
3,442
def choice_from_param(self, param): try: return self.rel_field.to_python(param) except __HOLE__: raise ValueError()
ValidationError
dataset/ETHPy150Open ionelmc/django-easyfilters/src/django_easyfilters/filters.py/RelatedObjectMixin.choice_from_param
3,443
def make_numeric_range_choice(to_python, to_str): """ Returns a Choice class that represents a numeric choice range, using the passed in 'to_python' and 'to_str' callables to do conversion to/from native data types. """ @python_2_unicode_compatible @total_ordering class NumericRangeChoic...
ValidationError
dataset/ETHPy150Open ionelmc/django-easyfilters/src/django_easyfilters/filters.py/make_numeric_range_choice
3,444
def decompose_field(field): from api.base.serializers import ( HideIfRetraction, HideIfRegistration, HideIfDisabled, AllowMissing ) WRAPPER_FIELDS = (HideIfRetraction, HideIfRegistration, HideIfDisabled, AllowMissing) while isinstance(field, WRAPPER_FIELDS): try: fie...
AttributeError
dataset/ETHPy150Open CenterForOpenScience/osf.io/api/base/utils.py/decompose_field
3,445
def add_node(self, node): if not isinstance(node, Node): try: node = Node.registry[node] except __HOLE__: logger.error("Unable to find Node '%s' in registry.", node) logger.debug("Adding node '%s' to monitoring group '%s'.", node.name, ...
KeyError
dataset/ETHPy150Open cloudtools/nymms/nymms/resources.py/MonitoringGroup.add_node
3,446
def add_monitor(self, monitor): if not isinstance(monitor, Monitor): try: monitor = Monitor.registry[monitor] except __HOLE__: logger.error("Unable to find Monitor '%s' in registry.", monitor) logger.debug("Adding monit...
KeyError
dataset/ETHPy150Open cloudtools/nymms/nymms/resources.py/MonitoringGroup.add_monitor
3,447
def __init__(self, name, realm=None, address=None, node_monitor=None, monitoring_groups=None, **kwargs): self.name = name self.realm = realm self.address = address or name self.node_monitor = node_monitor self.monitoring_groups = WeakValueDictionary() sel...
KeyError
dataset/ETHPy150Open cloudtools/nymms/nymms/resources.py/Node.__init__
3,448
def __init__(self, name, command, realm=None, monitoring_groups=None, **kwargs): self.name = name self.realm = realm if not isinstance(command, Command): try: command = Command.registry[command] except KeyError: logger.erro...
KeyError
dataset/ETHPy150Open cloudtools/nymms/nymms/resources.py/Monitor.__init__
3,449
def __ProcessProperties(self, kind_name, namespace, entity_key_size, prop_lists): for prop_list in prop_lists: for prop in prop_list: try: value = datastore_types.FromPropertyPb(prop) self.__AggregateProperty(kind_name, namespace, entity_key_size, ...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/datastore/datastore_stats_generator.py/DatastoreStatsProcessor.__ProcessProperties
3,450
def do_wan_type(self, line): try: type=eval("LinksysSession.WAN_CONNECT_"+line.strip().upper()) self.session.set_connection_type(type) except __HOLE__: print_stderr("linksys: unknown connection type.") return 0
ValueError
dataset/ETHPy150Open cloudaice/simple-data/misc/virtenv/share/doc/pycurl/examples/linksys.py/LinksysInterpreter.do_wan_type
3,451
def next_time(time_string): try: parsed = list(time.strptime(time_string, "%H:%M")) except (TypeError, __HOLE__): return float(time_string) now = time.localtime() current = list(now) current[3:6] = parsed[3:6] current_time = time.time() delta = time.mktime(current) - curre...
ValueError
dataset/ETHPy150Open abusesa/abusehelper/abusehelper/core/mailer.py/next_time
3,452
def _get_cpu_count(): try: return cpu_count() except __HOLE__: raise RuntimeError('Could not determine CPU count and no ' '--instance-count supplied.')
NotImplementedError
dataset/ETHPy150Open mbr/flask-appconfig/flask_appconfig/server_backends.py/_get_cpu_count
3,453
def __init__(self, *args, **kwargs): try: val = args[3] except __HOLE__: val = kwargs['releaselevel'] if val not in ('', 'a', 'alpha', 'b', 'beta'): raise ValueError("Release-level must be one of 'a', 'alpha', 'b' or 'beta' but '{}' given".format(val)) ...
IndexError
dataset/ETHPy150Open Aeronautics/aero/aero/__version__.py/V.__init__
3,454
@resource.register('.*\.json(\.gz)?') def resource_json_ambiguous(path, **kwargs): """ Try to guess if this file is line-delimited or not """ if os.path.exists(path): f = open(path) try: one = next(f) except __HOLE__: # gzip f.close() return resource_...
UnicodeDecodeError
dataset/ETHPy150Open blaze/odo/odo/backends/json.py/resource_json_ambiguous
3,455
@register.tag def gravatar_url(_parser, token): try: _tag_name, email = token.split_contents() except __HOLE__: raise template.TemplateSyntaxError( '{} tag requires a single argument'.format( token.contents.split()[0])) return GravatarUrlNode(email)
ValueError
dataset/ETHPy150Open deis/deis/controller/web/templatetags/gravatar_tags.py/gravatar_url
3,456
def get_request_url(self, request_id): """Returns the URL the request e.g. 'http://localhost:8080/foo?bar=baz'. Args: request_id: The string id of the request making the API call. Returns: The URL of the request as a string. """ try: host = os.environ['HTTP_HOST'] except __HO...
KeyError
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/api/request_info.py/_LocalRequestInfo.get_request_url
3,457
def read_string(self): len = self._read_size() byte_payload = self.trans.read(len) if self.decode_response: try: byte_payload = byte_payload.decode('utf-8') except __HOLE__: pass return byte_payload
UnicodeDecodeError
dataset/ETHPy150Open eleme/thriftpy/thriftpy/protocol/compact.py/TCompactProtocol.read_string
3,458
def read_struct(self, obj): self.read_struct_begin() while True: fname, ftype, fid = self.read_field_begin() if ftype == TType.STOP: break if fid not in obj.thrift_spec: self.skip(ftype) continue try: ...
IndexError
dataset/ETHPy150Open eleme/thriftpy/thriftpy/protocol/compact.py/TCompactProtocol.read_struct
3,459
def _get(self, name, obj): try: attr = getattr(obj, name) except __HOLE__: return if callable(attr): attr = attr(obj) return attr
AttributeError
dataset/ETHPy150Open quantmind/lux/lux/extensions/sitemap/__init__.py/BaseSitemap._get
3,460
def _ball_drain_while_active(self, balls, **kwargs): if balls <= 0: return {'balls': balls} no_balls_in_play = False try: if not self.machine.game.balls_in_play: no_balls_in_play = True except __HOLE__: no_balls_in_play = True ...
AttributeError
dataset/ETHPy150Open missionpinball/mpf/mpf/devices/ball_save.py/BallSave._ball_drain_while_active
3,461
def set_recursion_limit(self): """Set explicit recursion limit if set in the environment. This is set here to make sure we're setting it always when we initialize Django, also when we're loading celery (which is calling django.setup too). This is only being used for the amo-val...
TypeError
dataset/ETHPy150Open mozilla/addons-server/src/olympia/core/apps.py/CoreConfig.set_recursion_limit
3,462
def _runlevel(): ''' Return the current runlevel ''' if 'upstart._runlevel' in __context__: return __context__['upstart._runlevel'] out = __salt__['cmd.run'](['runlevel', '{0}'.format(_find_utmp())], python_shell=False) try: ret = out.split()[1] except __HOLE__: # The...
IndexError
dataset/ETHPy150Open saltstack/salt/salt/modules/upstart.py/_runlevel
3,463
def getInternalQueue(self, thread_id): """ returns intenal command queue for a given thread. if new queue is created, notify the RDB about it """ try: return self.cmdQueue[thread_id] except __HOLE__: self.internalQueueLock.acquire() try: ...
KeyError
dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/common/diagnostic/pydevDebug/pydevd.py/PyDB.getInternalQueue
3,464
def processNetCommand(self, cmd_id, seq, text): '''Processes a command received from the Java side @param cmd_id: the id of the command @param seq: the sequence of the command @param text: the text received in the command @note: this method is run as a big switc...
AttributeError
dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/common/diagnostic/pydevDebug/pydevd.py/PyDB.processNetCommand
3,465
def trace_dispatch(self, frame, event, arg): ''' This is the callback used when we enter some context in the debugger. We also decorate the thread we are in with info about the debugging. The attributes added are: pydev_state pydev_step_stop pydev_st...
SystemExit
dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/common/diagnostic/pydevDebug/pydevd.py/PyDB.trace_dispatch
3,466
def settrace(host='localhost', stdoutToServer=False, stderrToServer=False, port=5678, suspend=True, trace_only_current_thread=True): '''Sets the tracing function with the pydev debug function and initializes needed facilities. @param host: the user may specify another host, if the debug server is not in th...
AttributeError
dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/common/diagnostic/pydevDebug/pydevd.py/settrace
3,467
def AddTransfer(self, throttle_name, token_count): """Add a count to the amount this thread has transferred. Each time a thread transfers some data, it should call this method to note the amount sent. The counts may be rotated if sufficient time has passed since the last rotation. Args: thro...
KeyError
dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/ext/remote_api/throttle.py/Throttle.AddTransfer
3,468
def add_driver(notification_driver): """Add a notification driver at runtime.""" # Make sure the driver list is initialized. _get_drivers() if isinstance(notification_driver, basestring): # Load and add try: driver = importutils.import_module(notification_driver) ...
ImportError
dataset/ETHPy150Open Havate/havate-openstack/proto-build/gui/horizon/Horizon_GUI/openstack_dashboard/openstack/common/notifier/api.py/add_driver
3,469
def get_processes(self): """Get the processes running on the device. Returns a dictionary (PID, Process).""" processes = {} # Get ps output cmd = ["ps", "-Z"] # Split by newlines and remove first line ("LABEL USER PID PPID NAME") # TODO: surround with try/except?...
ValueError
dataset/ETHPy150Open seandroid-analytics/seal/sealib/device.py/Device.get_processes
3,470
def get_files(self, path="/"): """Get the files under the given path from a connected device. The path must be a directory. Returns a dictionary (filename, File).""" files_dict = {} listing = [] path = os.path.normpath(path) cmd = ["ls", "-lRZ", "'" + path + "'"]...
ValueError
dataset/ETHPy150Open seandroid-analytics/seal/sealib/device.py/Device.get_files
3,471
def get_file(self, path): """Get the file matching the given path from a connected device. The path must be a file. Returns a dictionary (filename, File).""" path = os.path.normpath(path) cmd = ["ls", "-lZ", "'" + path + "'"] listing = subprocess.check_output(self.shell ...
ValueError
dataset/ETHPy150Open seandroid-analytics/seal/sealib/device.py/Device.get_file
3,472
def get_dir(self, path): """Get the directory matching the given path from a connected device. The path must be a directory. This only returns information on the single directory ("ls -ldZ"): to get information about all the directory content recursively, use get_files(path). ...
ValueError
dataset/ETHPy150Open seandroid-analytics/seal/sealib/device.py/Device.get_dir
3,473
def __init__(self, data, table_name=None, default_dialect=None, save_metadata_to=None, metadata_source=None, varying_length_text=False, uniques=False, pk_name=None, force_pk=False, data_size_cushion=0, _parent_table=None, _fk_field_name=None, reorder=F...
TypeError
dataset/ETHPy150Open catherinedevlin/ddl-generator/ddlgenerator/ddlgenerator.py/Table.__init__
3,474
def django_models(self, metadata_source=None): sql = self.sql(dialect='postgresql', inserts=False, creates=True, drops=True, metadata_source=metadata_source) u = sql.split(';\n') try: import django except __HOLE__: print('Cannot find Django on the cur...
ImportError
dataset/ETHPy150Open catherinedevlin/ddl-generator/ddlgenerator/ddlgenerator.py/Table.django_models
3,475
@classmethod def do_request(self, method, url, *args, **kwargs): auth_token = kwargs.get('token', None) params = kwargs.get('params', None) headers = kwargs.get('headers', None) proxy = kwargs.get('proxy', None) if not auth_token: try: config = ConfigParser.ConfigParser() config.read(os.path.exp...
ValueError
dataset/ETHPy150Open yspanchal/docli/docli/commands/base_request.py/DigitalOcean.do_request
3,476
def handle(self, *args, **options): for permission in StoredPermission.objects.all(): try: Permission.get( {'pk': '%s.%s' % (permission.namespace, permission.name)}, proxy_only=True ) except __HOLE__: ...
KeyError
dataset/ETHPy150Open mayan-edms/mayan-edms/mayan/apps/permissions/management/commands/purgepermissions.py/Command.handle
3,477
def __init__(self, n): if n: try: value = int(n) except __HOLE__ as e: raise FilterValidationError(e) now = timezone.now() frm_dt = now - timedelta(seconds=value) super(SecondsFilter, self).__init__(value, start_time__gt...
ValueError
dataset/ETHPy150Open django-silk/silk/silk/request_filters.py/SecondsFilter.__init__
3,478
def _parse(dt, fmt): """attempt to coerce dt into a datetime given fmt, otherwise raise a FilterValidationError""" try: dt = datetime.strptime(dt, fmt) except TypeError: if not isinstance(dt, datetime): raise FilterValidationError('Must be a datetime object') except __HOL...
ValueError
dataset/ETHPy150Open django-silk/silk/silk/request_filters.py/_parse
3,479
def __init__(self, n): try: value = int(n) except __HOLE__ as e: raise FilterValidationError(e) super(NumQueriesFilter, self).__init__(value, num_queries__gte=n)
ValueError
dataset/ETHPy150Open django-silk/silk/silk/request_filters.py/NumQueriesFilter.__init__
3,480
def __init__(self, n): try: value = int(n) except __HOLE__ as e: raise FilterValidationError(e) super(TimeSpentOnQueriesFilter, self).__init__(value, db_time__gte=n)
ValueError
dataset/ETHPy150Open django-silk/silk/silk/request_filters.py/TimeSpentOnQueriesFilter.__init__
3,481
def __init__(self, n): try: value = int(n) except __HOLE__ as e: raise FilterValidationError(e) super(OverallTimeFilter, self).__init__(value, time_taken__gte=n)
ValueError
dataset/ETHPy150Open django-silk/silk/silk/request_filters.py/OverallTimeFilter.__init__
3,482
def setColor(self, color): # Check that the color does not already exist exists = False for c in self._colorHistory: if color == c: exists = True break # If the color does not exist then add it if not exists: self._colorHis...
StopIteration
dataset/ETHPy150Open rwl/muntjac/muntjac/addon/colorpicker/color_picker_history.py/ColorPickerHistory.setColor
3,483
@property def json(self): try: return json.loads(self.value) except (TypeError, __HOLE__): return {}
ValueError
dataset/ETHPy150Open mozilla/addons-server/src/olympia/zadmin/models.py/Config.json
3,484
def save_messages(self, msgs): msg_ids = ['.'.join(msg['id']) for msg in msgs] cache.set('validation.job_id:%s' % self.job_id, msg_ids) for msg, key in zip(msgs, msg_ids): if isinstance(msg['description'], list): des = [] for _m in msg['description']: ...
ValueError
dataset/ETHPy150Open mozilla/addons-server/src/olympia/zadmin/models.py/ValidationJobTally.save_messages
3,485
def run_action(module_name, args=None, forward_args=None): """ Run an action using its module path and a list of arguments If forward_args is given, it must be an argparse.Namespace object. This namespace will be merged with args before being passed to the do() method of module_name. """ i...
ImportError
dataset/ETHPy150Open aldebaran/qibuild/python/qisys/script.py/run_action
3,486
def main_wrapper(module, args): """This wraps the main method of an action so that: * when an exception is raised that derived from ``qisys.error.Error``, simply dispaly the error message and exit * when sys.exit() or ui.fatal() is called, just exit * also handle KeyboardInterrupt * Other ca...
KeyboardInterrupt
dataset/ETHPy150Open aldebaran/qibuild/python/qisys/script.py/main_wrapper
3,487
def action_modules_from_package(package_name): """Returns a suitable list of modules from a package. Example: assuming you have: actions/foo/__init__.py actions/foo/spam.py actions/foo/eggs.py then action_modules_from_package("actions.foo") returns: [actions.foo.spam, actions.f...
ImportError
dataset/ETHPy150Open aldebaran/qibuild/python/qisys/script.py/action_modules_from_package
3,488
def test_parses_dates_with_better_error_message(self): try: parse_date('foo') self.fail('Should have failed to parse') except __HOLE__ as e: self.assertIn('Unable to parse date value: foo', str(e))
ValueError
dataset/ETHPy150Open aws/aws-cli/tests/unit/customizations/cloudtrail/test_validation.py/TestValidation.test_parses_dates_with_better_error_message
3,489
def test_ensures_cloudtrail_arns_are_valid(self): try: assert_cloudtrail_arn_is_valid('foo:bar:baz') self.fail('Should have failed') except __HOLE__ as e: self.assertIn('Invalid trail ARN provided: foo:bar:baz', str(e))
ValueError
dataset/ETHPy150Open aws/aws-cli/tests/unit/customizations/cloudtrail/test_validation.py/TestValidation.test_ensures_cloudtrail_arns_are_valid
3,490
def test_ensures_cloudtrail_arns_are_valid_when_missing_resource(self): try: assert_cloudtrail_arn_is_valid( 'arn:aws:cloudtrail:us-east-1:%s:foo' % TEST_ACCOUNT_ID) self.fail('Should have failed') except __HOLE__ as e: self.assertIn('Invalid trail ARN...
ValueError
dataset/ETHPy150Open aws/aws-cli/tests/unit/customizations/cloudtrail/test_validation.py/TestValidation.test_ensures_cloudtrail_arns_are_valid_when_missing_resource
3,491
def subcheck__get_fake_values(self, cls): res1 = get_fake_values(cls, annotate=False, seed=0) res2 = get_fake_values(cls, annotate=True, seed=0) if hasattr(cls, 'lower'): cls = class_by_name[cls] attrs = cls._necessary_attrs + cls._recommended_attrs attrnames = [at...
ValueError
dataset/ETHPy150Open NeuralEnsemble/python-neo/neo/test/coretest/test_generate_datasets.py/Test__get_fake_values.subcheck__get_fake_values
3,492
def subcheck__generate_datasets(self, cls, cascade, seed=None): self.annotations['seed'] = seed if seed is None: res = fake_neo(obj_type=cls, cascade=cascade) else: res = fake_neo(obj_type=cls, cascade=cascade, seed=seed) if not hasattr(cls, 'lower'): ...
ValueError
dataset/ETHPy150Open NeuralEnsemble/python-neo/neo/test/coretest/test_generate_datasets.py/Test__generate_datasets.subcheck__generate_datasets
3,493
def _get_linked_doctypes(doctype): ret = {} # find fields where this doctype is linked ret.update(get_linked_fields(doctype)) ret.update(get_dynamic_linked_fields(doctype)) # find links of parents links = frappe.db.sql("""select dt from `tabCustom Field` where (fieldtype="Table" and options=%s)""", (doctype)...
ImportError
dataset/ETHPy150Open frappe/frappe/frappe/desk/form/linked_with.py/_get_linked_doctypes
3,494
def Encode(self): try: return self._CEncode() except __HOLE__: e = Encoder() self.Output(e) return e.buffer().tostring()
NotImplementedError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/net/proto/ProtocolBuffer.py/ProtocolMessage.Encode
3,495
def SerializePartialToString(self): try: return self._CEncodePartial() except (NotImplementedError, __HOLE__): e = Encoder() self.OutputPartial(e) return e.buffer().tostring()
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/net/proto/ProtocolBuffer.py/ProtocolMessage.SerializePartialToString
3,496
def MergePartialFromString(self, s): try: self._CMergeFromString(s) except __HOLE__: a = array.array('B') a.fromstring(s) d = Decoder(a, 0, len(a)) self.TryMerge(d)
NotImplementedError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/net/proto/ProtocolBuffer.py/ProtocolMessage.MergePartialFromString
3,497
def _fetch(self, value, arg): try: message = self.spam[self._mailbox][value - 1] message_id = value except __HOLE__: for x, item in enumerate(self.spam[self._mailbox]): if item["uid"] == value: message = item mes...
TypeError
dataset/ETHPy150Open uwdata/termite-data-server/web2py/gluon/contrib/mockimaplib.py/Connection._fetch
3,498
def _get_messages(self, query): if query.strip().isdigit(): return [self.spam[self._mailbox][int(query.strip()) - 1],] elif query[1:-1].strip().isdigit(): return [self.spam[self._mailbox][int(query[1:-1].strip()) -1],] elif query[1:-1].replace("UID", "").strip().isdigit()...
TypeError
dataset/ETHPy150Open uwdata/termite-data-server/web2py/gluon/contrib/mockimaplib.py/Connection._get_messages
3,499
def append(self, mailbox, flags, struct_time, message): """ result, data = self.connection.append(mailbox, flags, struct_time, message) if result == "OK": uid = int(re.findall("\d+", str(data))[-1]) """ last = self.spam[mailbox][-1] try: ...
ValueError
dataset/ETHPy150Open uwdata/termite-data-server/web2py/gluon/contrib/mockimaplib.py/Connection.append