Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
1,000
def run_test(self): result = None timeout_duration = 10 # Default test case timeout event_queue = Queue() # Events from DUT to host dut_event_queue = Queue() # Events from host to DUT {k;v} def callback__notify_prn(key, value, timestamp): """! Handles _...
ValueError
dataset/ETHPy150Open ARMmbed/htrun/mbed_host_tests/host_tests_runner/host_test_default.py/DefaultTestSelector.run_test
1,001
def execute(self): """! Test runner for host test. @details This function will start executing test and forward test result via serial port to test suite. This function is sensitive to work-flow flags such as --skip-flashing, --skip-reset etc. First fu...
KeyboardInterrupt
dataset/ETHPy150Open ARMmbed/htrun/mbed_host_tests/host_tests_runner/host_test_default.py/DefaultTestSelector.execute
1,002
def basic_auth(realm, checkpassword, debug=False): """A CherryPy tool which hooks at before_handler to perform HTTP Basic Access Authentication, as specified in :rfc:`2617`. If the request has an 'authorization' header with a 'Basic' scheme, this tool attempts to authenticate the credentials supplied i...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/lib/auth_basic.py/basic_auth
1,003
def errstr (exc): try: code = exc.args[0] if exc.args else exc.errno return '[Errno %s] %s' % (errno.errorcode.get(code,str(code)),str(exc)) except KeyError: return '[Errno unknown (key)] %s' % str(exc) except __HOLE__: return '[Errno unknown (attr)] %s' % str(exc)
AttributeError
dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/util/errstr.py/errstr
1,004
def prepare_search_groups(events, source_duration, chapter_times, max_ts_duration, max_ts_distance): last_unlinked = None for idx, event in enumerate(events): if event.is_comment: try: event.link_event(events[idx+1]) except IndexError: event.link_e...
StopIteration
dataset/ETHPy150Open tp7/Sushi/sushi.py/prepare_search_groups
1,005
def hydrate(self, bundle): """Hydrate handles the conversion of fqdn to a label or domain.""" if 'fqdn' in bundle.data: try: label_domain = ensure_label_domain(bundle.data['fqdn']) bundle.data['label'], bundle.data['domain'] = label_domain except _...
ValidationError
dataset/ETHPy150Open mozilla/inventory/mozdns/api/v1/api.py/CommonDNSResource.hydrate
1,006
@transaction.commit_on_success def obj_create(self, bundle, request=None, **kwargs): """ A generic version of creating a dns object. The strategy is simple: get bundle.data to the point where we call Class(**bundle.data) which creates an object. We then clean it and then save it. Fin...
ValueError
dataset/ETHPy150Open mozilla/inventory/mozdns/api/v1/api.py/CommonDNSResource.obj_create
1,007
@locked_function('inventory.record_lock') def save_commit(self, request, bundle, views, comment, kv): verb = "updated" if bundle.obj.pk else "created" error = None try: # obj's save() method should be calling full_clean() bundle.obj.save() except __HOLE__, e: ...
ValidationError
dataset/ETHPy150Open mozilla/inventory/mozdns/api/v1/api.py/CommonDNSResource.save_commit
1,008
def hydrate(self, bundle): # Nameservers don't have a label if 'fqdn' in bundle.data: bundle.errors['domain'] = "Nameservers shouldn't have a fqdn" elif 'label' in bundle.data: bundle.errors['domain'] = "Nameservers shouldn't have a label" else: domain...
ObjectDoesNotExist
dataset/ETHPy150Open mozilla/inventory/mozdns/api/v1/api.py/NameserverResource.hydrate
1,009
def goToDirectory(alias): """go to a saved directory""" if not settings.platformCompatible(): return False data = pickle.load(open(settings.getDataFile(), "rb")) try: data[alias] except __HOLE__: speech.fail("Sorry, it doesn't look like you have saved " + alias + " yet.") speech.fail("Go to the directory y...
KeyError
dataset/ETHPy150Open mikemelch/hallie/hallie/modules/user.py/goToDirectory
1,010
def handle_iters(self): for i in self.iterators: try: i.next() except __HOLE__: self.iterators.remove(i)
StopIteration
dataset/ETHPy150Open richo/groundstation/groundstation/station.py/Station.handle_iters
1,011
def create_channel(self, channel_name): try: os.mkdir(os.path.join(self.store.gref_path(), channel_name)) return True except __HOLE__: return False
OSError
dataset/ETHPy150Open richo/groundstation/groundstation/station.py/Station.create_channel
1,012
def write_graph(self, filename): """Writes the graph to the file with format based on file extension """ _, ext = os.path.splitext(filename) try: format = self.supported_formats[ext.lower()] except __HOLE__: raise ValueError("No format could be found for t...
KeyError
dataset/ETHPy150Open croach/pydata2013/govtrack.py/Graph.write_graph
1,013
def party_affiliation(name): """Returns the member's political party affiliation Given a name with the following format: TITLE FIRST_NAME LAST_NAME [PARTY_AFFILIATION-DISTRICT_OR_STATE] this function parses out the party affiliation and returns it. """ parties = {'R': 'republican', 'D': 'd...
KeyError
dataset/ETHPy150Open croach/pydata2013/govtrack.py/party_affiliation
1,014
@staticmethod def parse(version): """Attempts to parse the given string as Semver, then falls back to Namedver.""" try: return Semver.parse(version) except __HOLE__: return Namedver.parse(version)
ValueError
dataset/ETHPy150Open pantsbuild/pants/src/python/pants/task/scm_publish_mixin.py/Version.parse
1,015
@classmethod def parse(cls, version): # must not contain whitespace if not cls._VALID_NAME.match(version): raise ValueError("Named versions must match {}: '{}'".format(cls._VALID_NAME.pattern, version)) if cls._INVALID_NAME.match(version): raise ValueError("Named version must contain at least ...
ValueError
dataset/ETHPy150Open pantsbuild/pants/src/python/pants/task/scm_publish_mixin.py/Namedver.parse
1,016
@staticmethod def parse(version): components = version.split('.', 3) if len(components) != 3: raise ValueError major, minor, patch = components def to_i(component): try: return int(component) except (TypeError, __HOLE__): raise ValueError('Invalid revision component ...
ValueError
dataset/ETHPy150Open pantsbuild/pants/src/python/pants/task/scm_publish_mixin.py/Semver.parse
1,017
def AddProperty(self, name, _type, animatable=True, user=True): ''' Add a property to this component @param name: the name of the property @param _type: the data type of the property: ''' if self.ListProperties(pattern=name): raise Exceptio...
KeyError
dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/moBu/site-packages/PyMoBu-0.2/pymobu/components/__init__.py/PMBComponent.AddProperty
1,018
def SetInverseMatrix(self, matrix, worldSpace=False, _type='Transformation'): ''' Set the inverse matrix @param worldSpace: world space matrix (True/False) Default False @param _type: matrix type (Transformation, Translation, Rotation, Scaling, Center, All) ''' try:...
KeyError
dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/moBu/site-packages/PyMoBu-0.2/pymobu/components/__init__.py/PMBModel.SetInverseMatrix
1,019
def SetMatrix(self, matrix, worldSpace=False, _type='Transformation'): ''' Set the matrix @param worldSpace: world space matrix (True/False) Default False @param _type: matrix type (Transformation, Translation, Rotation, Scaling, Center, All) ''' try: s...
KeyError
dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/moBu/site-packages/PyMoBu-0.2/pymobu/components/__init__.py/PMBModel.SetMatrix
1,020
def GetInverseMatrix(self, worldSpace=False, _type='Transformation'): ''' Get the inverse matrix @param worldSpace: world space matrix (True/False) Default False @param _type: matrix type (Transformation, Translation, Rotation, Scaling, Center, All) ''' matrix = FB...
KeyError
dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/moBu/site-packages/PyMoBu-0.2/pymobu/components/__init__.py/PMBModel.GetInverseMatrix
1,021
def GetMatrix(self, worldSpace=False, _type='Transformation'): ''' Get the matrix @param worldSpace: world space matrix (True/False) Default False @param _type: matrix type (Transformation, Translation, Rotation, Scaling, Center, All) ''' matrix = FBMatrix() ...
KeyError
dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/moBu/site-packages/PyMoBu-0.2/pymobu/components/__init__.py/PMBModel.GetMatrix
1,022
@classmethod def from_queryset(cls, queryset, fields=None): if fields is None: fields = queryset.model._meta.writable_fields else: fields = [queryset.model._meta.get_field(f) for f in fields] table = cls(*(f.name for f in fields)) for instance in queryset: ...
AttributeError
dataset/ETHPy150Open natano/tiget/tiget/table.py/Table.from_queryset
1,023
def _fetch_changes(self, filenames, progress): count = 0 total = len(filenames) progress(_('Parsing RCS files'), count, total) # We will commit changes to the database every few seconds to # avoid having to scan all RCS files again in case the process # is interrupted or...
KeyboardInterrupt
dataset/ETHPy150Open ustuehler/git-cvs/cvsgit/cvs.py/CVS._fetch_changes
1,024
def get_admin_delete_url(self): try: # Django <=1.6 model_name = self._meta.module_name except __HOLE__: # Django >1.6 model_name = self._meta.model_name return urlresolvers.reverse( 'admin:{0}_{1}_delete'.format(self._meta.app_label, m...
AttributeError
dataset/ETHPy150Open divio/django-filer/filer/models/foldermodels.py/Folder.get_admin_delete_url
1,025
def test_invalid_class(): ppn = Perceptron(epochs=40, eta=0.01, random_seed=1) try: ppn.fit(X, y2) # -2, 1 class assert(1 == 2) except __HOLE__: pass
ValueError
dataset/ETHPy150Open rasbt/mlxtend/mlxtend/classifier/tests/test_perceptron.py/test_invalid_class
1,026
def find_test_case(self): splitted_test_target = self.test_target.split(".") module_ref = None module_name_len = 0 for i in range(len(splitted_test_target)): try: module_ref = importlib.import_module(".".join(splitted_test_target[:i + 1])) modu...
ImportError
dataset/ETHPy150Open KarlGong/ptest/ptest/testfinder.py/TestFinder.find_test_case
1,027
def find_test_cases_in_module(self, module_ref): for module_element in dir(module_ref): test_class_ref = getattr(module_ref, module_element) try: if test_class_ref.__pd_type__ == PDecoratorType.TestClass \ and test_class_ref.__enabled__ \ ...
AttributeError
dataset/ETHPy150Open KarlGong/ptest/ptest/testfinder.py/TestFinder.find_test_cases_in_module
1,028
def find_test_cases_in_class(self, test_class_ref): for class_element in dir(test_class_ref): test_case_ref = getattr(test_class_ref(), class_element) try: if test_case_ref.__pd_type__ == PDecoratorType.Test \ and test_case_ref.__enabled__ \ ...
AttributeError
dataset/ETHPy150Open KarlGong/ptest/ptest/testfinder.py/TestFinder.find_test_cases_in_class
1,029
@cached_property def image(self): """Return a Pil representation of this image """ if sys.version < '3': imageio = StringIO.StringIO(self._image_data) else: imageio = StringIO.BytesIO(self._image_data) try: source_image = PILImage.open(imageio) ...
IOError
dataset/ETHPy150Open jorgebastida/glue/glue/core.py/Image.image
1,030
def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except __HOLE__: raise AttributeError("no such move, %r" % (name,))
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/utils/six.py/remove_move
1,031
def get_host_target(env): debug('vc.py:get_host_target()') host_platform = env.get('HOST_ARCH') if not host_platform: host_platform = platform.machine() # TODO(2.5): the native Python platform.machine() function returns # '' on all Python versions before 2.6, after which it also us...
KeyError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Tool/MSCommon/vc.py/get_host_target
1,032
def msvc_version_to_maj_min(msvc_version): msvc_version_numeric = ''.join([x for x in msvc_version if x in string_digits + '.']) t = msvc_version_numeric.split(".") if not len(t) == 2: raise ValueError("Unrecognized version %s (%s)" % (msvc_version,msvc_version_numeric)) try: maj = int(t[0])...
ValueError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Tool/MSCommon/vc.py/msvc_version_to_maj_min
1,033
def find_vc_pdir(msvc_version): """Try to find the product directory for the given version. Note ---- If for some reason the requested version could not be found, an exception which inherits from VisualCException will be raised.""" root = 'Software\\' if common.is_win64(): root ...
KeyError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Tool/MSCommon/vc.py/find_vc_pdir
1,034
def msvc_setup_env_once(env): try: has_run = env["MSVC_SETUP_RUN"] except __HOLE__: has_run = False if not has_run: msvc_setup_env(env) env["MSVC_SETUP_RUN"] = True
KeyError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Tool/MSCommon/vc.py/msvc_setup_env_once
1,035
def view_judge(request, judge_id): judge_id = int(judge_id) try: judge = Judge.objects.get(pk=judge_id) except Judge.DoesNotExist: return render_to_response('error.html', {'error_type': "View Judge", 'error_name': str(judge_...
ValueError
dataset/ETHPy150Open jolynch/mit-tab/mittab/apps/tab/judge_views.py/view_judge
1,036
def enter_judge(request): if request.method == 'POST': form = JudgeForm(request.POST) if form.is_valid(): try: form.save() except __HOLE__: return render_to_response('error.html', {'error_type': "Judge",...
ValueError
dataset/ETHPy150Open jolynch/mit-tab/mittab/apps/tab/judge_views.py/enter_judge
1,037
def add_scratches(request, judge_id, number_scratches): try: judge_id,number_scratches = int(judge_id),int(number_scratches) except __HOLE__: return render_to_response('error.html', {'error_type': "Scratch",'error_name': "Data Entry", ...
ValueError
dataset/ETHPy150Open jolynch/mit-tab/mittab/apps/tab/judge_views.py/add_scratches
1,038
def view_scratches(request, judge_id): try: judge_id = int(judge_id) except __HOLE__: return render_to_response('error.html', {'error_type': "Scratch",'error_name': "Delete", 'error_info':"I require INTEGERS!"}, ...
ValueError
dataset/ETHPy150Open jolynch/mit-tab/mittab/apps/tab/judge_views.py/view_scratches
1,039
def _strerror(err): try: return os.strerror(err) except (ValueError, OverflowError, __HOLE__): if err in errorcode: return errorcode[err] return "Unknown error %s" %err
NameError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/asyncore.py/_strerror
1,040
def __repr__(self): status = [self.__class__.__module__+"."+self.__class__.__name__] if self.accepting and self.addr: status.append('listening') elif self.connected: status.append('connected') if self.addr is not None: try: status.appen...
TypeError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/asyncore.py/dispatcher.__repr__
1,041
def accept(self): # XXX can return either an address pair or None try: conn, addr = self.socket.accept() except __HOLE__: return None except socket.error as why: if why.args[0] in (EWOULDBLOCK, ECONNABORTED, EAGAIN): return None ...
TypeError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/asyncore.py/dispatcher.accept
1,042
def __getattr__(self, attr): try: retattr = getattr(self.socket, attr) except __HOLE__: raise AttributeError("%s instance has no attribute '%s'" %(self.__class__.__name__, attr)) else: msg = "%(me)s.%(attr)s is deprecated. Use ...
AttributeError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/asyncore.py/dispatcher.__getattr__
1,043
def close_all(map=None, ignore_all=False): if map is None: map = socket_map for x in map.values(): try: x.close() except __HOLE__, x: if x.args[0] == EBADF: pass elif not ignore_all: raise except _reraised_except...
OSError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/asyncore.py/close_all
1,044
def __init__(self, fd, map=None): dispatcher.__init__(self, None, map) self.connected = True try: fd = fd.fileno() except __HOLE__: pass self.set_file(fd) # set it to non-blocking mode flags = fcntl.fcntl...
AttributeError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/asyncore.py/file_dispatcher.__init__
1,045
def clear_mappers(): """Remove all mappers from all classes. This function removes all instrumentation from classes and disposes of their associated mappers. Once called, the classes are unmapped and can be later re-mapped with new mappers. :func:`.clear_mappers` is *not* for normal use, as there...
KeyError
dataset/ETHPy150Open goFrendiAsgard/kokoropy/kokoropy/packages/sqlalchemy/orm/__init__.py/clear_mappers
1,046
def Open(self, urn, aff4_type=None, mode="r"): """Opens the named object. DeletionPool will only open the object if it's not in the pool already. Otherwise it will just return the cached version. Objects are cached based on their urn and mode. I.e. same object opened with mode="r" and mode="rw" wil...
KeyError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/DeletionPool.Open
1,047
def MultiOpen(self, urns, aff4_type=None, mode="r"): """Opens many urns efficiently, returning cached objects when possible.""" result = [] not_opened_urns = [] for urn in urns: key = self._ObjectKey(urn, mode) try: result.append(self._objects_cache[key]) except __HOLE__: ...
KeyError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/DeletionPool.MultiOpen
1,048
def ListChildren(self, urn): """Lists children of a given urn. Resulting list is cached.""" result = self.MultiListChildren([urn]) try: return result[urn] except __HOLE__: return []
KeyError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/DeletionPool.ListChildren
1,049
def MultiListChildren(self, urns): """Lists children of a bunch of given urns. Results are cached.""" result = {} not_listed_urns = [] for urn in urns: try: result[urn] = self._children_lists_cache[urn] except __HOLE__: not_listed_urns.append(urn) if not_listed_urns: ...
KeyError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/DeletionPool.MultiListChildren
1,050
def RecursiveMultiListChildren(self, urns): """Recursively lists given urns. Results are cached.""" result = {} checked_urns = set() not_cached_urns = [] urns_to_check = urns while True: found_children = [] for urn in urns_to_check: try: children = result[urn] = s...
KeyError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/DeletionPool.RecursiveMultiListChildren
1,051
@classmethod def ParseAgeSpecification(cls, age): """Parses an aff4 age and returns a datastore age specification.""" try: return (0, int(age)) except (ValueError, __HOLE__): pass if age == NEWEST_TIME: return data_store.DB.NEWEST_TIMESTAMP elif age == ALL_TIMES: return da...
TypeError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/Factory.ParseAgeSpecification
1,052
def GetAttributes(self, urns, ignore_cache=False, token=None, age=NEWEST_TIME): """Retrieves all the attributes for all the urns.""" urns = set([utils.SmartUnicode(u) for u in urns]) if not ignore_cache: for subject in list(urns): key = self._MakeCacheInvariant(subject, tok...
KeyError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/Factory.GetAttributes
1,053
def SetAttributes(self, urn, attributes, to_delete, add_child_index=True, mutation_pool=None, sync=False, token=None): """Sets the attributes in the data store and update the cache.""" # Force a data_store lookup next. try: # Expire all entries in the cache for this urn (for all to...
KeyError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/Factory.SetAttributes
1,054
def _UpdateChildIndex(self, urn, token, mutation_pool=None): """Update the child indexes. This function maintains the index for direct child relations. When we set an AFF4 path, we always add an attribute like index:dir/%(childname)s to its parent. This is written asynchronously to its parent. ...
KeyError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/Factory._UpdateChildIndex
1,055
def _DeleteChildFromIndex(self, urn, token): try: basename = urn.Basename() dirname = rdfvalue.RDFURN(urn.Dirname()) try: self.intermediate_cache.ExpireObject(urn.Path()) except __HOLE__: pass data_store.DB.DeleteAttributes( dirname, ["index:dir/%s" % utils....
KeyError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/Factory._DeleteChildFromIndex
1,056
def MultiOpen(self, urns, mode="rw", ignore_cache=False, token=None, aff4_type=None, age=NEWEST_TIME, follow_symlinks=True): """Opens a bunch of urns efficiently.""" if token is None: token = data_store.default_token if mode not in ["w", "r", "rw"]: raise RuntimeError("Invalid ...
IOError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/Factory.MultiOpen
1,057
def Create(self, urn, aff4_type, mode="w", token=None, age=NEWEST_TIME, ignore_cache=False, force_new_version=True, object_exists=False, mutation_pool=None, transaction=None): """Creates the urn if it does not already exist, otherwise opens it. If the urn exists and is of a different ...
IOError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/Factory.Create
1,058
def MultiDelete(self, urns, token=None): """Drop all the information about given objects. DANGEROUS! This recursively deletes all objects contained within the specified URN. Args: urns: Urns of objects to remove. token: The Security Token to use for opening this item. Raises: Run...
KeyError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/Factory.MultiDelete
1,059
def __init__(self, predicate, attribute_type=rdfvalue.RDFString, description="", name=None, _copy=False, default=None, index=None, versioned=True, lock_protected=False, creates_new_object_version=True): """Constructor. Args: predicate: The name of this attrib...
KeyError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/Attribute.__init__
1,060
@classmethod def GetAttributeByName(cls, name): # Support attribute names with a . in them: try: if "." in name: name, field = name.split(".", 1) return cls.NAMES[name][field] return cls.NAMES[name] except __HOLE__: raise AttributeError("Invalid attribute %s" % name)
KeyError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/Attribute.GetAttributeByName
1,061
def GetRDFValueType(self): """Returns this attribute's RDFValue class.""" result = self.attribute_type for field_name in self.field_names: # Support the new semantic protobufs. if issubclass(result, rdf_structs.RDFProtoStruct): try: result = result.type_infos.get(field_name).ty...
AttributeError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/Attribute.GetRDFValueType
1,062
def Validate(self): try: Attribute.GetAttributeByName(self._value) except (AttributeError, __HOLE__): raise type_info.TypeValueError( "Value %s is not an AFF4 attribute name" % self._value)
KeyError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/AFF4Attribute.Validate
1,063
def __init__(self, urn, mode="r", parent=None, clone=None, token=None, local_cache=None, age=NEWEST_TIME, follow_symlinks=True, aff4_type=None, object_exists=False, mutation_pool=None, transaction=None): if urn is not None: urn = rdfvalue.RDFURN(urn) self.urn =...
KeyError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/AFF4Object.__init__
1,064
def DecodeValueFromAttribute(self, attribute_name, value, ts): """Given a serialized value, decode the attribute. Only attributes which have been previously defined are permitted. Args: attribute_name: The string name of the attribute. value: The serialized attribute value. ts: The ti...
KeyError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/AFF4Object.DecodeValueFromAttribute
1,065
def Get(self, attribute, default=None): """Gets the attribute from this object.""" if attribute is None: return default # Allow the user to specify the attribute by name. elif isinstance(attribute, str): attribute = Attribute.GetAttributeByName(attribute) # We can't read attributes fro...
AttributeError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/AFF4Object.Get
1,066
def _GetChunkForWriting(self, chunk): """Opens a chunk for writing, creating a new one if it doesn't exist yet.""" try: chunk = self.chunk_cache.Get(chunk) chunk.dirty = True return chunk except __HOLE__: pass try: chunk = self._ReadChunk(chunk) chunk.dirty = True ...
KeyError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/AFF4ImageBase._GetChunkForWriting
1,067
def _GetChunkForReading(self, chunk): """Returns the relevant chunk from the datastore and reads ahead.""" try: return self.chunk_cache.Get(chunk) except KeyError: pass # We don't have this chunk already cached. The most common read # access pattern is contiguous reading so since we hav...
KeyError
dataset/ETHPy150Open google/grr/grr/lib/aff4.py/AFF4ImageBase._GetChunkForReading
1,068
def load_performance_check_config(): config_file = os.path.join(PATH_TO_SYSTEM_PAASTA_CONFIG_DIR, 'performance-check.json') try: with open(config_file) as f: return json.load(f) except __HOLE__ as e: print "No performance check config to use. Safely bailing." print e.stre...
IOError
dataset/ETHPy150Open Yelp/paasta/paasta_tools/cli/cmds/performance_check.py/load_performance_check_config
1,069
def _namespaces(elem, encoding, default_namespace=None): # identify namespaces used in this tree # maps qnames to *encoded* prefix:local names qnames = {None: None} # maps uri:s to prefixes namespaces = {} if default_namespace: namespaces[default_namespace] = "" def enc...
TypeError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/xml/etree/ElementTree.py/_namespaces
1,070
def _encode(text, encoding): try: return text.encode(encoding, "xmlcharrefreplace") except (__HOLE__, AttributeError): _raise_serialization_error(text)
TypeError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/xml/etree/ElementTree.py/_encode
1,071
def _escape_cdata(text, encoding): # escape character data try: # it's worth avoiding do-nothing calls for strings that are # shorter than 500 character, or so. assume that's, by far, # the most common case in most applications. if "&" in text: text = text.rep...
TypeError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/xml/etree/ElementTree.py/_escape_cdata
1,072
def _escape_attrib(text, encoding): # escape attribute value try: if "&" in text: text = text.replace("&", "&amp;") if "<" in text: text = text.replace("<", "&lt;") if ">" in text: text = text.replace(">", "&gt;") if "\"" in text: ...
AttributeError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/xml/etree/ElementTree.py/_escape_attrib
1,073
def _escape_attrib_html(text, encoding): # escape attribute value try: if "&" in text: text = text.replace("&", "&amp;") if ">" in text: text = text.replace(">", "&gt;") if "\"" in text: text = text.replace("\"", "&quot;") return text....
TypeError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/xml/etree/ElementTree.py/_escape_attrib_html
1,074
def __init__(self, source, events, parser, close_source=False): self._file = source self._close_file = close_source self._events = [] self._index = 0 self._error = None self.root = self._root = None self._parser = parser # wire up the parser for ev...
AttributeError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/xml/etree/ElementTree.py/_IterParseIterator.__init__
1,075
def next(self): while 1: try: item = self._events[self._index] self._index += 1 return item except __HOLE__: pass if self._error: e = self._error self._error = None ...
IndexError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/xml/etree/ElementTree.py/_IterParseIterator.next
1,076
def __init__(self, html=0, target=None, encoding=None): try: from xml.parsers import expat except __HOLE__: try: import pyexpat as expat except ImportError: raise ImportError( "No module named expat; use Simp...
ImportError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/xml/etree/ElementTree.py/XMLParser.__init__
1,077
def _fixname(self, key): # expand qname, and convert name string to ascii, if possible try: name = self._names[key] except __HOLE__: name = key if "}" in name: name = "{" + name self._names[key] = name = self._fixtext(name) ...
KeyError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/xml/etree/ElementTree.py/XMLParser._fixname
1,078
def _comment(self, data): try: comment = self.target.comment except __HOLE__: pass else: return comment(self._fixtext(data))
AttributeError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/xml/etree/ElementTree.py/XMLParser._comment
1,079
def _pi(self, target, data): try: pi = self.target.pi except __HOLE__: pass else: return pi(self._fixtext(target), self._fixtext(data))
AttributeError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/xml/etree/ElementTree.py/XMLParser._pi
1,080
def _default(self, text): prefix = text[:1] if prefix == "&": # deal with undefined entities try: self.target.data(self.entity[text[1:-1]]) except __HOLE__: from xml.parsers import expat err = expat.error( ...
KeyError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/xml/etree/ElementTree.py/XMLParser._default
1,081
def run(self, lib, opts, args): file_path = opts.output file_format = self.config['default_format'].get(str) file_mode = 'a' if opts.append else 'w' format_options = self.config[file_format]['formatting'].get(dict) export_format = ExportFormat.factory( file_format, ...
IOError
dataset/ETHPy150Open beetbox/beets/beetsplug/export.py/ExportPlugin.run
1,082
def file(self, address): """ Return a readable file-like object for the specified address. """ # Do the import here 'cos I'm not sure how much this will actually # be used. from .._compat import urlopen, HTTPError try: f = urlopen('http://' + address) excep...
HTTPError
dataset/ETHPy150Open enthought/envisage/envisage/resource/http_resource_protocol.py/HTTPResourceProtocol.file
1,083
def cast_to_route_factory(in_arg): from meta import MetaApplication if isinstance(in_arg, BaseRoute): return in_arg elif isinstance(in_arg, Sequence): try: if in_arg[1] is MetaApplication: raise ValueError(_meta_exc_msg) if isinstance(in_arg[1], BaseAp...
TypeError
dataset/ETHPy150Open mahmoud/clastic/clastic/application.py/cast_to_route_factory
1,084
def __init__(self, routes=None, resources=None, middlewares=None, render_factory=None, error_handler=None, **kwargs): self.debug = kwargs.pop('debug', None) self.slash_mode = kwargs.pop('slash_mode', S_REDIRECT) if kwargs: raise TypeError('unexpected keyword args: %r...
TypeError
dataset/ETHPy150Open mahmoud/clastic/clastic/application.py/BaseApplication.__init__
1,085
def set_error_handler(self, error_handler=None): if error_handler is None: if self.debug: deh_type = self.default_debug_error_handler_type else: deh_type = self.default_error_handler_type error_handler = deh_type() check_render_error(er...
TypeError
dataset/ETHPy150Open mahmoud/clastic/clastic/application.py/BaseApplication.set_error_handler
1,086
def make_tag_decorator(known_tags): """ Create a decorator allowing tests to be tagged with the *known_tags*. """ def tag(*tags): """ Tag a test method with the given tags. Can be used in conjunction with the --tags command-line argument for runtests.py. """ ...
AttributeError
dataset/ETHPy150Open numba/numba/numba/testing/main.py/make_tag_decorator
1,087
def _choose_tagged_tests(tests, tags): """ Select tests that are tagged with at least one of the given tags. """ selected = [] tags = set(tags) for test in _flatten_suite(tests): assert isinstance(test, unittest.TestCase) func = getattr(test, test._testMethodName) try: ...
AttributeError
dataset/ETHPy150Open numba/numba/numba/testing/main.py/_choose_tagged_tests
1,088
def _refleak_cleanup(): # Collect cyclic trash and read memory statistics immediately after. func1 = sys.getallocatedblocks try: func2 = sys.gettotalrefcount except __HOLE__: func2 = lambda: 42 # Flush standard output, so that buffered data is sent to the OS and # associated Pyt...
AttributeError
dataset/ETHPy150Open numba/numba/numba/testing/main.py/_refleak_cleanup
1,089
def addSuccess(self, test): try: rc_deltas, alloc_deltas = self._huntLeaks(test) except __HOLE__: # Test failed when repeated assert not self.wasSuccessful() return # These checkers return False on success, True on failure def check_rc_del...
AssertionError
dataset/ETHPy150Open numba/numba/numba/testing/main.py/RefleakTestResult.addSuccess
1,090
def _run_parallel_tests(self, result, pool, child_runner): remaining_ids = set(t.id() for t in self._ptests) it = pool.imap_unordered(child_runner, self._ptests) while True: try: child_result = it.__next__(self.timeout) except __HOLE__: ret...
StopIteration
dataset/ETHPy150Open numba/numba/numba/testing/main.py/ParallelTestRunner._run_parallel_tests
1,091
def _get_db_name(db_settings, suffix): "This provides the default test db name that Django uses." from django import VERSION as DJANGO_VERSION name = None try: if DJANGO_VERSION > (1, 7): name = db_settings['TEST']['NAME'] elif DJANGO_VERSION < (1, 7): name = db_...
KeyError
dataset/ETHPy150Open pytest-dev/pytest-django/pytest_django/db_reuse.py/_get_db_name
1,092
def _parse_int(num): try: return num and int(num) except __HOLE__: pass
ValueError
dataset/ETHPy150Open kobotoolbox/kobocat/onadata/apps/api/viewsets/briefcase_api.py/_parse_int
1,093
def GetVersionObject(): """Gets the version of the SDK by parsing the VERSION file. Returns: A Yaml object or None if the VERSION file does not exist. """ version_filename = os.path.join(os.path.dirname(google.appengine.__file__), VERSION_FILE) try: version_fh = open...
IOError
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/tools/sdk_update_checker.py/GetVersionObject
1,094
def CheckForUpdates(self): """Queries the server for updates and nags the user if appropriate. Queries the server for the latest SDK version at the same time reporting the local SDK version. The server will respond with a yaml document containing the fields: 'release': The name of the release (e...
ValueError
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/tools/sdk_update_checker.py/SDKUpdateChecker.CheckForUpdates
1,095
def _ParseNagFile(self): """Parses the nag file. Returns: A NagFile if the file was present else None. """ nag_filename = SDKUpdateChecker.MakeNagFilename() try: fh = open(nag_filename) except __HOLE__: return None try: nag = NagFile.Load(fh) finally: fh.cl...
IOError
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/tools/sdk_update_checker.py/SDKUpdateChecker._ParseNagFile
1,096
def _WriteNagFile(self, nag): """Writes the NagFile to the user's nag file. If the destination path does not exist, this method will log an error and fail silently. Args: nag: The NagFile to write. """ nagfilename = SDKUpdateChecker.MakeNagFilename() try: fh = open(nagfilename,...
IOError
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/tools/sdk_update_checker.py/SDKUpdateChecker._WriteNagFile
1,097
def test_pickling(self): import pickle mods = [pickle] try: import cPickle mods.append(cPickle) except __HOLE__: pass protocols = [0, 1, 2] for mod in mods: for protocol in protocols: for ast in (compile(i, "...
ImportError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_ast.py/AST_Tests.test_pickling
1,098
def copy_template(template_name, copy_to, **options): """copies the specified template directory to the copy_to location""" import django_extensions style = color_style() ERROR = getattr(style, 'ERROR', lambda x: x) SUCCESS = getattr(style, 'SUCCESS', lambda x: x) template_dir = os.path.join(d...
OSError
dataset/ETHPy150Open django-extensions/django-extensions/django_extensions/management/commands/create_jobs.py/copy_template
1,099
def get_info(process=None, interval=0, with_childs=False): """Return information about a process. (can be an pid or a Process object) If process is None, will return the information about the current process. """ # XXX moce get_info to circus.process ? from circus.process import (get_children, get_...
TypeError
dataset/ETHPy150Open circus-tent/circus/circus/util.py/get_info