Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
5,900
def handle_response(self, method, response): try: data = response.json(object_hook=self.get_json_object_hook) except __HOLE__: data = None if response.status_code == 200: return ApiResponse(response, method, data) if data is None: raise T...
ValueError
dataset/ETHPy150Open inueni/birdy/birdy/twitter.py/BaseTwitterClient.handle_response
5,901
def get_request_token(self, base_auth_url=None, callback_url=None, auto_set_token=True, **kwargs): if callback_url: self.session._client.client.callback_uri = to_unicode(callback_url, 'utf-8') try: token = self.session.fetch_request_token(self.request_token_url) ...
ValueError
dataset/ETHPy150Open inueni/birdy/birdy/twitter.py/UserClient.get_request_token
5,902
def get_access_token(self, oauth_verifier, auto_set_token=True): required = (self.access_token, self.access_token_secret) if not all(required): raise TwitterClientError('''%s must be initialized with access_token and access_token_secret to fetch ...
ValueError
dataset/ETHPy150Open inueni/birdy/birdy/twitter.py/UserClient.get_access_token
5,903
def get_access_token(self, auto_set_token=True): data = {'grant_type': 'client_credentials'} try: response = self.session.post(self.request_token_url, auth=self.auth, data=data) data = json.loads(response.content.decode('utf-8')) access_token = data['access_t...
ValueError
dataset/ETHPy150Open inueni/birdy/birdy/twitter.py/AppClient.get_access_token
5,904
def reset_config(): while True: try: CONFIG._pop_object() except __HOLE__: break
IndexError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/tests/test_config.py/reset_config
5,905
def __init__(self, generator): self.g = generator self.io_loop = IOLoop.instance() try: self.call(self.g.next()) except __HOLE__: pass
StopIteration
dataset/ETHPy150Open truemped/tornadotools/tornadotools/adisp.py/CallbackDispatcher.__init__
5,906
def _send_result(self, results, single): try: result = results[0] if single else results if isinstance(result, Exception): self.call(self.g.throw(result)) else: self.call(self.g.send(result)) except __HOLE__: pass
StopIteration
dataset/ETHPy150Open truemped/tornadotools/tornadotools/adisp.py/CallbackDispatcher._send_result
5,907
def get_module_by_name(self, _module): """Returns the module with the given name. Args: _module: A str containing the name of the module. Returns: The module.Module with the provided name. Raises: request_info.ModuleDoesNotExistError: The module does not exist. """ try: ...
KeyError
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/tools/devappserver2/dispatcher.py/Dispatcher.get_module_by_name
5,908
def _resolve_target(self, hostname, path): """Returns the module and instance that should handle this request. Args: hostname: A string containing the value of the host header in the request or None if one was not present. path: A string containing the path of the request. Returns: ...
KeyError
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/tools/devappserver2/dispatcher.py/Dispatcher._resolve_target
5,909
def get_os_instance_and_project_id(context, fixed_ip): try: nova = clients.nova(context) os_address = nova.fixed_ips.get(fixed_ip) os_instances = nova.servers.list( search_opts={'hostname': os_address.hostname, 'all_tenants': True}) return...
StopIteration
dataset/ETHPy150Open openstack/ec2-api/ec2api/metadata/api.py/get_os_instance_and_project_id
5,910
def get_os_instance_and_project_id_by_provider_id(context, provider_id, fixed_ip): neutron = clients.neutron(context) os_subnets = neutron.list_subnets(advanced_service_providers=[provider_id], fields=['network_id']) if ...
IndexError
dataset/ETHPy150Open openstack/ec2-api/ec2api/metadata/api.py/get_os_instance_and_project_id_by_provider_id
5,911
def get_namespace_from_filepath(filename): namespace = os.path.dirname(filename).strip(os.sep).replace(os.sep, config.get('namespace_delimiter')) if '{namespace}' in config.get('filename_format'): try: splitted_filename = os.path.basename(filename).split('.') if namespace: ...
ValueError
dataset/ETHPy150Open tuvistavie/python-i18n/i18n/resource_loader.py/get_namespace_from_filepath
5,912
def __getattr__(self, name): """ All attributes of the spatial backend return False by default. """ try: return self.__dict__[name] except __HOLE__: return False
KeyError
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/contrib/gis/db/backend/base.py/BaseSpatialBackend.__getattr__
5,913
def sha256(fileName): """Compute sha256 hash of the specified file""" m = hashlib.sha256() try: fd = open(fileName,"rb") except __HOLE__: print "Unable to open the file in readmode:", fileName return content = fd.readlines() fd.close() for eachLine in content: ...
IOError
dataset/ETHPy150Open smart-classic/smart_server/smart/models/record_object.py/sha256
5,914
@inherit_docstring_from(QueryStrategy) def make_query(self): dataset = self.dataset try: unlabeled_entry_ids, X_pool = zip(*dataset.get_unlabeled_entries()) except __HOLE__: # might be no more unlabeled data left return while self.budget_used < se...
ValueError
dataset/ETHPy150Open ntucllab/libact/libact/query_strategies/active_learning_by_learning.py/ActiveLearningByLearning.make_query
5,915
@staticmethod def tail(fname, window): """Read last N lines from file fname.""" try: f = open(fname, 'r') except __HOLE__, err: if err.errno == errno.ENOENT: return [] else: raise else: BUFSIZ = 1024 ...
IOError
dataset/ETHPy150Open gmcquillan/firetower/firetower/util/log_watcher.py/LogWatcher.tail
5,916
def __init__(self, *args, **kwargs): super(AdminParametersForm, self).__init__(*args, **kwargs) self.field_widths = { "default_domain_quota": 2 } hide_fields = False dpath = None code, output = exec_cmd("which dovecot") if not code: dpath =...
OSError
dataset/ETHPy150Open tonioo/modoboa/modoboa/admin/app_settings.py/AdminParametersForm.__init__
5,917
def update(dest, upd, recursive_update=True, merge_lists=False): ''' Recursive version of the default dict.update Merges upd recursively into dest If recursive_update=False, will use the classic dict.update, or fall back on a manual merge (helpful for non-dict types like FunctionWrapper) If m...
AttributeError
dataset/ETHPy150Open saltstack/salt/salt/utils/dictupdate.py/update
5,918
def test_small_verbosedict(): expected_string = ("You tried to access the key 'b' " "which does not exist. " "The extant keys are: ['a']") dd = core.verbosedict() dd['a'] = 1 assert_equal(dd['a'], 1) try: dd['b'] except __HOLE__ as e: ...
KeyError
dataset/ETHPy150Open scikit-beam/scikit-beam/skbeam/core/tests/test_utils.py/test_small_verbosedict
5,919
def test_large_verbosedict(): expected_sting = ("You tried to access the key 'a' " "which does not exist. There are 100 " "extant keys, which is too many to show you") dd = core.verbosedict() for j in range(100): dd[j] = j # test success for j in...
KeyError
dataset/ETHPy150Open scikit-beam/scikit-beam/skbeam/core/tests/test_utils.py/test_large_verbosedict
5,920
def test_subtract_reference_images(): num_images = 10 img_dims = 200 ones = np.ones((img_dims, img_dims)) img_lst = [ones * _ for _ in range(num_images)] img_arr = np.asarray(img_lst) is_dark_lst = [True] is_dark = False was_dark = True while len(is_dark_lst) < num_images: if...
TypeError
dataset/ETHPy150Open scikit-beam/scikit-beam/skbeam/core/tests/test_utils.py/test_subtract_reference_images
5,921
def test_img_to_relative_xyi(random_seed=None): from skbeam.core.utils import img_to_relative_xyi # make the RNG deterministic if random_seed is not None: np.random.seed(42) # set the maximum image dims maxx = 2000 maxy = 2000 # create a randomly sized image nx = int(np.random.ra...
AssertionError
dataset/ETHPy150Open scikit-beam/scikit-beam/skbeam/core/tests/test_utils.py/test_img_to_relative_xyi
5,922
def write(self, payload): try: NailgunProtocol.write_chunk(self._socket, self._chunk_type, payload) except __HOLE__ as e: # If the remote client disconnects and we try to perform a write (e.g. socket.send/sendall), # an 'error: [Errno 32] Broken pipe' exception can be thrown. Setting mask_brok...
IOError
dataset/ETHPy150Open pantsbuild/pants/src/python/pants/java/nailgun_io.py/NailgunStreamWriter.write
5,923
def fmatch_best(needle, haystack, min_ratio=0.6): try: return sorted( fmatch_iter(needle, haystack, min_ratio), reverse=True, )[0][1] except __HOLE__: pass
IndexError
dataset/ETHPy150Open celery/kombu/kombu/utils/text.py/fmatch_best
5,924
def get_category(self, slug): """ Get the category object """ try: return get_category_for_slug(slug) except __HOLE__ as e: raise Http404(str(e))
ObjectDoesNotExist
dataset/ETHPy150Open edoburu/django-fluent-blogs/fluent_blogs/views/entries.py/EntryCategoryArchive.get_category
5,925
def __new__(cls, *uris, **settings): address = register_server(*uris, **settings) http_uri = address.http_uri("/") try: inst = cls.__instances[address] except __HOLE__: inst = super(DBMS, cls).__new__(cls) inst.address = address inst.__remo...
KeyError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/database/__init__.py/DBMS.__new__
5,926
def __eq__(self, other): try: return remote(self) == remote(other) except __HOLE__: return False
AttributeError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/database/__init__.py/DBMS.__eq__
5,927
def _bean_dict(self, name): info = Resource(remote(self).uri.string + "db/manage/server/jmx/domain/org.neo4j").get().content raw_config = [b for b in info["beans"] if b["name"].endswith("name=%s" % name)][0] d = {} for attribute in raw_config["attributes"]: name = attribute["...
ValueError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/database/__init__.py/DBMS._bean_dict
5,928
def __new__(cls, *uris, **settings): database = settings.pop("database", "data") address = register_server(*uris, **settings) key = (cls, address, database) try: inst = cls.__instances[key] except __HOLE__: inst = super(Graph, cls).__new__(cls) ...
KeyError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/database/__init__.py/Graph.__new__
5,929
def node(self, id_): """ Fetch a node by ID. This method creates an object representing the remote node with the ID specified but fetches no data from the server. For this reason, there is no guarantee that the entity returned actually exists. :param id_: """ res...
KeyError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/database/__init__.py/Graph.node
5,930
def pull(self, subgraph): """ Pull data to one or more entities from their remote counterparts. :param subgraph: the collection of nodes and relationships to pull """ try: subgraph.__db_pull__(self) except __HOLE__: raise TypeError("No method defined to p...
AttributeError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/database/__init__.py/Graph.pull
5,931
def push(self, subgraph): """ Push data from one or more entities to their remote counterparts. :param subgraph: the collection of nodes and relationships to push """ try: subgraph.__db_push__(self) except __HOLE__: raise TypeError("No method defined to p...
AttributeError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/database/__init__.py/Graph.push
5,932
def relationship(self, id_): """ Fetch a relationship by ID. :param id_: """ resource = remote(self).resolve("relationship/" + str(id_)) uri_string = resource.uri.string try: return Relationship.cache[uri_string] except __HOLE__: relations...
KeyError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/database/__init__.py/Graph.relationship
5,933
def fetch(self): try: return self.buffer.popleft() except __HOLE__: if self.loaded: return None else: self.transaction.process() return self.fetch()
IndexError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/database/__init__.py/HTTPDataSource.fetch
5,934
def load(self, data): assert not self.loaded try: entities = self.transaction.entities.popleft() except (__HOLE__, IndexError): entities = {} self._keys = keys = tuple(data["columns"]) hydrate = self.graph._hydrate for record in data["data"]: ...
AttributeError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/database/__init__.py/HTTPDataSource.load
5,935
def fetch(self): try: return self.buffer.popleft() except __HOLE__: if self.loaded: return None else: self.connection.send() while not self.buffer and not self.loaded: self.connection.fetch() ...
IndexError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/database/__init__.py/BoltDataSource.fetch
5,936
def create(self, subgraph): """ Create remote nodes and relationships that correspond to those in a local subgraph. Any entities in *subgraph* that are already bound to remote entities will remain unchanged, those which are not will become bound to their newly-created counterparts. ...
AttributeError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/database/__init__.py/Transaction.create
5,937
def degree(self, subgraph): """ Return the total number of relationships attached to all nodes in a subgraph. :param subgraph: a :class:`.Node`, :class:`.Relationship` or other :class:`.Subgraph` :returns: the total number of distinct relationships """ ...
AttributeError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/database/__init__.py/Transaction.degree
5,938
def delete(self, subgraph): """ Delete the remote nodes and relationships that correspond to those in a local subgraph. :param subgraph: a :class:`.Node`, :class:`.Relationship` or other :class:`.Subgraph` """ try: subgraph.__db_delete__(self) ...
AttributeError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/database/__init__.py/Transaction.delete
5,939
def exists(self, subgraph): """ Determine whether one or more graph entities all exist within the database. Note that if any nodes or relationships in *subgraph* are not bound to remote counterparts, this method will return ``False``. :param subgraph: a :class:`.Node`, :class:`.Relation...
AttributeError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/database/__init__.py/Transaction.exists
5,940
def merge(self, subgraph, primary_label=None, primary_key=None): """ Merge nodes and relationships from a local subgraph into the database. Each node and relationship is merged independently, with nodes merged first and relationships merged second. For each node, the merge is carried ou...
AttributeError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/database/__init__.py/Transaction.merge
5,941
def separate(self, subgraph): """ Delete the remote relationships that correspond to those in a local subgraph. This leaves any nodes untouched. :param subgraph: a :class:`.Node`, :class:`.Relationship` or other :class:`.Subgraph` """ try: subg...
AttributeError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/database/__init__.py/Transaction.separate
5,942
def run(self, statement, parameters=None, **kwparameters): self._assert_unfinished() connection = self.session.connection try: entities = self.entities.popleft() except __HOLE__: entities = {} source = BoltDataSource(connection, entities, remote(self.graph...
IndexError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/database/__init__.py/BoltTransaction.run
5,943
def evaluate(self, field=0): """ Return the value of the first field from the next record (or the value of another field if explicitly specified). This method attempts to move the cursor one step forward and, if successful, selects and returns an individual value from the new cu...
IndexError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/database/__init__.py/Cursor.evaluate
5,944
def __getitem__(self, item): if isinstance(item, string): try: return tuple.__getitem__(self, self.__keys.index(item)) except __HOLE__: raise KeyError(item) elif isinstance(item, slice): return self.__class__(self.__keys[item.start:item...
ValueError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/database/__init__.py/Record.__getitem__
5,945
def touchopen(filename, *args, **kwargs): try: os.remove(filename) except __HOLE__: pass open(filename, "a").close() # "touch" file return open(filename, *args, **kwargs) # The constrained memory should have no more than 1024 cells
OSError
dataset/ETHPy150Open crista/exercises-in-programming-style/01-good-old-times/tf-01.py/touchopen
5,946
def get_backend_register(self, k, default=None): try: return json.loads(self.backend_register).get(k, default) except __HOLE__: return default
AttributeError
dataset/ETHPy150Open open-cloud/xos/xos/core/models/plcorebase.py/PlModelMixIn.get_backend_register
5,947
def set_backend_register(self, k, v): br = {} try: br=json.loads(self.backend_register) except __HOLE__: br={} br[k] = v self.backend_register = json.dumps(br)
AttributeError
dataset/ETHPy150Open open-cloud/xos/xos/core/models/plcorebase.py/PlModelMixIn.set_backend_register
5,948
def get_backend_details(self): try: scratchpad = json.loads(self.backend_register) except AttributeError: return (None, None, None, None) try: exponent = scratchpad['exponent'] except __HOLE__: exponent = None try: las...
KeyError
dataset/ETHPy150Open open-cloud/xos/xos/core/models/plcorebase.py/PlModelMixIn.get_backend_details
5,949
def delete(self, *args, **kwds): # so we have something to give the observer purge = kwds.get('purge',False) if purge: del kwds['purge'] silent = kwds.get('silent',False) if silent: del kwds['silent'] try: purge = purge or observer_disa...
NameError
dataset/ETHPy150Open open-cloud/xos/xos/core/models/plcorebase.py/PlCoreBase.delete
5,950
def test_string(): """ Dumping and loading a string """ filename, mode = 'test.h5', 'w' string_obj = "The quick brown fox jumps over the lazy dog" dump(string_obj, filename, mode) string_hkl = load(filename) #print "Initial list: %s"%list_obj #print "Unhickled data: %s"%list_hkl try: ...
AssertionError
dataset/ETHPy150Open telegraphic/hickle/tests/test_hickle.py/test_string
5,951
def test_unicode(): """ Dumping and loading a unicode string """ filename, mode = 'test.h5', 'w' u = unichr(233) + unichr(0x0bf2) + unichr(3972) + unichr(6000) dump(u, filename, mode) u_hkl = load(filename) try: assert type(u) == type(u_hkl) == unicode assert u == u_hkl ...
AssertionError
dataset/ETHPy150Open telegraphic/hickle/tests/test_hickle.py/test_unicode
5,952
def test_list(): """ Dumping and loading a list """ filename, mode = 'test.h5', 'w' list_obj = [1, 2, 3, 4, 5] dump(list_obj, filename, mode) list_hkl = load(filename) #print "Initial list: %s"%list_obj #print "Unhickled data: %s"%list_hkl try: assert type(list_obj) == type(lis...
AssertionError
dataset/ETHPy150Open telegraphic/hickle/tests/test_hickle.py/test_list
5,953
def test_set(): """ Dumping and loading a list """ filename, mode = 'test.h5', 'w' list_obj = set([1, 0, 3, 4.5, 11.2]) dump(list_obj, filename, mode) list_hkl = load(filename) #print "Initial list: %s"%list_obj #print "Unhickled data: %s"%list_hkl try: assert type(list_obj) ==...
AssertionError
dataset/ETHPy150Open telegraphic/hickle/tests/test_hickle.py/test_set
5,954
def test_numpy(): """ Dumping and loading numpy array """ filename, mode = 'test.h5', 'w' dtypes = ['float32', 'float64', 'complex64', 'complex128'] for dt in dtypes: array_obj = np.ones(8, dtype=dt) dump(array_obj, filename, mode) array_hkl = load(filename) try: ...
AssertionError
dataset/ETHPy150Open telegraphic/hickle/tests/test_hickle.py/test_numpy
5,955
def test_masked(): """ Test masked numpy array """ filename, mode = 'test.h5', 'w' a = np.ma.array([1,2,3,4], dtype='float32', mask=[0,1,0,0]) dump(a, filename, mode) a_hkl = load(filename) try: assert a_hkl.dtype == a.dtype assert np.all((a_hkl, a)) os.remo...
AssertionError
dataset/ETHPy150Open telegraphic/hickle/tests/test_hickle.py/test_masked
5,956
def test_dict(): """ Test dictionary dumping and loading """ filename, mode = 'test.h5', 'w' dd = { 'name' : 'Danny', 'age' : 28, 'height' : 6.1, 'dork' : True, 'nums' : [1, 2, 3], 'narr' : np.array([1,2,3]), #'unic' : u'dan[at]thetel...
AssertionError
dataset/ETHPy150Open telegraphic/hickle/tests/test_hickle.py/test_dict
5,957
def test_compression(): """ Test compression on datasets""" filename, mode = 'test.h5', 'w' dtypes = ['int32', 'float32', 'float64', 'complex64', 'complex128'] comps = [None, 'gzip', 'lzf'] for dt in dtypes: for cc in comps: array_obj = np.ones(32768, dtype=dt) ...
AssertionError
dataset/ETHPy150Open telegraphic/hickle/tests/test_hickle.py/test_compression
5,958
def test_masked_dict(): """ Test dictionaries with masked arrays """ filename, mode = 'test.h5', 'w' dd = { "data" : np.ma.array([1,2,3], mask=[True, False, False]), "data2" : np.array([1,2,3,4,5]) } dump(dd, filename, mode) dd_hkl = load(filename) for k in dd.keys()...
AssertionError
dataset/ETHPy150Open telegraphic/hickle/tests/test_hickle.py/test_masked_dict
5,959
def test_track_times(): """ Verify that track_times = False produces identical files """ hashes = [] for obj, filename, mode, kwargs in DUMP_CACHE: if isinstance(filename, hickle.H5FileWrapper): filename = str(filename.file_name) kwargs['track_times'] = False caching_dump...
AssertionError
dataset/ETHPy150Open telegraphic/hickle/tests/test_hickle.py/test_track_times
5,960
def test_comp_kwargs(): """ Test compression with some kwargs for shuffle and chunking """ filename, mode = 'test.h5', 'w' dtypes = ['int32', 'float32', 'float64', 'complex64', 'complex128'] comps = [None, 'gzip', 'lzf'] chunks = [(100, 100), (250, 250)] shuffles = [True, False] scaleoffse...
AssertionError
dataset/ETHPy150Open telegraphic/hickle/tests/test_hickle.py/test_comp_kwargs
5,961
def run_file_cleanup(): """ Clean up temp files """ for filename in ('test.hdf', 'test.hkl', 'test.h5'): try: os.remove(filename) except __HOLE__: pass
OSError
dataset/ETHPy150Open telegraphic/hickle/tests/test_hickle.py/run_file_cleanup
5,962
def test_list_long_type(): """ Check long comes back out as a long """ filename, mode = 'test.h5', 'w' list_obj = [1L, 2L, 3L, 4L, 5L] dump(list_obj, filename, mode) list_hkl = load(filename) #print "Initial list: %s"%list_obj #print "Unhickled data: %s"%list_hkl try: assert ty...
AssertionError
dataset/ETHPy150Open telegraphic/hickle/tests/test_hickle.py/test_list_long_type
5,963
def test_list_order(): """ https://github.com/telegraphic/hickle/issues/26 """ d = [np.arange(n + 1) for n in range(20)] hickle.dump(d, 'test.h5') d_hkl = hickle.load('test.h5') try: for ii, xx in enumerate(d): assert d[ii].shape == d_hkl[ii].shape for ii, xx in enum...
AssertionError
dataset/ETHPy150Open telegraphic/hickle/tests/test_hickle.py/test_list_order
5,964
def test_legacy_hickles(): try: a = load("hickle_1_1_0.hkl") b = load("hickle_1_3_0.hkl") import h5py d = h5py.File("hickle_1_1_0.hkl")["data"]["a"][:] d2 = h5py.File("hickle_1_3_0.hkl")["data"]["a"][:] assert np.allclose(d, a["a"]) assert np.allclos...
IOError
dataset/ETHPy150Open telegraphic/hickle/tests/test_hickle.py/test_legacy_hickles
5,965
def __validate_simple_subfield(self, parameter, field, segment_list, _segment_index=0): """Verifies that a proposed subfield actually exists and is a simple field. Here, simple means it is not a MessageField (nested). Args: parameter: String; the '.' delimited name o...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/ext/endpoints/api_config.py/ApiConfigGenerator.__validate_simple_subfield
5,966
def get_setting(key): """ Get setting values from CONF_FILE :param key: :return: """ try: with open(CONF_FILE) as cf: settings = json.load(cf) except __HOLE__: return None if key in settings.keys(): return settings[key] return None # pragma: no ...
IOError
dataset/ETHPy150Open dwighthubbard/hostlists/hostlists/hostlists.py/get_setting
5,967
def multikeysort(items, columns): comparers = [ ((operator.itemgetter(col[1:].strip()), -1) if col.startswith('-') else (operator.itemgetter(col.strip()), 1)) for col in columns ] def comparer(left, right): for fn, mult in comparers: try: result = cmp_compat(fn(l...
KeyError
dataset/ETHPy150Open dwighthubbard/hostlists/hostlists/hostlists.py/multikeysort
5,968
def compress(hostnames): """ Compress a list of host into a more compact range representation """ domain_dict = {} result = [] for host in hostnames: if '.' in host: domain = '.'.join(host.split('.')[1:]) else: domain = '' try: domain_d...
KeyError
dataset/ETHPy150Open dwighthubbard/hostlists/hostlists/hostlists.py/compress
5,969
def compress_domain(hostnames): """ Compress a list of hosts in a domain into a more compact representation """ hostnames.sort() prev_dict = {'prefix': "", 'suffix': '', 'number': 0} items = [] items_block = [] new_hosts = [] for host in hostnames: try: parsed_dic...
AttributeError
dataset/ETHPy150Open dwighthubbard/hostlists/hostlists/hostlists.py/compress_domain
5,970
def clean_fields(self, exclude=None): """ This is an override of the default model clean_fields method. Essentially, in addition to validating the fields, this method validates the :class:`Template` instance that is used to render this :class:`Page`. This is useful for catching template errors before they show up a...
ValidationError
dataset/ETHPy150Open ithinksw/philo/philo/models/pages.py/Page.clean_fields
5,971
def __init__(self, coord=None, mode='continuous'): super(Coordinate, self).__init__() if coord is None: self.value = 0 return if not isinstance(coord, list) and not isinstance(coord, str): raise TypeError("Coordinates parameter must be a list with coordinates...
ValueError
dataset/ETHPy150Open neuropoly/spinalcordtoolbox/scripts/msct_types.py/Coordinate.__init__
5,972
@staticmethod def datetime_from_string(value): try: return datetime.datetime.strptime(value, PINBOARD_DATETIME_FORMAT) except __HOLE__: return datetime.datetime.strptime(value, PINBOARD_ALTERNATE_DATETIME_FORMAT)
ValueError
dataset/ETHPy150Open lionheart/pinboard.py/pinboard/pinboard.py/Pinboard.datetime_from_string
5,973
def __init__(self, dbname,overwrite=False): self.dbname = dbname if overwrite: try: os.remove( dbname ) except __HOLE__: pass self.conn = sqlite3.connect(dbname) if overwrite: self.setup()
OSError
dataset/ETHPy150Open bmander/graphserver/pygs/graphserver/ext/osm/profiledb.py/ProfileDB.__init__
5,974
def get(self, id): c = self.get_cursor() c.execute( "SELECT profile FROM profiles WHERE id = ?", (id,) ) try: (profile,) = c.next() except __HOLE__: return None finally: c.close() return unpack_coords( profile )
StopIteration
dataset/ETHPy150Open bmander/graphserver/pygs/graphserver/ext/osm/profiledb.py/ProfileDB.get
5,975
def _filter_drag_end(self, event): source = self.filterTreeWidget.currentItem() source_name = source.text(0) target = self.filterTreeWidget.itemAt(event.pos()) source_top, source_group = self._get_filter_item_coords(source) parent = target.parent() if parent: ...
ValueError
dataset/ETHPy150Open rproepp/spykeviewer/spykeviewer/ui/filter_dock.py/FilterDock._filter_drag_end
5,976
def __init__(self, *args, **kwargs): dispatcher.send(signal=signals.pre_init, sender=self.__class__, args=args, kwargs=kwargs) # There is a rather weird disparity here; if kwargs, it's set, then args # overrides it. It should be one or the other; don't duplicate the work # The ...
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/db/models/base.py/Model.__init__
5,977
def _collect_sub_objects(self, seen_objs): """ Recursively populates seen_objs with all objects related to this object. When done, seen_objs will be in the format: {model_class: {pk_val: obj, pk_val: obj, ...}, model_class: {pk_val: obj, pk_val: obj, ...}, ...} "...
ObjectDoesNotExist
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/db/models/base.py/Model._collect_sub_objects
5,978
def _get_next_or_previous_by_FIELD(self, field, is_next, **kwargs): op = is_next and '>' or '<' where = '(%s %s %%s OR (%s = %%s AND %s.%s %s %%s))' % \ (backend.quote_name(field.column), op, backend.quote_name(field.column), backend.quote_name(self._meta.db_table), backend.quote...
IndexError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/db/models/base.py/Model._get_next_or_previous_by_FIELD
5,979
def _save_FIELD_file(self, field, filename, raw_contents, save=True): directory = field.get_directory_name() try: # Create the date-based directory if it doesn't exist. os.makedirs(os.path.join(settings.MEDIA_ROOT, directory)) except __HOLE__: # Directory probably already exists. ...
OSError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/db/models/base.py/Model._save_FIELD_file
5,980
def GetFromStore(self, file_path): """Retrieve file from zip files. Get the file from the source, it must not have been in the memcache. If possible, we'll use the zip file index to quickly locate where the file should be found. (See MapToFileArchive documentation for assumptions about file orderin...
KeyError
dataset/ETHPy150Open aehlke/manabi/apps/dojango/appengine/memcache_zipserve.py/MemcachedZipHandler.GetFromStore
5,981
def LoadZipFile(self, zipfilename): """Convenience method to load zip file. Just a convenience method to load the zip file from the data store. This is useful if we ever want to change data stores and also as a means of dependency injection for testing. This method will look at our file cache first...
RuntimeError
dataset/ETHPy150Open aehlke/manabi/apps/dojango/appengine/memcache_zipserve.py/MemcachedZipHandler.LoadZipFile
5,982
def handle_port(self, context, data): """Notify all agent extensions to handle port.""" for extension in self: try: extension.obj.handle_port(context, data) # TODO(QoS) add agent extensions exception and catch them here except __HOLE__: ...
AttributeError
dataset/ETHPy150Open openstack/neutron/neutron/agent/l2/extensions/manager.py/AgentExtensionsManager.handle_port
5,983
def delete_port(self, context, data): """Notify all agent extensions to delete port.""" for extension in self: try: extension.obj.delete_port(context, data) # TODO(QoS) add agent extensions exception and catch them here # instead of AttributeError ...
AttributeError
dataset/ETHPy150Open openstack/neutron/neutron/agent/l2/extensions/manager.py/AgentExtensionsManager.delete_port
5,984
@never_cache def password_reset_confirm(request, uidb64=None, token=None, template_name='registration/password_reset_confirm.html', token_generator=default_token_generator, set_password_form=SetPasswordForm, post...
TypeError
dataset/ETHPy150Open adieu/django-nonrel/django/contrib/auth/views.py/password_reset_confirm
5,985
def dict_for_mongo(d): for key, value in d.items(): if type(value) == list: value = [dict_for_mongo(e) if type(e) == dict else e for e in value] elif type(value) == dict: value = dict_for_mongo(value) elif key == '_id': try: ...
ValueError
dataset/ETHPy150Open kobotoolbox/kobocat/onadata/apps/viewer/models/parsed_instance.py/dict_for_mongo
5,986
def build_suite(app_module): "Create a complete Django test suite for the provided application module" suite = unittest.TestSuite() # Load unit and doctests in the models.py file suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(app_module)) try: suite.addTest(doctest.DocTest...
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/test/simple.py/build_suite
5,987
def main(argv): parser = ArgumentParser(usage=__doc__.lstrip()) parser.add_argument("--verbose", "-v", action="count", default=1, help="more verbosity") parser.add_argument("--no-build", "-n", action="store_true", default=False, help="do not build the project ...
AttributeError
dataset/ETHPy150Open scipy/scipy/runtests.py/main
5,988
def lcov_generate(): try: os.unlink(LCOV_OUTPUT_FILE) except __HOLE__: pass try: shutil.rmtree(LCOV_HTML_DIR) except OSError: pass print("Capturing lcov info...") subprocess.call(['lcov', '-q', '-c', '-d', os.path.join(ROOT_DIR, 'build'), '-b', ROOT_DIR...
OSError
dataset/ETHPy150Open scipy/scipy/runtests.py/lcov_generate
5,989
def _wrap_writer_for_text(fp, encoding): try: fp.write('') except __HOLE__: fp = io.TextIOWrapper(fp, encoding) return fp
TypeError
dataset/ETHPy150Open pallets/flask/flask/json.py/_wrap_writer_for_text
5,990
def run(): """This client pushes PE Files -> ELS Indexer.""" # Grab server args args = client_helper.grab_server_args() # Start up workbench connection workbench = zerorpc.Client(timeout=300, heartbeat=60) workbench.connect('tcp://'+args['server']+':'+args['port']) # Test out PEFile -...
TypeError
dataset/ETHPy150Open SuperCowPowers/workbench/workbench/clients/pe_indexer.py/run
5,991
def install_grabix(env): """a wee tool for random access into BGZF files https://github.com/arq5x/grabix """ version = "0.1.6" revision = "ba792bc872d38d3cb5a69b2de00e39a6ac367d69" try: uptodate = versioncheck.up_to_date(env, "grabix", version, stdout_flag="version:") # Old versions ...
IOError
dataset/ETHPy150Open chapmanb/cloudbiolinux/cloudbio/custom/bio_nextgen.py/install_grabix
5,992
def get_default_mrcluster(): """ Get the default JT (not necessarily HA). """ global MR_CACHE global MR_NAME_CACHE try: all_mrclusters() return MR_CACHE.get(MR_NAME_CACHE) except __HOLE__: # Return an arbitrary cluster candidates = all_mrclusters() if candidates: return candidat...
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/libs/hadoop/src/hadoop/cluster.py/get_default_mrcluster
5,993
def get_default_yarncluster(): """ Get the default RM (not necessarily HA). """ global MR_NAME_CACHE try: return conf.YARN_CLUSTERS[MR_NAME_CACHE] except __HOLE__: return get_yarn()
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/libs/hadoop/src/hadoop/cluster.py/get_default_yarncluster
5,994
def tearDown(self): try: os.remove('SLSQP.out') except OSError: pass try: os.remove('SNOPT_print.out') os.remove('SNOPT_summary.out') except __HOLE__: pass
OSError
dataset/ETHPy150Open OpenMDAO/OpenMDAO/mpitest/test_mpi_opt.py/TestMPIOpt.tearDown
5,995
def tearDown(self): try: os.remove('SLSQP.out') except OSError: pass try: os.remove('SNOPT_print.out') os.remove('SNOPT_summary.out') except __HOLE__: pass
OSError
dataset/ETHPy150Open OpenMDAO/OpenMDAO/mpitest/test_mpi_opt.py/ParallelMPIOptAsym.tearDown
5,996
def tearDown(self): try: os.remove('SLSQP.out') except OSError: pass try: os.remove('SNOPT_print.out') os.remove('SNOPT_summary.out') except __HOLE__: pass
OSError
dataset/ETHPy150Open OpenMDAO/OpenMDAO/mpitest/test_mpi_opt.py/ParallelMPIOptPromoted.tearDown
5,997
def tearDown(self): try: os.remove('SLSQP.out') except OSError: pass try: os.remove('SNOPT_print.out') os.remove('SNOPT_summary.out') except __HOLE__: pass
OSError
dataset/ETHPy150Open OpenMDAO/OpenMDAO/mpitest/test_mpi_opt.py/ParallelMPIOpt.tearDown
5,998
def create(self, req, body): parser = req.get_parser()(req.headers, req.body) scheme = {"category": storage.StorageResource.kind} obj = parser.parse() validator = occi_validator.Validator(obj) validator.validate(scheme) attrs = obj.get("attributes", {}) name = at...
KeyError
dataset/ETHPy150Open openstack/ooi/ooi/api/storage.py/Controller.create
5,999
def service(self): '''Handle a request ''' # The key is the request path key = self.request.url.path.strip('/') # Set content-type self.response.headers = ['Content-Type: application/json'] # Standard reply rsp = '{"status": "OK"}' if not key: # Empty key means l...
KeyError
dataset/ETHPy150Open rsms/smisk/examples/core/key-value-store/app.py/KeyValueStore.service