Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
7,700
def query_filter(query): """Translate a query-style string to a 'filter'. Query can be the following formats: Case Insensitive 'value' OR '*= value' Contains 'value*' OR '^= value' Begins with value '*value' OR '$= value' Ends with value '*value*' OR '_= value' Contains val...
ValueError
dataset/ETHPy150Open softlayer/softlayer-python/SoftLayer/utils.py/query_filter
7,701
def resolve_ids(identifier, resolvers): """Resolves IDs given a list of functions. :param string identifier: identifier string :param list resolvers: a list of functions :returns list: """ # Before doing anything, let's see if this is an integer try: return [int(identifier)] ex...
ValueError
dataset/ETHPy150Open softlayer/softlayer-python/SoftLayer/utils.py/resolve_ids
7,702
def convert_resource(self, resource, view): serializer_data = view.get_serializer(instance=None) fields = serializer_data.fields links = {} if "links" in resource: links = resource["links"] del resource["links"] for field_name, field in six.iteritems(f...
AttributeError
dataset/ETHPy150Open kevin-brown/drf-json-api/rest_framework_json_api/parsers.py/JsonApiMixin.convert_resource
7,703
def __del__(self): "Deletes this Geometry." try: capi.destroy_geom(self._ptr) except (AttributeError, __HOLE__): pass # Some part might already have been garbage collected # Pickle routines
TypeError
dataset/ETHPy150Open django/django/django/contrib/gis/gdal/geometries.py/OGRGeometry.__del__
7,704
def parse_body(self): if len(self.body) == 0 and not self.parse_zero_length_body: return self.body try: try: body = ET.XML(self.body) except __HOLE__: # lxml wants a bytes and tests are basically hard-coded to str body ...
ValueError
dataset/ETHPy150Open apache/libcloud/libcloud/test/storage/test_s3.py/S3MockRawResponse.parse_body
7,705
def _remove_test_file(self): file_path = os.path.abspath(__file__) + '.temp' try: os.unlink(file_path) except __HOLE__: pass
OSError
dataset/ETHPy150Open apache/libcloud/libcloud/test/storage/test_s3.py/S3Tests._remove_test_file
7,706
def test_upload_object_invalid_ex_storage_class(self): # Invalid hash is detected on the amazon side and BAD_REQUEST is # returned file_path = os.path.abspath(__file__) container = Container(name='foo_bar_container', extra={}, driver=self.driver) obj...
ValueError
dataset/ETHPy150Open apache/libcloud/libcloud/test/storage/test_s3.py/S3Tests.test_upload_object_invalid_ex_storage_class
7,707
def parse_color(text): '''Parse a string to a kivy color. Supported formats: * rgb(r, g, b) * rgba(r, g, b, a) * rgb * rgba * rrggbb * rrggbbaa For hexadecimal values, you case also use: * #rgb * #rgba * #rrggbb * #rrggbbaa '...
AttributeError
dataset/ETHPy150Open kivy/kivy/kivy/parser.py/parse_color
7,708
def string_to_numeric(string, type=int): try: return type(string) except __HOLE__: return 0
ValueError
dataset/ETHPy150Open dimagi/commcare-hq/custom/m4change/user_calcs/__init__.py/string_to_numeric
7,709
def run(): '''Run the command-line runner.''' args = arg_parser() settings = utils.Settings.read() console.configure(settings) retry_decryption = settings.get("retry_decryption", config.USER_SETTINGS["retry_decryption"]) def try_decrypt(remindme): if not remindme.is_encrypted(): ...
KeyboardInterrupt
dataset/ETHPy150Open GochoMugo/remindme/remindme/cli.py/run
7,710
def init_notebook(): """ Initialize the Jupyter notebook by injecting the necessary CSS and JS into the browser. """ from IPython.display import display, Javascript, HTML # todo: ideally you don't want user interactions done this way: # they result in spamming of JavaScript "objects" a...
IndexError
dataset/ETHPy150Open zoofIO/flexx/flexx/app/funcs.py/init_notebook
7,711
def main(): try: options = make_argument_parser().parse_args() if options.debug: logging.basicConfig() stun.log.setLevel(logging.DEBUG) nat_type, external_ip, external_port = stun.get_ip_info( source_ip=options.source_ip, source_port=options....
KeyboardInterrupt
dataset/ETHPy150Open jtriley/pystun/stun/cli.py/main
7,712
def create_library(self, source_code=None, args=None, wait_time=3, retries=10): """Creates a whizzml library from its source code. The `source_code` parameter can be a: {library ID}: the ID for an existing whizzml library {path}: the path to a file conta...
IOError
dataset/ETHPy150Open bigmlcom/python/bigml/libraryhandler.py/LibraryHandler.create_library
7,713
def setWeightMatrixSparse(self, W): """ Set the weight matrix of this graph. Requires as input a scipy sparse matrix with the same dimensions as the current weight matrix. Edges are represented by non-zero edges. :param W: The weight matrix to use. """ ...
AttributeError
dataset/ETHPy150Open charanpald/APGL/apgl/graph/PySparseGraph.py/PySparseGraph.setWeightMatrixSparse
7,714
@staticmethod def _bytes_to_cursor_pb(cursor): try: cursor_pb = datastore_pb.CompiledCursor(cursor) except (__HOLE__, TypeError), e: raise datastore_errors.BadValueError( 'Invalid cursor (%r). Details: %s' % (cursor, e)) except Exception, e: if e.__class__.__name__ == 'P...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/datastore/datastore_query.py/Cursor._bytes_to_cursor_pb
7,715
@staticmethod def _urlsafe_to_bytes(cursor): if not isinstance(cursor, basestring): raise datastore_errors.BadValueError( 'cursor argument should be str or unicode (%r)' % (cursor,)) try: decoded_bytes = base64.b64decode(str(cursor).replace('-', '+').replace('_', '/')) except (__...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/datastore/datastore_query.py/Cursor._urlsafe_to_bytes
7,716
def process_query_result_if_first(self, query_result): if not self.__was_first_result_processed: self.__was_first_result_processed = True self.__keys_only = query_result.keys_only() if query_result.has_compiled_query(): self.__compiled_query = query_result.compiled_query else: ...
NotImplementedError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/datastore/datastore_query.py/_BatchShared.process_query_result_if_first
7,717
@command("Set up Taskwarrior to sync issues with your Inthe.AM account.") def setup(config, args, *extra, **kwargs): parser = argparse.ArgumentParser() parser.add_argument( '--data-dir', type=os.path.expanduser, default='~/.tasks' ) extra_args = parser.parse_args(extra) twve...
OSError
dataset/ETHPy150Open coddingtonbear/taskwarrior-inthe.am/taskwarrior_inthe_am/commands.py/setup
7,718
def get_for_model(self, model): """ Returns the ContentType object for a given model, creating the ContentType if necessary. Lookups are cached so that subsequent lookups for the same model don't hit the database. """ opts = model._meta key = (opts.app_label, opts...
KeyError
dataset/ETHPy150Open dcramer/django-compositepks/django/contrib/contenttypes/models.py/ContentTypeManager.get_for_model
7,719
def get_for_id(self, id): """ Lookup a ContentType by ID. Uses the same shared cache as get_for_model (though ContentTypes are obviously not created on-the-fly by get_by_id). """ try: ct = self.__class__._cache[id] except __HOLE__: # This could rai...
KeyError
dataset/ETHPy150Open dcramer/django-compositepks/django/contrib/contenttypes/models.py/ContentTypeManager.get_for_id
7,720
def __init__(self, **options): """ See the class docstring for explanation of options. """ if not pil_available: raise PilNotAvailable( 'Python Imaging Library is required for this formatter') Formatter.__init__(self, **options) # Read the styl...
ValueError
dataset/ETHPy150Open adieu/allbuttonspressed/pygments/formatters/img.py/ImageFormatter.__init__
7,721
def get_shell_dialog(): global _shell_dialog if _shell_dialog is not None: return _shell_dialog try: deps = {'pip': 'ipython>=1.0', 'linux-ubuntu': 'ipython-qtconsole', 'linux-debian': 'ipython-qtconsole'} IPython = py_import('IPython.qt.console.ric...
ImportError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/gui/shell.py/get_shell_dialog
7,722
def assertDestinationAdded(self, programPath): """ Assert that when running under the given program a new destination is added by L{redirectLogsForTrial}. @param programPath: A path to a program. @type programPath: L{str} """ destination = _RedirectLogsForTrial(F...
ValueError
dataset/ETHPy150Open ClusterHQ/eliot/eliot/tests/test_twisted.py/RedirectLogsForTrialTests.assertDestinationAdded
7,723
@cherrypy.expose def repost_fragment(self, **kwargs): response = self.rp.parse_authentication_response(cherrypy.session, kwargs["url_fragment"]) html_page = self._load_HTML_page_from_file("htdocs/success_page.html") # Support for hyb...
KeyError
dataset/ETHPy150Open rohe/pyoidc/oidc_example/simple_rp/src/rp.py/RPServer.repost_fragment
7,724
@port.setter def port(self, port): """ Sets the port that WebDriver will be running on """ if not isinstance(port, int): raise WebDriverException("Port needs to be an integer") try: port = int(port) if port < 1 or port > 65535: ...
ValueError
dataset/ETHPy150Open apiad/sublime-browser-integration/selenium/webdriver/firefox/firefox_profile.py/FirefoxProfile.port
7,725
def escape(m): all, tail = m.group(0, 1) assert all.startswith("\\") esc = simple_escapes.get(tail) if esc is not None: return esc if tail.startswith("x"): hexes = tail[1:] if len(hexes) < 2: raise ValueError("invalid hex string escape ('\\%s')" % tail) tr...
ValueError
dataset/ETHPy150Open JT5D/Alfred-Popclip-Sublime/Sublime Text 2/Python PEP8 Autoformat/libs/lib2to3/pgen2/literals.py/escape
7,726
def quantity(): # <1> try: quantity.counter += 1 # <2> except __HOLE__: quantity.counter = 0 # <3> storage_name = '_{}:{}'.format('quantity', quantity.counter) # <4> def qty_getter(instance): # <5> return getattr(instance, storage_name) def qty_setter(instance, value)...
AttributeError
dataset/ETHPy150Open fluentpython/example-code/20-descriptor/bulkfood/bulkfood_v4prop.py/quantity
7,727
def render(self, name, value, attrs=None): if not isinstance(value, list): value = self.decompress(value) if self.is_localized: for widget in self.widgets: widget.is_localized = self.is_localized output = [] final_attrs = self.build_attrs(attrs) ...
IndexError
dataset/ETHPy150Open MongoEngine/django-mongoengine/django_mongoengine/forms/widgets.py/Dictionary.render
7,728
def __init__(self, sub_attrs, key_value=None, attrs=None, **kwargs): widgets = [self.key_type()] if callable(self.key_type) else [] if self.value_type in [TextInput, HiddenInput]: if sub_attrs: try: widgets = [self.key_type(attrs=sub_attrs['key']), self.va...
KeyError
dataset/ETHPy150Open MongoEngine/django-mongoengine/django_mongoengine/forms/widgets.py/Pair.__init__
7,729
def render(self, name, value, attrs=None): if self.is_localized: for widget in self.widgets: widget.is_localized = self.is_localized if not isinstance(value, list): value = self.decompress(value) output = [] final_attrs = self.build_attrs(attrs) ...
IndexError
dataset/ETHPy150Open MongoEngine/django-mongoengine/django_mongoengine/forms/widgets.py/Pair.render
7,730
def set_cdata_mode(self, tag): try: self.interesting = _html_parser.interesting_cdata except __HOLE__: self.interesting = re.compile(r'</\s*%s\s*>' % tag.lower(), re.I) self.cdata_tag = tag.lower()
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/utils/html_parser.py/HTMLParser.set_cdata_mode
7,731
@content def POST(self): data = self.checked_data() try: if 'passwordCredentials' in data['auth']: if not validate_password_credentials( **data['auth']['passwordCredentials']): raise self.http(401) elif 'token' in da...
TypeError
dataset/ETHPy150Open openstack/fuel-web/nailgun/nailgun/fake_keystone/handlers.py/TokensHandler.POST
7,732
def __getattr__(self, name): try: return self[name] except __HOLE__: raise AttributeError(name)
KeyError
dataset/ETHPy150Open D-L/SimpleBookMarks/src/tornado/util.py/ObjectDict.__getattr__
7,733
def import_object(name): """Imports an object by name. import_object('x') is equivalent to 'import x'. import_object('x.y.z') is equivalent to 'from x.y import z'. >>> import tornado.escape >>> import_object('tornado.escape') is tornado.escape True >>> import_object('tornado.escape.utf8') ...
AttributeError
dataset/ETHPy150Open D-L/SimpleBookMarks/src/tornado/util.py/import_object
7,734
def __init__(self, func, name): self.name = name try: self.arg_pos = inspect.getargspec(func).args.index(self.name) except __HOLE__: # Not a positional parameter self.arg_pos = None
ValueError
dataset/ETHPy150Open D-L/SimpleBookMarks/src/tornado/util.py/ArgReplacer.__init__
7,735
def run_detail(request, run_id): test_run = get_object_or_404(TestRun, id=run_id) sort = request.GET.get('sort') if sort == 'response_time': order_by = '-timer_total' elif sort == 'sql_queries': order_by = '-sql_num_queries' elif sort == 'sql_time': order_by = '-sql...
ValueError
dataset/ETHPy150Open lincolnloop/django-debug-logging/debug_logging/views.py/run_detail
7,736
def _status_query(query, hostname, enumerate=None, service=None): ''' Send query along to Nagios. ''' config = _config() data = None params = { 'hostname': hostname, 'query': query, } ret = { 'result': False } if enumerate: params['formatoptions...
ValueError
dataset/ETHPy150Open saltstack/salt/salt/modules/nagios_rpc.py/_status_query
7,737
def get_queryset(self, extra_filters=None): try: return self.instance._prefetched_objects_cache[self.prefetch_cache_name] except (__HOLE__, KeyError): kwargs = extra_filters if extra_filters else {} return self.through.tags_for(self.model, self.instance, **kwargs)
AttributeError
dataset/ETHPy150Open alex/django-taggit/taggit/managers.py/_TaggableManager.get_queryset
7,738
def parse_yaml(yaml_file): """ Parses a yaml file, returning its contents as a dict. """ try: import yaml except ImportError: sys.exit("Unable to import yaml module.") try: with io.open(yaml_file, encoding='utf-8') as fname: return yaml.load(fname) excep...
IOError
dataset/ETHPy150Open ktbyers/netmiko/tests/test_utils.py/parse_yaml
7,739
def mk_test_name(name, value, index=0): """ Generate a new name for a test case. It will take the original test name and append an ordinal index and a string representation of the value, and convert the result into a valid python identifier by replacing extraneous characters with ``_``. If has...
NameError
dataset/ETHPy150Open numba/numba/numba/testing/ddt.py/mk_test_name
7,740
def feed_data(func, new_name, *args, **kwargs): """ This internal method decorator feeds the test data item to the test. """ @wraps(func) def wrapper(self): return func(self, *args, **kwargs) wrapper.__name__ = new_name # Try to call format on the docstring if func.__doc__: ...
IndexError
dataset/ETHPy150Open numba/numba/numba/testing/ddt.py/feed_data
7,741
def configure(config): """When using Lino's default method, the :setting:`LOGGING` setting in your :xfile:`settings.py` must be a dictionary containing the parameters you want to set. Available parameters are: :param logfile: the full path of the lino `system.log` file. If absent or `None`, ther...
IOError
dataset/ETHPy150Open lsaffre/lino/lino/utils/log.py/configure
7,742
def test_emit(self): self.log.set_level(Level.DEBUG) for l in Level.iterconstants(): _lname = l.name.lower() try: getattr(self.log, _lname)("Message", _satraceback=False) except __HOLE__: self.assertEqual(l, Level.FATAL) ...
SystemExit
dataset/ETHPy150Open smartanthill/smartanthill1_0/smartanthill/test/test_log.py/LogCase.test_emit
7,743
def _resolve_urlspec(self, site_name, url_spec): if isinstance(url_spec, (list, tuple)): url_spec = dict(zip(['pattern', 'handler', 'kwargs', 'name'], url_spec)) if not 'pattern' in url_spec or not 'handler' in url_spec: msg = 'Missing attributes in handler configuration in site...
AttributeError
dataset/ETHPy150Open foundit/Piped/contrib/cyclone/piped_cyclone/providers.py/CycloneProvider._resolve_urlspec
7,744
@query def __contains__(self, member): """:keyword:`in` operator. Tests whether the set contains the given operand ``member``. :param member: the value to test :returns: ``True`` if the sorted set contains the given operand ``member`` :rtype: :class:`bool`...
TypeError
dataset/ETHPy150Open dahlia/sider/sider/sortedset.py/SortedSet.__contains__
7,745
@query def __eq__(self, operand): if not isinstance(operand, collections.Sized): return False length = len(self) if length != len(operand): return False zrange = self.session.client.zrange operand_is_sortedset = isinstance(operand, SortedSet) i...
KeyError
dataset/ETHPy150Open dahlia/sider/sider/sortedset.py/SortedSet.__eq__
7,746
def StartInstance(self, instance, block_devices, startup_paused): """Start an instance. For the chroot manager, we try to mount the block device and execute '/ganeti-chroot start'. """ root_dir = self._InstanceDir(instance.name) if not os.path.exists(root_dir): try: os.mkdir(root...
IOError
dataset/ETHPy150Open ganeti/ganeti/lib/hypervisor/hv_chroot.py/ChrootManager.StartInstance
7,747
def facebook_callback(fun_or_app, route=None): def handler(fun, *args, **kwargs): error = None access_token = None if CSRF_TOKEN_REQUIRED: if 'state' not in request.args: error = FacebookError(message="`state` parameter is required. This request might have been in...
AttributeError
dataset/ETHPy150Open elmcitylabs/ECL-Facebook/ecl_facebook/flask_decorators.py/facebook_callback
7,748
@detail_route(methods=['put']) def set_state(self, request, pk=None): """ Special view endpoint to set and reset a state of a motion. Send PUT {'state': <state_id>} to set and just PUT {} to reset the state. Only managers can use this view. """ # Retrieve motion and ...
ValueError
dataset/ETHPy150Open OpenSlides/OpenSlides/openslides/motions/views.py/MotionViewSet.set_state
7,749
def fetch(self): counter = 0 while counter <= self.timeout and not self.done: try: self.dispatch(self.transport) self.done = True self.logger.info("Done processing.") except urllib2.HTTPError, err: #code = err.code ...
IOError
dataset/ETHPy150Open comodit/synapse-agent/synapse/resourcefile.py/ResourceFile.fetch
7,750
def _get_http(self): self.logger.info('Trying to open url %s' % self.url) webfile = urllib2.urlopen(self.url) try: tasks = json.loads(webfile.read()) self.logger.info('Found %d task(s), processing...' % len(tasks)) except __HOLE__, err: raise Exception...
ValueError
dataset/ETHPy150Open comodit/synapse-agent/synapse/resourcefile.py/ResourceFile._get_http
7,751
def _get_fs(self): self.logger.info('Trying to open file %s' % self.path) with open(self.path, 'r') as fd: try: tasks = json.load(fd) self.logger.info('Found %d task(s)' % len(tasks)) except __HOLE__, err: raise Exception('Error whi...
ValueError
dataset/ETHPy150Open comodit/synapse-agent/synapse/resourcefile.py/ResourceFile._get_fs
7,752
def prepdir(coord): ''' ''' path = 'tiles/%(zoom)d/%(column)d/%(row)d' % coord.__dict__ try: makedirs(path) except __HOLE__: pass return path
OSError
dataset/ETHPy150Open codeforamerica/US-Census-Area-API/data/index-tiles.py/prepdir
7,753
def next_node(self, condition=None, include_self=0, descend=1, siblings=0, ascend=0): """ Return the first node in the iterable returned by traverse(), or None if the iterable is empty. Parameter list is the same as of traverse. Note that include_self defaults...
IndexError
dataset/ETHPy150Open adieu/allbuttonspressed/docutils/nodes.py/Node.next_node
7,754
def replace_self(self, new): """ Replace `self` node with `new`, where `new` is a node or a list of nodes. """ update = new if not isinstance(new, Node): # `new` is a list; update first child. try: update = new[0] except...
IndexError
dataset/ETHPy150Open adieu/allbuttonspressed/docutils/nodes.py/Element.replace_self
7,755
def parse_csv_date(date): try: return None if date == 'NULL' else datetime.strptime(date, '%m/%d/%y') except __HOLE__: print("Can't parse the following date: " + date)
ValueError
dataset/ETHPy150Open codeforamerica/comport/comport/utils.py/parse_csv_date
7,756
def __init__(self, *args, **kwargs): super(ReturnsContract, self).__init__(*args, **kwargs) assert len(self.args) in [1, 2, 3] self.obj_name = self.args[0] or None self.obj_type = self.objects[self.obj_name] try: self.min_bound = int(self.args[1]) except Ind...
IndexError
dataset/ETHPy150Open wcong/ants/ants/contracts/default.py/ReturnsContract.__init__
7,757
def __getitem__(self, key): key = key.lower() try: return self.base_data_types_reverse[key] except __HOLE__: size = get_field_size(key) if size is not None: return ('CharField', {'max_length': size}) raise KeyError
KeyError
dataset/ETHPy150Open django/django/django/db/backends/sqlite3/introspection.py/FlexibleFieldLookupDict.__getitem__
7,758
def get_relations(self, cursor, table_name): """ Return a dictionary of {field_name: (field_name_other_table, other_table)} representing all relationships to the given table. """ # Dictionary of relations to return relations = {} # Schema for this table c...
TypeError
dataset/ETHPy150Open django/django/django/db/backends/sqlite3/introspection.py/DatabaseIntrospection.get_relations
7,759
def render(self, name, value, attrs=None): if value is not None: # Special handling for MarkupField value. # This won't touch simple TextFields because they don't have # 'raw' attribute. try: value = value.raw except __HOLE__: ...
AttributeError
dataset/ETHPy150Open zsiciarz/django-markitup/markitup/widgets.py/MarkupInput.render
7,760
def close(self): try: return self.file.close() except __HOLE__ as e: if e.errno != 2: # Means the file was moved or deleted before the tempfile # could unlink it. Still sets self.file.close_called and # calls self.file.file.close()...
OSError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/core/files/uploadedfile.py/TemporaryUploadedFile.close
7,761
def QuotedFileName(fname): """Given a filename, return a quoted version if necessary """ import regutil, string try: string.index(fname, " ") # Other chars forcing quote? return '"%s"' % fname except __HOLE__: # No space in name. return fname
ValueError
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/win32/scripts/regsetup.py/QuotedFileName
7,762
def LocateFileName(fileNamesString, searchPaths): """Locate a file name, anywhere on the search path. If the file can not be located, prompt the user to find it for us (using a common OpenFile dialog) Raises KeyboardInterrupt if the user cancels. """ import regutil, string, os...
ImportError
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/win32/scripts/regsetup.py/LocateFileName
7,763
def LocateOptionalPath(fileName, searchPaths): """Like LocatePath, but returns None if the user cancels. """ try: return LocatePath(fileName, searchPaths) except __HOLE__: return None
KeyboardInterrupt
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/win32/scripts/regsetup.py/LocateOptionalPath
7,764
def LocateOptionalFileName(fileName, searchPaths = None): """Like LocateFileName, but returns None if the user cancels. """ try: return LocateFileName(fileName, searchPaths) except __HOLE__: return None
KeyboardInterrupt
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/win32/scripts/regsetup.py/LocateOptionalFileName
7,765
def send_click(self, click): """ Sends a click to the server if the previous click has been confirmed. Args: click (BaseClick): The click to send. Returns: the click's action ID if the click could be sent, None if the previous click has not been rece...
AttributeError
dataset/ETHPy150Open SpockBotMC/SpockBot/spockbot/plugins/helpers/inventory.py/InventoryPlugin.send_click
7,766
def find_all_tests(root_suite): """Yields all the tests and their names from a given suite.""" suites = [root_suite] while suites: tsuite = suites.pop() try: # not that suite is iterable, thus every sub-suite from suite # is appended to the suites list sui...
TypeError
dataset/ETHPy150Open BasicWolf/kaylee/kaylee/testsuite/__init__.py/find_all_tests
7,767
def tests(): def assert_eq(x, y): try: expr = xpath(x) assert expr == y, expr except __HOLE__: ast = Decompiler(x.gi_code).ast print ast print raise assert (div for div in DOM).gi_frame.f_locals['.0'] == DOM assert...
AssertionError
dataset/ETHPy150Open hchasestevens/xpyth/tests.py/tests
7,768
def ingest ( self ): """Read the stack and ingest""" with closing ( ocpcaproj.OCPCAProjectsDB() ) as projdb: proj = projdb.loadProject ( self.token ) with closing ( ocpcadb.OCPCADB (proj) ) as db: (startslice, endslice) = proj.datasetcfg.slicerange (xcubedim, ycubedim, zcubedim) = cubed...
IOError
dataset/ETHPy150Open neurodata/ndstore/ingest/eva/eva15.py/CatmaidIngest.ingest
7,769
def POST(self): i = web.input(email="", password="") if not waltz.utils.valid_email(i.email): return self.GET(msg="invalid email") try: u = User(i.email) except __HOLE__: return self.GET(msg="no such user") if u.authenticate(i.password)...
AttributeError
dataset/ETHPy150Open mekarpeles/waltz/examples/simplelogin/routes/auth.py/Login.POST
7,770
def render_tag(self, context, runcaseversion, user, environment, varname): """Get/construct Result and place it in context under ``varname``""" # check for any completed result states from other users for this # same case/env combo. include_kwargs = dict( environment=environ...
IndexError
dataset/ETHPy150Open mozilla/moztrap/moztrap/view/runtests/templatetags/execution.py/OtherResultFor.render_tag
7,771
def routerrule_list(request, **params): if 'router_id' in params: params['device_id'] = params['router_id'] if 'router' in request.META: router = request.META['router'] else: router = api.router_get(request, params['device_id']) try: rules = router.router_rules except...
AttributeError
dataset/ETHPy150Open CiscoSystems/avos/openstack_dashboard/dashboards/project/routers/extensions/routerrules/rulemanager.py/routerrule_list
7,772
def get_errno(e): """ Return the errno of an exception, or the first argument if errno is not available. :param e: the exception object """ try: return e.errno except __HOLE__: return e.args[0]
AttributeError
dataset/ETHPy150Open jasonrbriggs/stomp.py/stomp/backward.py/get_errno
7,773
def get_dihedrals_for_conformation(self, conformation): coordsets = self.structure_ensemble.getCoordsets() self.structure_ensemble.setCoords(coordsets[conformation]) dihedral_angles = [] for residue in self.structure_ensemble.iterResidues(): try: ...
ValueError
dataset/ETHPy150Open victor-gil-sepulveda/pyProCT/pyproct/data/handler/protein/proteinEnsembleData.py/ProteinEnsembleData.get_dihedrals_for_conformation
7,774
def _scan(self): # We're only interested in file-based modules (not C extensions). modules = [m.__file__ for m in sys.modules.values() if m and getattr(m, '__file__', None)] for filename in modules: # We're only interested in the source .py files. file...
OSError
dataset/ETHPy150Open jparise/python-reloader/monitor.py/ModuleMonitor._scan
7,775
@expose(help="create project files from a template") def create(self): if not len(self.app.pargs.extra) >= 1: raise boss_exc.BossArgumentError("Destination path required.") if not self.app.pargs.template: raise boss_exc.BossArgumentError("Template label required.") ...
IndexError
dataset/ETHPy150Open datafolklabs/boss/boss/cli/controllers/base.py/BossBaseController.create
7,776
def get_taskwarrior_config(path): try: return TaskRc(path) except __HOLE__: return {}
IOError
dataset/ETHPy150Open coddingtonbear/taskwarrior-inthe.am/taskwarrior_inthe_am/taskwarrior.py/get_taskwarrior_config
7,777
def continue_with(self, func): try: response = func() except __HOLE__ as exception: if self.parent: self.parent.on_success(exception.args) except BaseException as exception: if isinstance(exception, TaskFailed): exception.tasktr...
StopIteration
dataset/ETHPy150Open SpockBotMC/SpockBot/spockbot/plugins/tools/task.py/Task.continue_with
7,778
def test_main(): for name in dir(_testcapi): if name.startswith('test_'): test = getattr(_testcapi, name) if test_support.verbose: print "internal", name try: test() except _testcapi.error: raise test_support.Te...
AttributeError
dataset/ETHPy150Open babble/babble/include/jython/Lib/test/test_capi.py/test_main
7,779
def run(port=5000): host = '127.0.0.1' try: from werkzeug.serving import run_simple except __HOLE__: pass else: run_simple(host, port, app, use_reloader=True, use_debugger=True) return print('Could not import Werkzeug, running without the reloader ' 'or debu...
ImportError
dataset/ETHPy150Open Kozea/WeasyPrint/weasyprint/navigator.py/run
7,780
def _eval_derivative(self, s): try: res = 0 if self.args[0].has(s) or self.args[1].has(s): for i, p in enumerate(self._diffargs): m = self._diffargs[i].diff(s) if m != 0: res += self.fdiff((1, i))*m ...
NotImplementedError
dataset/ETHPy150Open sympy/sympy/sympy/functions/special/hyper.py/TupleParametersBase._eval_derivative
7,781
def _eval_evalf(self, prec): # The default code is insufficient for polar arguments. # mpmath provides an optional argument "r", which evaluates # G(z**(1/r)). I am not sure what its intended use is, but we hijack it # here in the following way: to evaluate at a number z of |argument| ...
ValueError
dataset/ETHPy150Open sympy/sympy/sympy/functions/special/hyper.py/meijerg._eval_evalf
7,782
def success(self): if self.status == 403: raise InvalidCredsError('Invalid credentials', GoGridNodeDriver) if self.status == 401: raise InvalidCredsError('API Key has insufficient rights', GoGridNodeDriver) if not self.body: return None try: ...
ValueError
dataset/ETHPy150Open cloudkick/libcloud/libcloud/compute/drivers/gogrid.py/GoGridResponse.success
7,783
def parse_error(self): try: return json.loads(self.body)["list"][0]['message'] except __HOLE__: return None
ValueError
dataset/ETHPy150Open cloudkick/libcloud/libcloud/compute/drivers/gogrid.py/GoGridResponse.parse_error
7,784
def list_nodes(self): passwords_map = {} res = self._server_list() try: for password in self._password_list()['list']: try: passwords_map[password['server']['id']] = password['password'] except __HOLE__: pass exce...
KeyError
dataset/ETHPy150Open cloudkick/libcloud/libcloud/compute/drivers/gogrid.py/GoGridNodeDriver.list_nodes
7,785
def _get_first_ip(self, location=None): ips = self.ex_list_ips(public=True, assigned=False, location=location) try: return ips[0].ip except __HOLE__: raise LibcloudError('No public unassigned IPs left', GoGridNodeDriver)
IndexError
dataset/ETHPy150Open cloudkick/libcloud/libcloud/compute/drivers/gogrid.py/GoGridNodeDriver._get_first_ip
7,786
def ex_create_node_nowait(self, **kwargs): """Don't block until GoGrid allocates id for a node but return right away with id == None. The existance of this method is explained by the fact that GoGrid assigns id to a node only few minutes after creation.""" name = kwargs[...
KeyError
dataset/ETHPy150Open cloudkick/libcloud/libcloud/compute/drivers/gogrid.py/GoGridNodeDriver.ex_create_node_nowait
7,787
def has_key(self,key): if self._is_hasheable(key): return self.hasheable_instances.has_key(key) else: for i,j in self.not_hasheable_instances: try: if i == key: return True except __HOLE__: ...
TypeError
dataset/ETHPy150Open weblabdeusto/weblabdeusto/server/src/voodoo/mapper.py/_InstanceDictionary.has_key
7,788
def remove_unpickables(instance): # This function tries to do the same as: # load_from_dto(dto_generator(obj), skip_recoverables = True ) # in a far faster way already_removed_hash = {} # For those that can be hashed already_removed_nothash = {} # For those that can't be hashed: ...
TypeError
dataset/ETHPy150Open weblabdeusto/weblabdeusto/server/src/voodoo/mapper.py/remove_unpickables
7,789
def load_from_dto(instance,exceptions = None,skip_recoverables=False): if exceptions == None: exceptions = _default_exceptions else: tmp_exceptions = () for i in exceptions: tmp_exceptions = tmp_exceptions + (i,) exceptions = tmp_exceptions parsed_instances = _In...
AttributeError
dataset/ETHPy150Open weblabdeusto/weblabdeusto/server/src/voodoo/mapper.py/load_from_dto
7,790
def jsonrpc_method(name, authenticated=False, authentication_arguments=['username', 'password'], safe=False, validate=False, site=default_site): """ Wraps a function turns it into a json-rpc method. Adds several attri...
KeyError
dataset/ETHPy150Open samuraisam/django-json-rpc/jsonrpc/__init__.py/jsonrpc_method
7,791
def i2cReg(self,wr,addr=0x00,data=0x0000): try : if(wr == "w"): tmp = (data&0x00FF)<<8 | (data&0xFF00)>>8 #print "W:0x%02X = 0x%04X" % (addr,data) return bus.write_word_data(self.I2C_ADDR,addr,tmp) elif(wr == "r"): tmp = bu...
IOError
dataset/ETHPy150Open DexterInd/GrovePi/Software/Python/grove_i2c_temp_hum_hdc1000/grove_i2c_temp_hum_hdc1000.py/HDC1000.i2cReg
7,792
def Temperature(self): try : bus.write_byte(self.I2C_ADDR,0x00) time.sleep(0.20) d=[0]*2 # print self.i2c.read_block_data(I2C_ADDR,0x00) d[0] = bus.read_byte(self.I2C_ADDR) time.sleep(0.001) d[1] = bus.read_byte(self.I2C_ADDR) ...
IOError
dataset/ETHPy150Open DexterInd/GrovePi/Software/Python/grove_i2c_temp_hum_hdc1000/grove_i2c_temp_hum_hdc1000.py/HDC1000.Temperature
7,793
def Humidity(self): try : bus.write_byte(self.I2C_ADDR,0x00) time.sleep(0.10) d=[0]*2 d[0] = bus.read_byte(self.I2C_ADDR) time.sleep(0.001) d[1] = bus.read_byte(self.I2C_ADDR) time.sleep(0.001) #print "0x%02X :0x%0...
IOError
dataset/ETHPy150Open DexterInd/GrovePi/Software/Python/grove_i2c_temp_hum_hdc1000/grove_i2c_temp_hum_hdc1000.py/HDC1000.Humidity
7,794
def default_test_processes(): """ Default number of test processes when using the --parallel option. """ # The current implementation of the parallel test runner requires # multiprocessing to start subprocesses with fork(). # On Python 3.4+: if multiprocessing.get_start_method() != 'fork': i...
KeyError
dataset/ETHPy150Open django/django/django/test/runner.py/default_test_processes
7,795
def run(self, result): """ Distribute test cases across workers. Return an identifier of each test case with its result in order to use imap_unordered to show results as soon as they're available. To minimize pickling errors when getting results from workers: - pass ba...
StopIteration
dataset/ETHPy150Open django/django/django/test/runner.py/ParallelTestSuite.run
7,796
def is_discoverable(label): """ Check if a test label points to a python package or file directory. Relative labels like "." and ".." are seen as directories. """ try: mod = import_module(label) except (ImportError, __HOLE__): pass else: return hasattr(mod, '__path__...
TypeError
dataset/ETHPy150Open django/django/django/test/runner.py/is_discoverable
7,797
def processmessage(self, tags, args): if self.writer is not None and args: lines = self.format_message(tags, args) self.writer(''.join(lines)) try: self._tag2proc[tags](tags, args) except __HOLE__: pass
KeyError
dataset/ETHPy150Open pytest-dev/pytest/_pytest/vendored_packages/pluggy.py/_TagTracer.processmessage
7,798
def _wrapped_call(wrap_controller, func): """ Wrap calling to a function with a generator which needs to yield exactly once. The yield point will trigger calling the wrapped function and return its _CallOutcome to the yield point. The generator then needs to finish (raise StopIteration) in order for t...
StopIteration
dataset/ETHPy150Open pytest-dev/pytest/_pytest/vendored_packages/pluggy.py/_wrapped_call
7,799
def varnames(func, startindex=None): """ return argument name tuple for a function, method, class or callable. In case of a class, its "__init__" method is considered. For methods the "self" parameter is not included unless you are passing an unbound method with Python3 (which has no supports for unbou...
TypeError
dataset/ETHPy150Open pytest-dev/pytest/_pytest/vendored_packages/pluggy.py/varnames