Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
8,500 | def get_instance_scenario(self, instance_id, tenant_id=None, verbose=False):
'''Obtain the instance information, filtering by one or several of the tenant, uuid or name
instance_id is the uuid or the name if it is not a valid uuid format
Only one instance must mutch the filtering or an error is ... | AttributeError | dataset/ETHPy150Open nfvlabs/openmano/openmano/nfvo_db.py/nfvo_db.get_instance_scenario |
8,501 | def delete_instance_scenario(self, instance_id, tenant_id=None):
'''Deletes a instance_Scenario, filtering by one or serveral of the tenant, uuid or name
instance_id is the uuid or the name if it is not a valid uuid format
Only one instance_scenario must mutch the filtering or an error is return... | AttributeError | dataset/ETHPy150Open nfvlabs/openmano/openmano/nfvo_db.py/nfvo_db.delete_instance_scenario |
8,502 | def update_datacenter_nets(self, datacenter_id, new_net_list=[]):
''' Removes the old and adds the new net list at datacenter list for one datacenter.
Attribute
datacenter_id: uuid of the datacenter to act upon
table: table where to insert
new_net_list: the new value... | AttributeError | dataset/ETHPy150Open nfvlabs/openmano/openmano/nfvo_db.py/nfvo_db.update_datacenter_nets |
8,503 | def CreateTemporaryDirectories():
"""Creates the temporary sub-directories needed by the current run."""
for path in (GetRunDirPath(), GetVersionDirPath()):
try:
os.makedirs(path)
except __HOLE__:
if not os.path.isdir(path):
raise | OSError | dataset/ETHPy150Open GoogleCloudPlatform/PerfKitBenchmarker/perfkitbenchmarker/temp_dir.py/CreateTemporaryDirectories |
8,504 | def register_middleware(self, middleware_instance):
registered_count = 0
self._middlewares.append(middleware_instance)
for hook in self._hooks.keys():
functor = getattr(middleware_instance, hook, None)
if functor is None:
try:
functor =... | AttributeError | dataset/ETHPy150Open 0rpc/zerorpc-python/zerorpc/context.py/Context.register_middleware |
8,505 | @ValidateLarchPlugin
def read_gsexdi(fname, _larch=None, nmca=4, bad=None, **kws):
"""Read GSE XDI Scan Data to larch group,
summing ROI data for MCAs and apply deadtime corrections
"""
group = _larch.symtable.create_group()
group.__name__ ='GSE XDI Data file %s' % fname
xdi = XDIFile(str(fname)... | AttributeError | dataset/ETHPy150Open xraypy/xraylarch/plugins/io/gse_xdiscan.py/read_gsexdi |
8,506 | @internationalizeDocstring
def todo(self, irc, msg, args, user, taskid):
"""[<username>] [<task id>]
Retrieves a task for the given task id. If no task id is given, it
will return a list of task ids that that user has added to their todo
list.
"""
try:
u... | KeyError | dataset/ETHPy150Open ProgVal/Limnoria/plugins/Todo/plugin.py/Todo.todo |
8,507 | def get_delete_permission(opts):
try:
from django.contrib.auth import get_permission_codename # flake8: noqa
return '%s.%s' % (opts.app_label,
get_permission_codename('delete', opts))
except __HOLE__:
return '%s.%s' % (opts.app_label,
... | ImportError | dataset/ETHPy150Open divio/django-filer/filer/utils/compatibility.py/get_delete_permission |
8,508 | def optimize(self, optimizer=None, start=None, **kwargs):
self._IN_OPTIMIZATION_ = True
if self.mpi_comm==None:
super(SparseGP_MPI, self).optimize(optimizer,start,**kwargs)
elif self.mpi_comm.rank==0:
super(SparseGP_MPI, self).optimize(optimizer,start,**kwargs)
... | ValueError | dataset/ETHPy150Open SheffieldML/GPy/GPy/core/sparse_gp_mpi.py/SparseGP_MPI.optimize |
8,509 | def __init__(self, initializer=None, age=None, payload=None, **kwarg):
super(GrrMessage, self).__init__(initializer=initializer, age=age, **kwarg)
if payload is not None:
self.payload = payload
# If the payload has a priority, the GrrMessage inherits it.
try:
self.priority = payload.... | AttributeError | dataset/ETHPy150Open google/grr/grr/lib/rdfvalues/flows.py/GrrMessage.__init__ |
8,510 | def __init__(self, layers, batch_size=None, input_space=None,
input_source='features', target_source='targets',
nvis=None, seed=None, layer_name=None, monitor_targets=True,
**kwargs):
super(MLP, self).__init__(**kwargs)
self.seed = seed
assert... | ValueError | dataset/ETHPy150Open lisa-lab/pylearn2/pylearn2/models/mlp.py/MLP.__init__ |
8,511 | def assert_rel_error(test_case, actual, desired, tolerance):
"""
Determine that the relative error between `actual` and `desired`
is within `tolerance`. If `desired` is zero, then use absolute error.
test_case: :class:`unittest.TestCase`
TestCase instance used for assertions.
actual: float... | IndexError | dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.util/src/openmdao/util/testutil.py/assert_rel_error |
8,512 | def from_content_disposition(self, content_disposition):
try:
filename = to_native_str(content_disposition,
encoding='latin-1', errors='replace').split(';')[1].split('=')[1]
filename = filename.strip('"\'')
return self.from_filename(filename)
except __... | IndexError | dataset/ETHPy150Open scrapy/scrapy/scrapy/responsetypes.py/ResponseTypes.from_content_disposition |
8,513 | def getdoc(object):
"""Get the documentation string for an object.
All tabs are expanded to spaces. To clean up docstrings that are
indented to line up with blocks of code, any whitespace than can be
uniformly removed from the second line onwards is removed."""
try:
doc = object.__doc__
... | AttributeError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/inspect.py/getdoc |
8,514 | def getmodule(object, _filename=None):
"""Return the module an object was defined in, or None if not found."""
if ismodule(object):
return object
if hasattr(object, '__module__'):
return sys.modules.get(object.__module__)
# Try the filename to modulename cache
if _filename is not Non... | TypeError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/inspect.py/getmodule |
8,515 | def getcomments(object):
"""Get lines of comments immediately preceding an object's source code.
Returns None when source can't be found.
"""
try:
lines, lnum = findsource(object)
except (IOError, __HOLE__):
return None
if ismodule(object):
# Look for a comment block at... | TypeError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/inspect.py/getcomments |
8,516 | def getframeinfo(frame, context=1):
"""Get information about a frame or traceback object.
A tuple of five things is returned: the filename, the line number of
the current line, the function name, a list of lines of context from
the source code, and the index of the current line within that list.
Th... | IOError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/inspect.py/getframeinfo |
8,517 | def DeleteBlob(self, blob_key):
"""Delete blob content."""
try:
del self._blobs[blobstore.BlobKey(unicode(blob_key))]
except __HOLE__:
pass | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/blobstore/dict_blob_storage.py/DictBlobStorage.DeleteBlob |
8,518 | def run(self):
import sys, subprocess
try:
from py import test as pytest
except __HOLE__:
raise Exception('Running tests requires pytest.')
errno = subprocess.call([sys.executable, '-m', 'py.test'])
raise SystemExit(errno) | ImportError | dataset/ETHPy150Open wickman/pystachio/setup.py/PyTest.run |
8,519 | def __setitem__(self, key, value):
try:
bnch = super(Header, self).__getitem__(key)
bnch.value = value
except __HOLE__:
bnch = Bunch.Bunch(key=key, value=value, comment='')
self.keyorder.append(key)
super(Header, self).__setitem__(key, bnch)
... | KeyError | dataset/ETHPy150Open ejeschke/ginga/ginga/BaseImage.py/Header.__setitem__ |
8,520 | def set_card(self, key, value, comment=None):
try:
bnch = super(Header, self).__getitem__(key)
bnch.value = value
if not (comment is None):
bnch.comment = comment
except __HOLE__:
if comment is None:
comment = ''
... | KeyError | dataset/ETHPy150Open ejeschke/ginga/ginga/BaseImage.py/Header.set_card |
8,521 | def get(self, key, alt=None):
try:
return self.__getitem__(key)
except __HOLE__:
return alt | KeyError | dataset/ETHPy150Open ejeschke/ginga/ginga/BaseImage.py/Header.get |
8,522 | def execute(self, args):
# pylint: disable=unpacking-non-sequence
ext_loader = ExtensionLoader(packages=settings.extension_packages, paths=settings.extension_paths)
extension = ext_loader.get_extension_class(args.name)
out = StringIO()
term_width, term_height = get_terminal_size(... | OSError | dataset/ETHPy150Open ARM-software/workload-automation/wlauto/commands/show.py/ShowCommand.execute |
8,523 | def createActor(self, newActorClass, targetActorRequirements, globalName,
sourceHash = None):
naa = self._addrManager.createLocalAddress()
if getattr(self, '_exiting', False):
return naa
if not globalName:
try:
self._startChildActor(na... | ImportError | dataset/ETHPy150Open godaddy/Thespian/thespian/system/actorManager.py/ActorManager.createActor |
8,524 | def manual_run():
errors, failed, count = 0, 0, 0
for test, in all_tests(skip_known_issues=False):
count += 1
print(test.description)
try:
test()
print "PASSED"
except __HOLE__, e:
failed += 1
print "****FAILED****", e;
exce... | AssertionError | dataset/ETHPy150Open RDFLib/rdflib/test/rdfa/run_w3c_rdfa_testsuite.py/manual_run |
8,525 | def parseColor(self, str):
"""
Handle a single ANSI color sequence
"""
# Drop the trailing 'm'
str = str[:-1]
if not str:
str = '0'
try:
parts = map(int, str.split(';'))
except __HOLE__:
log.msg('Invalid ANSI color seq... | ValueError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/conch/ui/ansi.py/AnsiParser.parseColor |
8,526 | def delegated(func):
"""A delegated method raises AttributeError in the absence of backend
support."""
@wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except __HOLE__:
raise ImplementationError(
"Method '%s' not provide... | KeyError | dataset/ETHPy150Open Toblerity/Shapely/shapely/impl.py/delegated |
8,527 | def __getitem__(self, key):
try:
return self.map[key]
except __HOLE__:
raise ImplementationError(
"Method '%s' not provided by registered "
"implementation '%s'" % (key, self.map)) | KeyError | dataset/ETHPy150Open Toblerity/Shapely/shapely/impl.py/BaseImpl.__getitem__ |
8,528 | @app.route("/length/<int:response_bytes>")
def fix_length_response(response_bytes):
if response_bytes < 1:
raise Exception("Forbidded response length: {0}".format(response_bytes))
try:
response = response_cache[response_bytes]
return response
except __HOLE__:
response = urand... | KeyError | dataset/ETHPy150Open svanoort/python-client-benchmarks/app.py/fix_length_response |
8,529 | @classmethod
def setupClass(cls):
global numpy
global assert_equal
global assert_almost_equal
try:
import numpy
from numpy.testing import assert_equal,assert_almost_equal
except __HOLE__:
raise SkipTest('NumPy not available.') | ImportError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/linalg/tests/test_graphmatrix.py/TestGraphMatrix.setupClass |
8,530 | def setAttributeNS(self, namespaceURI, localName, value):
'''
Keyword arguments:
namespaceURI -- namespace of attribute to create, None is for
attributes in no namespace.
localName -- local name of new attribute
value -- value of new attribute
... | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/SOAPpy/wstools/Utility.py/ElementProxy.setAttributeNS |
8,531 | def parse_exclude_devices(exclude_list):
"""Parse Exclude devices list
parses excluded device list in the form:
dev_name:pci_dev_1;pci_dev_2
@param exclude list: list of string pairs in "key:value" format
the key part represents the network device name
th... | ValueError | dataset/ETHPy150Open openstack/neutron/neutron/plugins/ml2/drivers/mech_sriov/agent/common/config.py/parse_exclude_devices |
8,532 | def handle_errors(callback, parsed=None, out=sys.stderr):
"""Execute the callback, optionally passing it parsed, and return
its return value. If an exception occurs, determine which kind it
is, output an appropriate message, and return the corresponding
error code."""
try:
if parsed:
... | SystemExit | dataset/ETHPy150Open quaddra/provision/provision/config.py/handle_errors |
8,533 | def import_by_path(path):
"""Append the path to sys.path, then attempt to import module with
path's basename, finally making certain to remove appended path.
http://stackoverflow.com/questions/1096216/override-namespace-in-python"""
sys.path.append(os.path.dirname(path))
try:
return __imp... | ImportError | dataset/ETHPy150Open quaddra/provision/provision/config.py/import_by_path |
8,534 | def assert_nodes_equal(nodes1, nodes2):
# Assumes iterables of nodes, or (node,datadict) tuples
nlist1 = list(nodes1)
nlist2 = list(nodes2)
try:
d1 = dict(nlist1)
d2 = dict(nlist2)
except (ValueError, __HOLE__):
d1 = dict.fromkeys(nlist1)
d2 = dict.fromkeys(nlist2)
... | TypeError | dataset/ETHPy150Open networkx/networkx/networkx/testing/utils.py/assert_nodes_equal |
8,535 | def test_keyFlattening(self):
"""
Test that L{KeyFlattener.flatKey} returns the expected keys for format
fields.
"""
def keyFromFormat(format):
for (
literalText,
fieldName,
formatSpec,
conversion,
... | ValueError | dataset/ETHPy150Open twisted/twisted/twisted/logger/test/test_flatten.py/FlatFormattingTests.test_keyFlattening |
8,536 | def save(self):
self._run_callbacks('before_save')
fields_dict = self.fields.as_dict()
try:
# Attempt update
id_ = fields_dict['id']
result = (r.table(self._table).get(id_).replace(r.row
.without(r.row.keys().difference(list(fields_dic... | KeyError | dataset/ETHPy150Open linkyndy/remodel/remodel/models.py/Model.save |
8,537 | def delete(self):
self._run_callbacks('before_delete')
try:
id_ = getattr(self.fields, 'id')
result = r.table(self._table).get(id_).delete().run()
except __HOLE__:
raise OperationError('Cannot delete %r (object not saved or '
... | AttributeError | dataset/ETHPy150Open linkyndy/remodel/remodel/models.py/Model.delete |
8,538 | @dispatch_to_metaclass
def get(self, key, default=None):
try:
return getattr(self.fields, key)
except __HOLE__:
return default | AttributeError | dataset/ETHPy150Open linkyndy/remodel/remodel/models.py/Model.get |
8,539 | def __getitem__(self, key):
try:
return getattr(self.fields, key)
except __HOLE__:
raise KeyError(key) | AttributeError | dataset/ETHPy150Open linkyndy/remodel/remodel/models.py/Model.__getitem__ |
8,540 | def __setitem__(self, key, value):
try:
setattr(self.fields, key, value)
except __HOLE__:
raise KeyError(key) | AttributeError | dataset/ETHPy150Open linkyndy/remodel/remodel/models.py/Model.__setitem__ |
8,541 | def __delitem__(self, key):
try:
delattr(self.fields, key)
except __HOLE__:
raise KeyError(key) | AttributeError | dataset/ETHPy150Open linkyndy/remodel/remodel/models.py/Model.__delitem__ |
8,542 | def __repr__(self):
try:
id_ = self.fields.id
except __HOLE__:
id_ = 'not saved'
return '<%s: %s>' % (self.__class__.__name__, id_) | AttributeError | dataset/ETHPy150Open linkyndy/remodel/remodel/models.py/Model.__repr__ |
8,543 | def get_option_list(self):
option_list = super(CatCommand, self).get_option_list()
try:
__import__('pygments')
option = make_option('-f', '--formatter', action='store',
dest='formatter_name', default='terminal',
help='Pygments specific formatter na... | ImportError | dataset/ETHPy150Open codeinn/vcs/vcs/commands/cat.py/CatCommand.get_option_list |
8,544 | def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
"""Sends PreparedRequest object. Returns Response object.
:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
:param stream: (optional) Whether to stream the request content.
... | TypeError | dataset/ETHPy150Open BergWerkGIS/QGIS-CKAN-Browser/CKAN-Browser/request/adapters.py/HTTPAdapter.send |
8,545 | def solve_univariate_inequality(expr, gen, relational=True):
"""Solves a real univariate inequality.
Examples
========
>>> from sympy.solvers.inequalities import solve_univariate_inequality
>>> from sympy.core.symbol import Symbol
>>> x = Symbol('x')
>>> solve_univariate_inequality(x**2 >... | NotImplementedError | dataset/ETHPy150Open sympy/sympy/sympy/solvers/inequalities.py/solve_univariate_inequality |
8,546 | def _solve_inequality(ie, s):
""" A hacky replacement for solve, since the latter only works for
univariate inequalities. """
expr = ie.lhs - ie.rhs
try:
p = Poly(expr, s)
if p.degree() != 1:
raise NotImplementedError
except (PolynomialError, __HOLE__):
try:
... | NotImplementedError | dataset/ETHPy150Open sympy/sympy/sympy/solvers/inequalities.py/_solve_inequality |
8,547 | def import_string(import_name, silent=False):
"""Imports an object based on a string. If *silent* is True the return
value will be None if the import fails.
Simplified version of the function with same name from `Werkzeug`_.
:param import_name:
The dotted name for the object to import.
:pa... | ImportError | dataset/ETHPy150Open numan/py-analytics/analytics/utils.py/import_string |
8,548 | def load_models_csv(self,filepath, model_no = None):
"""
Load predictions from an individual sub model into a dataframe stored in the sub_models list, if no model_no is given
then load data into next available index. Valid source is a CSV file.
"""
try:
if mode... | IndexError | dataset/ETHPy150Open theusual/kaggle-seeclickfix-ensemble/Bryan/ensembles.py/EnsembleAvg.load_models_csv |
8,549 | def sort_dataframes(self,sortcolumn):
"""
Sort all data frame attributes of class by a given column for ease of comparison.
"""
try:
for i in range(len(self.sub_models)):
self.sub_models[i] = self.sub_models[i].sort(sortcolumn)
if 'df_true' ... | KeyError | dataset/ETHPy150Open theusual/kaggle-seeclickfix-ensemble/Bryan/ensembles.py/EnsembleAvg.sort_dataframes |
8,550 | def _assertEqualsAndSerialize(self, expected, kranges):
results = []
while True:
try:
results.append(kranges.next())
kranges = kranges.__class__.from_json(kranges.to_json())
except __HOLE__:
break
self.assertRaises(StopIteration, kranges.next)
expected.sort()
resu... | StopIteration | dataset/ETHPy150Open GoogleCloudPlatform/appengine-mapreduce/python/test/mapreduce/key_ranges_test.py/KeyRangesTest._assertEqualsAndSerialize |
8,551 | def parse_url(url):
"""Parses the supplied Redis URL and returns a dict with the parsed/split data.
For ambiguous URLs like redis://localhost and redis://my_socket_file this function will prioritize network URLs over
socket URLs. redis://my_socket_file will be interpreted as a network URL, with the Redis s... | AttributeError | dataset/ETHPy150Open Robpol86/Flask-Redis-Helper/flask_redis.py/parse_url |
8,552 | def forwards(self, orm):
using_mysql = db.backend_name == 'mysql'
db.rename_table('easy_thumbnails_storagenew', 'easy_thumbnails_storage')
if using_mysql:
try:
db.drop_foreign_key('easy_thumbnails_source', 'storage_new_id')
except __HOLE__:
... | ValueError | dataset/ETHPy150Open SmileyChris/easy-thumbnails/easy_thumbnails/south_migrations/0010_rename_storage.py/Migration.forwards |
8,553 | def __eq__(self, other):
try:
return (self._ip == other._ip
and self._version == other._version)
except __HOLE__:
return NotImplemented | AttributeError | dataset/ETHPy150Open anandology/pyjamas/pyjs/src/pyjs/lib/ipaddr.py/_BaseIP.__eq__ |
8,554 | def __eq__(self, other):
try:
return (self._version == other._version
and self.network == other.network
and int(self.netmask) == int(other.netmask))
except __HOLE__:
if isinstance(other, _BaseIP):
return (self._version == ot... | AttributeError | dataset/ETHPy150Open anandology/pyjamas/pyjs/src/pyjs/lib/ipaddr.py/_BaseNet.__eq__ |
8,555 | def _ip_int_from_string(self, ip_str):
"""Turn the given IP string into an integer for comparison.
Args:
ip_str: A string, the IP ip_str.
Returns:
The IP ip_str as an integer.
Raises:
AddressValueError: if the string isn't a valid IP string.
... | ValueError | dataset/ETHPy150Open anandology/pyjamas/pyjs/src/pyjs/lib/ipaddr.py/_BaseV4._ip_int_from_string |
8,556 | def _is_valid_ip(self, address):
"""Validate the dotted decimal notation IP/netmask string.
Args:
address: A string, either representing a quad-dotted ip
or an integer which is a valid IPv4 IP address.
Returns:
A boolean, True if the string is a valid do... | ValueError | dataset/ETHPy150Open anandology/pyjamas/pyjs/src/pyjs/lib/ipaddr.py/_BaseV4._is_valid_ip |
8,557 | def _is_hostmask(self, ip_str):
"""Test if the IP string is a hostmask (rather than a netmask).
Args:
ip_str: A string, the potential hostmask.
Returns:
A boolean, True if the IP string is a hostmask.
"""
bits = ip_str.split('.')
try:
... | ValueError | dataset/ETHPy150Open anandology/pyjamas/pyjs/src/pyjs/lib/ipaddr.py/IPv4Network._is_hostmask |
8,558 | def _is_valid_netmask(self, netmask):
"""Verify that the netmask is valid.
Args:
netmask: A string, either a prefix or dotted decimal
netmask.
Returns:
A boolean, True if the prefix represents a valid IPv4
netmask.
"""
mask = n... | ValueError | dataset/ETHPy150Open anandology/pyjamas/pyjs/src/pyjs/lib/ipaddr.py/IPv4Network._is_valid_netmask |
8,559 | def _ip_int_from_string(self, ip_str=None):
"""Turn an IPv6 ip_str into an integer.
Args:
ip_str: A string, the IPv6 ip_str.
Returns:
A long, the IPv6 ip_str.
Raises:
AddressValueError: if ip_str isn't a valid IP Address.
"""
if not ... | ValueError | dataset/ETHPy150Open anandology/pyjamas/pyjs/src/pyjs/lib/ipaddr.py/_BaseV6._ip_int_from_string |
8,560 | def _is_valid_ip(self, ip_str):
"""Ensure we have a valid IPv6 address.
Probably not as exhaustive as it should be.
Args:
ip_str: A string, the IPv6 address.
Returns:
A boolean, True if this is a valid IPv6 address.
"""
# We need to have at lea... | ValueError | dataset/ETHPy150Open anandology/pyjamas/pyjs/src/pyjs/lib/ipaddr.py/_BaseV6._is_valid_ip |
8,561 | def _is_valid_netmask(self, prefixlen):
"""Verify that the netmask/prefixlen is valid.
Args:
prefixlen: A string, the netmask in prefix length format.
Returns:
A boolean, True if the prefix represents a valid IPv6
netmask.
"""
try:
... | ValueError | dataset/ETHPy150Open anandology/pyjamas/pyjs/src/pyjs/lib/ipaddr.py/IPv6Network._is_valid_netmask |
8,562 | def Decompress(self, compressed_data):
"""Decompresses the compressed data.
Args:
compressed_data: a byte string containing the compressed data.
Returns:
A tuple containing a byte string of the uncompressed data and
the remaining compressed data.
Raises:
BackEndError: if the X... | IOError | dataset/ETHPy150Open log2timeline/dfvfs/dfvfs/compression/xz_decompressor.py/XZDecompressor.Decompress |
8,563 | def test_low_sample_count(self):
uni = Uniform()
uni.num_samples = 1
try:
for case in uni:
pass
except __HOLE__ as err:
self.assertEqual(str(err),"Uniform distributions "
"must have at least 2 samp... | ValueError | dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.lib/src/openmdao/lib/doegenerators/test/test_uniform.py/TestCase.test_low_sample_count |
8,564 | def parsedate_tz(data):
"""Convert a date string to a time tuple.
Accounts for military timezones.
"""
data = data.split()
# The FWS after the comma after the day-of-week is optional, so search and
# adjust for this.
if data[0].endswith(',') or data[0].lower() in _daynames:
... | ValueError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/email/_parseaddr.py/parsedate_tz |
8,565 | def connectionLost(self, reason):
"""Close both ends of my pipe.
"""
if not hasattr(self, "o"):
return
for fd in self.i, self.o:
try:
os.close(fd)
except __HOLE__:
pass
del self.i, self.o | IOError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/internet/posixbase.py/_FDWaker.connectionLost |
8,566 | def wakeUp(self):
"""Write one byte to the pipe, and flush it.
"""
# We don't use fdesc.writeToFD since we need to distinguish
# between EINTR (try again) and EAGAIN (do nothing).
if self.o is not None:
try:
util.untilConcludes(os.write, self.o, 'x')
... | OSError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/internet/posixbase.py/_UnixWaker.wakeUp |
8,567 | @contextmanager
def _when_exits_zero(call_if_ok):
"""
Calls the function passed in if the SystemExit has a zero exit code.
"""
try:
yield
except __HOLE__ as se:
if getattr(se, 'code', None) == 0:
# Update the tracking branch to reference current HEAD
call_if_o... | SystemExit | dataset/ETHPy150Open robmadole/jig/src/jig/commands/ci.py/_when_exits_zero |
8,568 | @imm_action('set flag', target_class='args', prep='on', obj_msg_class="flags", self_object=True)
def add_flag(source, target, obj, **_):
try:
flag_id = target[0]
except __HOLE__:
raise ActionError("Flag id required.")
try:
flag_value = target[1]
except IndexError:
flag_va... | IndexError | dataset/ETHPy150Open genzgd/Lampost-Mud/lampost/mud/immortal.py/add_flag |
8,569 | @imm_action('clear flag', target_class='args', prep='from', obj_msg_class="flags", self_object=True)
def add_flag(source, target, obj, **_):
try:
flag_id = target[0]
except IndexError:
raise ActionError("Flag id required.")
try:
old_value = obj.flags.pop(flag_id)
except __HOLE__:... | KeyError | dataset/ETHPy150Open genzgd/Lampost-Mud/lampost/mud/immortal.py/add_flag |
8,570 | @imm_action('patch', '__dict__', imm_level='supreme', prep=":", obj_target_class="args")
def patch(target, verb, args, command, **_):
try:
split_ix = args.index(":")
prop = args[split_ix + 1]
new_value = find_extra(verb, split_ix + 2, command)
except (ValueError, __HOLE__):
retur... | IndexError | dataset/ETHPy150Open genzgd/Lampost-Mud/lampost/mud/immortal.py/patch |
8,571 | @imm_action('run update', imm_level='supreme')
def run_update(source, args, **_):
if not args:
return "Update name required."
try:
return lampost.setup.update.__dict__[args[0]](source, *args[1:])
except __HOLE__:
return "No such update." | KeyError | dataset/ETHPy150Open genzgd/Lampost-Mud/lampost/mud/immortal.py/run_update |
8,572 | @imm_action('combat log')
def combat_log(source, **_):
try:
delattr(source.env, 'combat_log')
return "Combat logging removed from {}".format(source.env.name)
except __HOLE__:
source.env.combat_log = True
return "Combat logging added to {}.".format(source.env.name) | AttributeError | dataset/ETHPy150Open genzgd/Lampost-Mud/lampost/mud/immortal.py/combat_log |
8,573 | def metadata(id, sleep_time=1):
"""
Given a HTRC ID, download the volume metadata from the Solr index.
:param id: HTRC volume id.
:type id: string
:param sleep_time: Sleep time to prevent denial of service
:type sleep_time: int in seconds, default: 1
:returns: dict
"""
solr ... | ValueError | dataset/ETHPy150Open inpho/vsm/vsm/extensions/htrc.py/metadata |
8,574 | def rm_lb_hyphens(plain_root, logger, ignore=['.json', '.log', '.err']):
"""
Looks for a hyphen followed by whitespace or a line break.
Reconstructs word and checks to see if the result exists in either
WordNet or the OS's default spellchecker dictionary. If so,
replaces fragments with reconstructe... | ImportError | dataset/ETHPy150Open inpho/vsm/vsm/extensions/htrc.py/rm_lb_hyphens |
8,575 | def htrc_get_titles(metadata, vol_id):
"""
Gets titles of the volume given the metadata from a json file
and volume id.
"""
try:
md = metadata[vol_id]
return md[md.keys()[0]]['titles']
except __HOLE__:
print 'Volume ID not found:', vol_id
raise | KeyError | dataset/ETHPy150Open inpho/vsm/vsm/extensions/htrc.py/htrc_get_titles |
8,576 | def _checkTimeout(self, result, name, lookupDeferred):
try:
userDeferred, cancelCall = self._runningQueries[lookupDeferred]
except __HOLE__:
pass
else:
del self._runningQueries[lookupDeferred]
cancelCall.cancel()
if isinstance(result, ... | KeyError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/internet/base.py/ThreadedResolver._checkTimeout |
8,577 | def removeTrigger_BASE(self, handle):
"""
Just try to remove the trigger.
@see: removeTrigger
"""
try:
phase, callable, args, kwargs = handle
except (TypeError, __HOLE__):
raise ValueError("invalid trigger handle")
else:
if pha... | ValueError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/internet/base.py/_ThreePhaseEvent.removeTrigger_BASE |
8,578 | def _moveCallLaterSooner(self, tple):
# Linear time find: slow.
heap = self._pendingTimedCalls
try:
pos = heap.index(tple)
# Move elt up the heap until it rests at the right place.
elt = heap[pos]
while pos != 0:
parent = (pos-1) /... | ValueError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/internet/base.py/ReactorBase._moveCallLaterSooner |
8,579 | def _stopThreadPool(self):
"""
Stop the reactor threadpool. This method is only valid if there
is currently a threadpool (created by L{_initThreadPool}). It
is not intended to be called directly; instead, it will be
called by a shutdown trigger created in L{... | ValueError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/internet/base.py/ReactorBase._stopThreadPool |
8,580 | def cancelTimeout(self):
if self.timeoutID is not None:
try:
self.timeoutID.cancel()
except __HOLE__:
pass
del self.timeoutID | ValueError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/internet/base.py/BaseConnector.cancelTimeout |
8,581 | def _handleSignals(self):
"""
Install the signal handlers for the Twisted event loop.
"""
try:
import signal
except __HOLE__:
log.msg("Warning: signal module unavailable -- "
"not installing signal handlers.")
return
... | ImportError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/internet/base.py/_SignalReactorMixin._handleSignals |
8,582 | def type_check(self, instance):
error_msg = ''
for t in self.union_types:
try:
check_constraint(t, instance)
return
except __HOLE__ as e:
error_msg = str(e)
continue
raise CompositeTypeHintError(
'%s type-constraint violated. Expected ... | TypeError | dataset/ETHPy150Open GoogleCloudPlatform/DataflowPythonSDK/google/cloud/dataflow/typehints/typehints.py/UnionHint.UnionConstraint.type_check |
8,583 | def _render_expression(self, check):
"""Turn a mongodb-style search dict into an SQL query."""
expressions = []
args = []
skeys = set(check.keys())
skeys.difference_update(set(self._keys))
skeys.difference_update(set(['buffers', 'result_buffers']))
if ske... | KeyError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/parallel/controller/sqlitedb.py/SQLiteDB._render_expression |
8,584 | def delete_if_lifetime_over(item, name):
"""
:return: True if file was deleted
"""
if 0 < item.meta['timestamp-max-life'] < time.time():
try:
current_app.storage.remove(name)
except (OSError, __HOLE__) as e:
pass
return True
return False | IOError | dataset/ETHPy150Open bepasty/bepasty-server/bepasty/utils/date_funcs.py/delete_if_lifetime_over |
8,585 | def stress(cmd, revision_tag, stress_sha, stats=None):
"""Run stress command and collect average statistics"""
# Check for compatible stress commands. This doesn't yet have full
# coverage of every option:
# Make sure that if this is a read op, that the number of threads
# was specified, otherwise s... | ValueError | dataset/ETHPy150Open datastax/cstar_perf/tool/cstar_perf/tool/benchmark.py/stress |
8,586 | def print_package_version(package_name, indent=' '):
try:
package = __import__(package_name)
version = getattr(package, '__version__', None)
package_file = getattr(package, '__file__', )
provenance_info = '{0} from {1}'.format(version, package_file)
except __HOLE__:
prov... | ImportError | dataset/ETHPy150Open neurosynth/neurosynth/ci/show-python-package-versions.py/print_package_version |
8,587 | def get_context(self, url='/'):
context = self.client.get(url).context
try:
return context[0]
except __HOLE__:
return context | KeyError | dataset/ETHPy150Open calebsmith/django-template-debug/template_debug/tests/base.py/TemplateDebugTestCase.get_context |
8,588 | def publish_status(self, target, temp, heater_percent, cooler_percent):
# Get timestamp in epoch seconds
timestamp = int(time.time())
# Append new status
status = [target, temp, heater_percent, cooler_percent, timestamp]
self._datapoints.append(status)
# Drop datapoints ... | IOError | dataset/ETHPy150Open amorphic/braubuddy/braubuddy/output/imagefile.py/ImageFileOutput.publish_status |
8,589 | @classmethod
def as_manager(cls):
class QuerySetManager(models.Manager):
use_for_related_fields = True
def __init__(self):
super(QuerySetManager, self).__init__()
self.queryset_class = cls
def get_query_set(self):
return s... | AttributeError | dataset/ETHPy150Open jumoconnect/openjumo/jumodjango/utils/query_set.py/QuerySet.as_manager |
8,590 | def _on_harvest_status_message(self):
try:
log.debug("Updating harvest with id %s", self.message["id"])
# Retrieve harvest model object
harvest = Harvest.objects.get(harvest_id=self.message["id"])
# And update harvest model object
harvest.status = sel... | ObjectDoesNotExist | dataset/ETHPy150Open gwu-libraries/sfm-ui/sfm/message_consumer/sfm_ui_consumer.py/SfmUiConsumer._on_harvest_status_message |
8,591 | def _on_warc_created_message(self):
try:
log.debug("Warc with id %s", self.message["warc"]["id"])
# Create warc model object
warc = Warc.objects.create(
harvest=Harvest.objects.get(harvest_id=self.message["harvest"]["id"]),
warc_id=self.message... | ObjectDoesNotExist | dataset/ETHPy150Open gwu-libraries/sfm-ui/sfm/message_consumer/sfm_ui_consumer.py/SfmUiConsumer._on_warc_created_message |
8,592 | def _on_export_status_message(self):
try:
log.debug("Updating export with id %s", self.message["id"])
# Retrieve export model object
export = Export.objects.get(export_id=self.message["id"])
# And update export model object
export.status = self.messag... | ObjectDoesNotExist | dataset/ETHPy150Open gwu-libraries/sfm-ui/sfm/message_consumer/sfm_ui_consumer.py/SfmUiConsumer._on_export_status_message |
8,593 | def _on_web_harvest_start_message(self):
try:
log.debug("Creating harvest for web harvest with id %s", self.message["id"])
parent_harvest = Harvest.objects.get(harvest_id=self.message["parent_id"])
harvest = Harvest.objects.create(harvest_type=self.message["type"],
... | ObjectDoesNotExist | dataset/ETHPy150Open gwu-libraries/sfm-ui/sfm/message_consumer/sfm_ui_consumer.py/SfmUiConsumer._on_web_harvest_start_message |
8,594 | def paginate(context, window=DEFAULT_WINDOW):
"""
Renders the ``pagination/pagination.html`` template, resulting in a
Digg-like display of the available pages, given the current page. If there
are too many pages to be displayed before and after the current page, then
elipses will be used to indicat... | KeyError | dataset/ETHPy150Open ilblackdragon/django-blogs/blog/templatetags/misc.py/paginate |
8,595 | def lazy_init(self):
try:
f=open(self.filename)
except __HOLE__:
warning("Can't open base %s" % self.filename)
return
try:
self.base = []
for l in f:
if l[0] in ["#","\n"]:
continue
l ... | IOError | dataset/ETHPy150Open phaethon/scapy/scapy/modules/p0f.py/p0fKnowledgeBase.lazy_init |
8,596 | def make_sure_path_exists(path):
try:
os.makedirs(path)
except __HOLE__ as exception:
if exception.errno != errno.EEXIST:
raise
if not os.path.isdir(path):
raise | OSError | dataset/ETHPy150Open fictivekin/openrecipes/scrapy_proj/grab_html.py/make_sure_path_exists |
8,597 | def get_zoom(self, request, default=16):
try:
zoom = int(request.GET['zoom'])
except (__HOLE__, KeyError):
zoom = default
else:
zoom = min(max(10, zoom), 18)
return zoom | ValueError | dataset/ETHPy150Open mollyproject/mollyproject/molly/utils/views.py/BaseView.get_zoom |
8,598 | def render(self, request, context, template_name, expires=None):
"""
Given a request, a context dictionary and a template name, this renders
the template with the given context according to the capabilities and
requested format of the client. An optional final argument is that of
... | IndexError | dataset/ETHPy150Open mollyproject/mollyproject/molly/utils/views.py/BaseView.render |
8,599 | def parse_accept_header(self, accept):
media_types = []
for media_type in accept.split(','):
try:
media_types.append(MediaType(media_type))
except __HOLE__:
pass
return media_types | ValueError | dataset/ETHPy150Open mollyproject/mollyproject/molly/utils/views.py/BaseView.parse_accept_header |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.