Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
3,000 | def _color_palette(cmap, n_colors):
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
colors_i = np.linspace(0, 1., n_colors)
if isinstance(cmap, (list, tuple)):
# we have a list of colors
try:
# first try to turn it into a palette with seaborn
... | ImportError | dataset/ETHPy150Open pydata/xarray/xarray/plot/utils.py/_color_palette |
3,001 | def info(name):
'''
Return user information
CLI Example:
.. code-block:: bash
salt '*' user.info root
'''
ret = {}
try:
data = pwd.getpwnam(name)
ret['gid'] = data.pw_gid
ret['groups'] = list_groups(name)
ret['home'] = data.pw_dir
ret['name'... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/modules/solaris_user.py/info |
3,002 | def varToXML(v, name):
""" single variable or dictionary to xml representation """
type, typeName, resolver = getType(v)
try:
if hasattr(v, '__class__'):
try:
cName = str(v.__class__)
if cName.find('.') != -1:
cName = cName.split('.')[... | TypeError | dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/common/diagnostic/pydevDebug/pydevd_vars.py/varToXML |
3,003 | def parse_args(args):
usage = ('usage: %prog service [service params] [general params] '
'[resource|param, ...] method [param, ...]')
parser = optparse.OptionParser(usage=usage)
parser.add_option('--verbose', '-v', dest='verbose',
action='count', default=0)
parser.add_... | ImportError | dataset/ETHPy150Open ducksboard/libsaas/libsaas/scripts/saas.py/parse_args |
3,004 | def get_objects(self, data=None, size=1024):
""" Get sentences but return list of NMEA objects
"""
str_data = self._read(data=data, size=size)
nmea_objects = []
for nmea_str in str_data:
try:
nmea_ob = self._get_type(nmea_str)()
except __HO... | TypeError | dataset/ETHPy150Open FishPi/FishPi-POCV---Command---Control/external/pynmea/streamer.py/NMEAStream.get_objects |
3,005 | def _split(self, data, separator=None):
""" Take some data and split up based on the notion that a sentence
looks something like:
$x,y,z or $x,y,z*ab
separator is for cases where there is something strange or
non-standard as a separator between sentences.
... | ValueError | dataset/ETHPy150Open FishPi/FishPi-POCV---Command---Control/external/pynmea/streamer.py/NMEAStream._split |
3,006 | @classmethod
def construct_from_string(cls, string):
""" attempt to construct this type from a string, raise a TypeError if
it's not possible
"""
try:
return cls(unit=string)
except __HOLE__:
raise TypeError("could not construct DatetimeTZDtype") | ValueError | dataset/ETHPy150Open pydata/pandas/pandas/types/dtypes.py/DatetimeTZDtype.construct_from_string |
3,007 | def addcause(self, cause):
try:
self.score += self.causesdict[cause]
self.causes.append(cause)
except __HOLE__:
print "ERROR: Unknown cause [%s]" % (cause) | KeyError | dataset/ETHPy150Open tatanus/SPF/spf/core/webprofiler.py/indicator.addcause |
3,008 | def default_blas_ldflags():
global numpy
try:
if (hasattr(numpy.distutils, '__config__') and
numpy.distutils.__config__):
# If the old private interface is available use it as it
# don't print information to the user.
blas_info = numpy.distutils.__conf... | KeyError | dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/configdefaults.py/default_blas_ldflags |
3,009 | def filter_compiledir(path):
# Expand '~' in path
path = os.path.expanduser(path)
# Turn path into the 'real' path. This ensures that:
# 1. There is no relative path, which would fail e.g. when trying to
# import modules from the compile dir.
# 2. The path is stable w.r.t. e.g. symlinks... | IOError | dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/configdefaults.py/filter_compiledir |
3,010 | def __init__(self, url, **config):
self.url = url
parsed = urlparse(self.url)
if parsed.scheme == "bolt":
self.host = parsed.hostname
self.port = parsed.port
else:
raise ProtocolError("Unsupported URI scheme: '%s' in url: '%s'. Currently only supported... | KeyError | dataset/ETHPy150Open nigelsmall/py2neo/py2neo/packages/neo4j/v1/session.py/Driver.__init__ |
3,011 | def session(self):
""" Create a new session based on the graph database details
specified within this driver:
>>> from neo4j.v1 import GraphDatabase
>>> driver = GraphDatabase.driver("bolt://localhost")
>>> session = driver.session()
"""
session = No... | IndexError | dataset/ETHPy150Open nigelsmall/py2neo/py2neo/packages/neo4j/v1/session.py/Driver.session |
3,012 | def index(self, key):
""" Return the index of the given key
"""
try:
return self._keys.index(key)
except __HOLE__:
raise KeyError(key) | ValueError | dataset/ETHPy150Open nigelsmall/py2neo/py2neo/packages/neo4j/v1/session.py/Record.index |
3,013 | def __eq__(self, other):
try:
return self._keys == tuple(other.keys()) and self._values == tuple(other.values())
except __HOLE__:
return False | AttributeError | dataset/ETHPy150Open nigelsmall/py2neo/py2neo/packages/neo4j/v1/session.py/Record.__eq__ |
3,014 | def get_url(self, secure=False, longurl=False):
"""
Return the url
:param secure: bool - To use https
:param longurl: bool - On local, reference the local path with the domain
ie: http://site.com/files/object.png otherwise /files/object.png
:return: str
... | NotImplementedError | dataset/ETHPy150Open mardix/flask-cloudy/flask_cloudy.py/Object.get_url |
3,015 | def authenticate(self, request):
client = cas.get_client() # Returns a CAS server client
try:
auth_header_field = request.META["HTTP_AUTHORIZATION"]
auth_token = cas.parse_auth_header(auth_header_field)
except (cas.CasTokenError, __HOLE__):
return None # If ... | KeyError | dataset/ETHPy150Open CenterForOpenScience/osf.io/api/base/authentication/drf.py/OSFCASAuthentication.authenticate |
3,016 | def __getitem__(self, name):
try:
return self.relevant[name]
except __HOLE__:
return () | KeyError | dataset/ETHPy150Open OpenMDAO/OpenMDAO/openmdao/core/relevance.py/Relevance.__getitem__ |
3,017 | def is_relevant(self, var_of_interest, varname):
""" Returns True if a variable is relevant to a particular variable
of interest.
Args
----
var_of_interest : str
Name of a variable of interest (either a parameter or a constraint
or objective output, depen... | KeyError | dataset/ETHPy150Open OpenMDAO/OpenMDAO/openmdao/core/relevance.py/Relevance.is_relevant |
3,018 | def test_point():
g = Point(0, 0)
try:
assert hash(g)
return False
except __HOLE__:
return True | TypeError | dataset/ETHPy150Open Toblerity/Shapely/tests/test_hash.py/test_point |
3,019 | def test_multipoint():
g = MultiPoint([(0, 0)])
try:
assert hash(g)
return False
except __HOLE__:
return True | TypeError | dataset/ETHPy150Open Toblerity/Shapely/tests/test_hash.py/test_multipoint |
3,020 | def test_polygon():
g = Point(0, 0).buffer(1.0)
try:
assert hash(g)
return False
except __HOLE__:
return True | TypeError | dataset/ETHPy150Open Toblerity/Shapely/tests/test_hash.py/test_polygon |
3,021 | def test_collection():
g = GeometryCollection([Point(0, 0)])
try:
assert hash(g)
return False
except __HOLE__:
return True | TypeError | dataset/ETHPy150Open Toblerity/Shapely/tests/test_hash.py/test_collection |
3,022 | def check_permissions(permission_type, user, project):
"""
Here we check permission types, and see if a user has proper perms.
If a user has "edit" permissions on a project, they pretty much have
carte blanche to do as they please, so we kick that back as true.
Otherwise we go more fine grained and... | AttributeError | dataset/ETHPy150Open f4nt/djtracker/djtracker/utils.py/check_permissions |
3,023 | def check_perms(request, project, user=None):
"""
Here we check permission types, and see if a user has proper perms.
If a user has "edit" permissions on a project, they pretty much have
carte blanche to do as they please, so we kick that back as true.
Otherwise we go more fine grained and check th... | AttributeError | dataset/ETHPy150Open f4nt/djtracker/djtracker/utils.py/check_perms |
3,024 | def render(self, part, context):
"""
render a mail part
"""
try:
return self.mailparts[part].nodelist.render(context)
except __HOLE__:
return None | KeyError | dataset/ETHPy150Open f4nt/djtracker/djtracker/utils.py/MailTemplate.render |
3,025 | @lazy_import
def pickle():
try:
import cPickle as pickle
except __HOLE__:
import pickle
return pickle | ImportError | dataset/ETHPy150Open cloudmatrix/esky/esky/sudo/__init__.py/pickle |
3,026 | @lazy_import
def threading():
try:
import threading
except __HOLE__:
threading = None
return threading | ImportError | dataset/ETHPy150Open cloudmatrix/esky/esky/sudo/__init__.py/threading |
3,027 | @lazy_import
def _impl():
try:
from esky.sudo import sudo_osx
return sudo_osx
except __HOLE__:
from esky.sudo import sudo_unix
return sudo_unix | ImportError | dataset/ETHPy150Open cloudmatrix/esky/esky/sudo/__init__.py/_impl |
3,028 | def __init__(self,target):
# Reflect the 'name' attribute if it has one, but don't worry
# if not. This helps SudoProxy be re-used on other classes.
try:
self.name = target.name
except __HOLE__:
pass
self.target = target
self.closed = False
... | AttributeError | dataset/ETHPy150Open cloudmatrix/esky/esky/sudo/__init__.py/SudoProxy.__init__ |
3,029 | def _get_sudo_argtypes(obj,methname):
"""Get the argtypes list for the given method.
This searches the base classes of obj if the given method is not declared
allowed_from_sudo, so that people don't have to constantly re-apply the
decorator.
"""
for base in _get_mro(obj):
try:
... | AttributeError | dataset/ETHPy150Open cloudmatrix/esky/esky/sudo/__init__.py/_get_sudo_argtypes |
3,030 | def _get_sudo_iterator(obj,methname):
"""Get the iterator flag for the given method.
This searches the base classes of obj if the given method is not declared
allowed_from_sudo, so that people don't have to constantly re-apply the
decorator.
"""
for base in _get_mro(obj):
try:
... | AttributeError | dataset/ETHPy150Open cloudmatrix/esky/esky/sudo/__init__.py/_get_sudo_iterator |
3,031 | def _get_mro(obj):
"""Get the method resolution order for an object.
In other words, get the list of classes what are used to look up methods
on the given object, in the order in which they'll be consulted.
"""
try:
return obj.__class__.__mro__
except __HOLE__:
return _get_oldst... | AttributeError | dataset/ETHPy150Open cloudmatrix/esky/esky/sudo/__init__.py/_get_mro |
3,032 | @base.get('/nodep/<host>/<int:port>')
def node_panel(request, host, port):
node = models.node.get_by_host_port(host, port)
if node is None:
return base.not_found()
detail = {}
try:
detail = file_ipc.read_details()['nodes'][
'%s:%d' % (node.host, node.port)]
except (__HOLE... | IOError | dataset/ETHPy150Open HunanTV/redis-ctl/handlers/nodes.py/node_panel |
3,033 | def render(self, name, value, attrs=None):
try:
year_val, month_val, day_val = value.year, value.month, value.day
except __HOLE__:
year_val = month_val = day_val = None
if isinstance(value, basestring):
match = RE_DATE.match(value)
if m... | AttributeError | dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/forms/extras/widgets.py/SelectDateWidget.render |
3,034 | def crop(config):
"""
This function takes an OpenVAS XML with results and return Vulnerability info.
:param config: Config instance
:type config: Config
:raises: TypeError, InvalidFormat
"""
import copy
if not isinstance(config, Config):
raise TypeError("Expected Config, got '... | ImportError | dataset/ETHPy150Open cr0hn/openvas_to_report/openvas_to_report/api.py/crop |
3,035 | def __init__(self, casemode=0, countpos=0, dirsonly=False, exclude="",
filesonly=False, hidden=False, ignorecase=False,
interactive=False, keepext=False, mediamode=False,
noclobber=False, recursive=False, regex=False, remdups=False,
remext=False, remno... | TypeError | dataset/ETHPy150Open mikar/demimove/demimove/fileops.py/FileOps.__init__ |
3,036 | def undo(self, actions=None):
if actions is None:
try:
actions = self.history.pop()
except __HOLE__:
log.error("History list is empty.")
return
for i in actions:
log.debug("{} -> {}.".format(i[1], i[0]))
if ... | IndexError | dataset/ETHPy150Open mikar/demimove/demimove/fileops.py/FileOps.undo |
3,037 | def modify_previews(self, previews):
if self.countcheck:
lenp, base, step = len(previews), self.countbase, self.countstep
countlen = len(str(lenp))
countrange = xrange(base, lenp * step + 1, step)
if self.countfill:
count = (str(i).rjust(countlen, ... | StopIteration | dataset/ETHPy150Open mikar/demimove/demimove/fileops.py/FileOps.modify_previews |
3,038 | def apply_remove(self, s):
if not self.removecheck:
return s
if self.remnonwords:
s = re.sub("\W", "", s, flags=self.ignorecase)
if self.remsymbols:
allowed = string.ascii_letters + string.digits + " .-_+" # []()
for i in ["utf-8", "latin1"]:
... | UnicodeDecodeError | dataset/ETHPy150Open mikar/demimove/demimove/fileops.py/FileOps.apply_remove |
3,039 | def get_tests(config={}):
tests = []
tests += list_test_cases(DSATest)
try:
from Crypto.PublicKey import _fastmath
tests += list_test_cases(DSAFastMathTest)
except __HOLE__:
from distutils.sysconfig import get_config_var
import inspect
_fm_path = os.path.normpath(... | ImportError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pycrypto-2.6.1/lib/Crypto/SelfTest/PublicKey/test_DSA.py/get_tests |
3,040 | def set_charset(self, charset):
"""Set the charset of the payload to a given character set.
charset can be a Charset instance, a string naming a character set, or
None. If it is a string it will be converted to a Charset instance.
If charset is None, the charset parameter will be remov... | TypeError | dataset/ETHPy150Open babble/babble/include/jython/Lib/email/message.py/Message.set_charset |
3,041 | def _get_params_preserve(self, failobj, header):
# Like get_params() but preserves the quoting of values. BAW:
# should this be part of the public interface?
missing = object()
value = self.get(header, missing)
if value is missing:
return failobj
params = []
... | ValueError | dataset/ETHPy150Open babble/babble/include/jython/Lib/email/message.py/Message._get_params_preserve |
3,042 | @cache_readonly
def theoretical_quantiles(self):
try:
return self.dist.ppf(self.theoretical_percentiles)
except __HOLE__:
msg = '%s requires more parameters to ' \
'compute ppf'.format(self.dist.name,)
raise TypeError(msg)
except:
... | TypeError | dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/graphics/gofplots.py/ProbPlot.theoretical_quantiles |
3,043 | def _get_dns_driver():
global DNS_DRIVER
if DNS_DRIVER:
return DNS_DRIVER
if not cfg.CONF.external_dns_driver:
return
try:
DNS_DRIVER = driver.ExternalDNSService.get_instance()
LOG.debug("External DNS driver loaded: %s",
cfg.CONF.external_dns_driver)
... | ImportError | dataset/ETHPy150Open openstack/neutron/neutron/plugins/ml2/extensions/dns_integration.py/_get_dns_driver |
3,044 | def check_custom_authorization_check_importable(app_configs, **kwargs):
errors = []
authorization_check = hijack_settings.HIJACK_AUTHORIZATION_CHECK
try:
if authorization_check != staff_member_required:
import_string(authorization_check)
except __HOLE__:
errors.append(
... | ImportError | dataset/ETHPy150Open arteria/django-hijack/hijack/checks.py/check_custom_authorization_check_importable |
3,045 | def check_hijack_decorator_importable(app_configs, **kwargs):
errors = []
decorator = hijack_settings.HIJACK_DECORATOR
try:
if decorator != 'django.contrib.admin.views.decorators.staff_member_required':
import_string(decorator)
except __HOLE__:
errors.append(
Erro... | ImportError | dataset/ETHPy150Open arteria/django-hijack/hijack/checks.py/check_hijack_decorator_importable |
3,046 | def render(self, context):
try:
output = self.filter_expression.resolve(context)
output = localize(output)
output = force_unicode(output)
except TemplateSyntaxError, e:
if not hasattr(e, 'source'):
e.source = self.source
raise
... | UnicodeDecodeError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/_internal/django/template/debug.py/DebugVariableNode.render |
3,047 | def configure(factory=None, **kwargs):
if not factory:
factory = os.environ.get(ENVIRONMENT_VARIABLE)
if not factory:
raise ImportError(
'Settings could not be imported because configure was called'
' without arguments and the environment variable %s is'
... | AttributeError | dataset/ETHPy150Open matthewwithanm/django-classbasedsettings/cbsettings/__init__.py/configure |
3,048 | def loads(self, response):
try:
return json.loads(response.content.decode('utf-8'))['data']
except (UnicodeDecodeError, __HOLE__):
return response.content | ValueError | dataset/ETHPy150Open swayf/proxmoxer/proxmoxer/backends/https.py/JsonSerializer.loads |
3,049 | @classmethod
def _handle_creation_inputs(cls, *args, **kwargs):
"""Return the number of rows, cols and flat matrix elements.
Examples
========
>>> from sympy import Matrix, I
Matrix can be constructed as follows:
* from a nested list of iterables
>>> Matr... | TypeError | dataset/ETHPy150Open sympy/sympy/sympy/matrices/matrices.py/MatrixBase._handle_creation_inputs |
3,050 | def norm(self, ord=None):
"""Return the Norm of a Matrix or Vector.
In the simplest case this is the geometric size of the vector
Other norms can be specified by the ord parameter
===== ============================ ==========================
ord norm for matrices ... | TypeError | dataset/ETHPy150Open sympy/sympy/sympy/matrices/matrices.py/MatrixBase.norm |
3,051 | def pinv(self):
"""Calculate the Moore-Penrose pseudoinverse of the matrix.
The Moore-Penrose pseudoinverse exists and is unique for any matrix.
If the matrix is invertible, the pseudoinverse is the same as the
inverse.
Examples
========
>>> from sympy import M... | ValueError | dataset/ETHPy150Open sympy/sympy/sympy/matrices/matrices.py/MatrixBase.pinv |
3,052 | def a2idx(j, n=None):
"""Return integer after making positive and validating against n."""
if type(j) is not int:
try:
j = j.__index__()
except __HOLE__:
raise IndexError("Invalid index a[%r]" % (j, ))
if n is not None:
if j < 0:
j += n
if ... | AttributeError | dataset/ETHPy150Open sympy/sympy/sympy/matrices/matrices.py/a2idx |
3,053 | def converter (function, klass=None):
def _integer (value):
if klass is None:
return function(value)
try:
return klass(value)
except __HOLE__:
return function(value)
return _integer | ValueError | dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/bgp/message/update/nlri/flow.py/converter |
3,054 | def __init__(self, settings, key_bindings):
super(CaffeVisApp, self).__init__(settings, key_bindings)
print 'Got settings', settings
self.settings = settings
self.bindings = key_bindings
self._net_channel_swap = (2,1,0)
self._net_channel_swap_inv = tuple([self._net_chann... | IOError | dataset/ETHPy150Open yosinski/deep-visualization-toolbox/caffevis/app.py/CaffeVisApp.__init__ |
3,055 | def _draw_layer_pane(self, pane):
'''Returns the data shown in highres format, b01c order.'''
if self.state.layers_show_back:
layer_dat_3D = self.net.blobs[self.state.layer].diff[0]
else:
layer_dat_3D = self.net.blobs[self.state.layer].data[0]
# Promote F... | IOError | dataset/ETHPy150Open yosinski/deep-visualization-toolbox/caffevis/app.py/CaffeVisApp._draw_layer_pane |
3,056 | def test_collectionannot(self):
'Test building an AnnotationDB from file'
from pygr import seqdb, cnestedlist, sqlgraph
hg18 = pygr.Data.getResource('TEST.Seq.Genome.hg18')
# BUILD ANNOTATION DATABASE FOR REFSEQ EXONS
exon_slices = Collection(
filename=os.path.join(se... | KeyError | dataset/ETHPy150Open cjlee112/pygr/tests/annotation_hg18_megatest.py/Build_Test.test_collectionannot |
3,057 | def test_mysqlannot(self):
'Test building an AnnotationDB from MySQL'
from pygr import seqdb, cnestedlist, sqlgraph
hg18 = pygr.Data.getResource('TEST.Seq.Genome.hg18')
# BUILD ANNOTATION DATABASE FOR REFSEQ EXONS: MYSQL VERSION
exon_slices = sqlgraph.SQLTableClustered(
... | KeyError | dataset/ETHPy150Open cjlee112/pygr/tests/annotation_hg18_megatest.py/Build_Test.test_mysqlannot |
3,058 | def run(self, args, opts):
if len(args) != 1:
raise UsageError()
editor = self.settings['EDITOR']
try:
spidercls = self.crawler_process.spider_loader.load(args[0])
except __HOLE__:
return self._err("Spider not found: %s" % args[0])
sfile = sy... | KeyError | dataset/ETHPy150Open scrapy/scrapy/scrapy/commands/edit.py/Command.run |
3,059 | def test_coercion(self):
f = CFoo()
# Test coercion from basic built-in types
f.ints = [1, 2, 3]
desired = [1, 2, 3]
self.assertEqual(f.ints, desired)
f.ints = (1, 2, 3)
self.assertEqual(f.ints, desired)
f.strs = ("abc", "def", "ghi")
self.assert... | ImportError | dataset/ETHPy150Open enthought/traits/traits/tests/test_list.py/ListTestCase.test_coercion |
3,060 | def test_build_request(self):
url = "http://storj.io/"
data = "test"
headers = {"referer": "http://www.google.com/"}
r = bt.build_request(url, data, headers)
self.assertTrue(isinstance(r, bt.Request))
# Invalid URL.
url = ""
try:
r = b... | ValueError | dataset/ETHPy150Open Storj/dataserv-client/tests/test_bandwidth_test.py/TestBandwidthTest.test_build_request |
3,061 | def test_get_config(self):
# Invalid URL.
try:
bt.getConfig(url="test")
except __HOLE__:
pass
# Valid XML.
configxml = """<?xml version="1.0" encoding="UTF-8"?>
<settings>
<client ip="127.0.0.1" lat="40" lon="-90" isp="Comcast Cable" isprating... | ValueError | dataset/ETHPy150Open Storj/dataserv-client/tests/test_bandwidth_test.py/TestBandwidthTest.test_get_config |
3,062 | def get_field_value_by_dotpath(
self, folder, field_name, raw=False, formatted=False
):
fields = folder.get_fields()
key_dotpath = None
if '.' in field_name:
field_name, key_dotpath = field_name.split('.', 1)
if field_name not in fields:
raise Jirafs... | ValueError | dataset/ETHPy150Open coddingtonbear/jirafs/jirafs/commands/field.py/Command.get_field_value_by_dotpath |
3,063 | def test_write_write_rollback_read_first_value(self):
with local_db.Transaction() as tx:
tx.execute('INSERT INTO tests VALUES (:k, :v)', k='foo', v='bar')
try:
with local_db.Transaction() as tx:
tx.execute('UPDATE tests SET value=:v WHERE key=:k',
... | RuntimeError | dataset/ETHPy150Open MirantisWorkloadMobility/CloudFerry/tests/lib/utils/test_local_db.py/LocalDbTestCase.test_write_write_rollback_read_first_value |
3,064 | def test_nested_tx_rollback_inner(self):
with local_db.Transaction() as tx1:
tx1.execute('INSERT INTO tests VALUES (:k, :v)', k='foo', v='bar')
try:
with local_db.Transaction() as tx2:
tx2.execute('UPDATE tests SET value=:v WHERE key=:k',
... | RuntimeError | dataset/ETHPy150Open MirantisWorkloadMobility/CloudFerry/tests/lib/utils/test_local_db.py/LocalDbTestCase.test_nested_tx_rollback_inner |
3,065 | def test_nested_tx_rollback_outer(self):
# Prepare state
with local_db.Transaction() as tx:
tx.execute('INSERT INTO tests VALUES (:k, :v)', k='foo', v='bar')
# Run outer rollback from inner tx
try:
with local_db.Transaction() as tx1:
tx1.execute('... | RuntimeError | dataset/ETHPy150Open MirantisWorkloadMobility/CloudFerry/tests/lib/utils/test_local_db.py/LocalDbTestCase.test_nested_tx_rollback_outer |
3,066 | def is_signed(file_path):
"""Return True if the file has been signed.
This utility function will help detect if a XPI file has been signed by
mozilla (if we can't trust the File.is_signed field).
It will simply check the signature filenames, and assume that if they're
named "mozilla.*" then the xp... | IOError | dataset/ETHPy150Open mozilla/addons-server/src/olympia/lib/crypto/packaged.py/is_signed |
3,067 | def ifind(pred, seq):
try:
return next(filter(pred, seq))
except __HOLE__:
return None | StopIteration | dataset/ETHPy150Open osrg/ryu/ryu/lib/ovs/vsctl.py/ifind |
3,068 | def set_queue(self, vsctl_qos, max_rate, min_rate,
queue_id):
ovsrec_qos = vsctl_qos.qos_cfg[0]
try:
ovsrec_queue = ovsrec_qos.queues[queue_id]
except (__HOLE__, KeyError):
ovsrec_queue = self.txn.insert(
self.txn.idl.tables[vswitch_idl.... | AttributeError | dataset/ETHPy150Open osrg/ryu/ryu/lib/ovs/vsctl.py/VSCtlContext.set_queue |
3,069 | @staticmethod
def _column_delete(ovsrec_row, column, ovsrec_del):
value = getattr(ovsrec_row, column)
try:
value.remove(ovsrec_del)
except __HOLE__:
# Datum.to_python() with _uuid_to_row trims down deleted
# references. If ovsrec_del.delete() is called bef... | ValueError | dataset/ETHPy150Open osrg/ryu/ryu/lib/ovs/vsctl.py/VSCtlContext._column_delete |
3,070 | def loadUserMapFromCache(self):
self.users = {}
self.userMapFromPerforceServer = False
try:
cache = open(self.getUserCacheFilename(), "rb")
lines = cache.readlines()
cache.close()
for line in lines:
entry = line.strip().split("\t")
... | IOError | dataset/ETHPy150Open zulip/zulip/api/integrations/perforce/git_p4.py/P4UserMap.loadUserMapFromCache |
3,071 | def importP4Labels(self, stream, p4Labels):
if verbose:
print("import p4 labels: " + ' '.join(p4Labels))
ignoredP4Labels = gitConfigList("git-p4.ignoredP4Labels")
validLabelRegexp = gitConfig("git-p4.labelImportRegexp")
if len(validLabelRegexp) == 0:
validLabelRe... | ValueError | dataset/ETHPy150Open zulip/zulip/api/integrations/perforce/git_p4.py/P4Sync.importP4Labels |
3,072 | def importChanges(self, changes):
cnt = 1
for change in changes:
description = p4_describe(change)
self.updateOptionDict(description)
if not self.silent:
sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
... | IOError | dataset/ETHPy150Open zulip/zulip/api/integrations/perforce/git_p4.py/P4Sync.importChanges |
3,073 | def importHeadRevision(self, revision):
print("Doing initial import of %s from revision %s into %s" % (' '.join(self.depotPaths), revision, self.branch))
details = {}
details["user"] = "git perforce import user"
details["desc"] = ("Initial import of %s from the state at revision %s\n"
... | IOError | dataset/ETHPy150Open zulip/zulip/api/integrations/perforce/git_p4.py/P4Sync.importHeadRevision |
3,074 | def main():
if len(sys.argv[1:]) == 0:
printUsage(list(commands.keys()))
sys.exit(2)
cmdName = sys.argv[1]
try:
klass = commands[cmdName]
cmd = klass()
except __HOLE__:
print("unknown command %s" % cmdName)
print("")
printUsage(list(commands.keys(... | KeyError | dataset/ETHPy150Open zulip/zulip/api/integrations/perforce/git_p4.py/main |
3,075 | def show(self, callback):
self.callback = callback
options = dict(
index=self.index
)
try:
response = self.client.indices.get_settings(**options)
except Exception as e:
return sublime.error_message("Error: {}".format(e))
self.choices... | KeyError | dataset/ETHPy150Open KunihikoKido/sublime-elasticsearch-client/panel/analyzer_list_panel.py/AnalyzerListPanel.show |
3,076 | @classmethod
def validate_template(cls):
y = re.findall(cls._MATCH_YEAR, cls._template)
m = re.findall(cls._MATCH_MONTH, cls._template)
c = re.findall(cls._MATCH_COUNTER, cls._template)
if len(y) > 1:
raise ValidationError('{year} can only be used once')
if len(m... | KeyError | dataset/ETHPy150Open django-bmf/django-bmf/djangobmf/core/numberrange.py/NumberRange.validate_template |
3,077 | @not_implemented_for('directed')
def find_cliques(G):
"""Search for all maximal cliques in a graph.
Maximal cliques are the largest complete subgraph containing
a given node. The largest maximal clique is sometimes called
the maximum clique.
Returns
-------
generator of lists: genetor of ... | KeyError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/algorithms/clique.py/find_cliques |
3,078 | def __descend_sections(self, key, create=False):
"""Traverse the nested mappings down to the last layer
"""
if self.base is None:
raise KeyError("Cannot access key in empty mapping")
try:
split_name = key.split(self.SECTION_SEPARATOR)
except __HOLE__ as er... | AttributeError | dataset/ETHPy150Open duerrp/pyexperiment/pyexperiment/utils/HierarchicalMapping.py/HierarchicalMapping.__descend_sections |
3,079 | def __getitem__(self, key):
"""Get an item
"""
section, subkey = self.__descend_sections(key)
# At the last section, get the value
try:
value = section[subkey]
except __HOLE__ as _err:
raise KeyError(
"Key '%s' does not exist" % key... | KeyError | dataset/ETHPy150Open duerrp/pyexperiment/pyexperiment/utils/HierarchicalMapping.py/HierarchicalMapping.__getitem__ |
3,080 | def __delitem__(self, key):
"""Delete an item
"""
section, subkey = self.__descend_sections(key)
# At the last section, set the value
try:
del section[subkey]
except __HOLE__ as _err:
raise KeyError(
"Key does not exist '%s'" % key) | KeyError | dataset/ETHPy150Open duerrp/pyexperiment/pyexperiment/utils/HierarchicalMapping.py/HierarchicalMapping.__delitem__ |
3,081 | def __iter__(self):
"""Need to define __iter__ to make it a MutableMapping
"""
iterator_list = [(iteritems(self.base or {}), '')]
while iterator_list:
iterator, prefix = iterator_list.pop()
try:
key, value = next(iterator)
if len(pr... | StopIteration | dataset/ETHPy150Open duerrp/pyexperiment/pyexperiment/utils/HierarchicalMapping.py/HierarchicalMapping.__iter__ |
3,082 | def get(self, key, default=None):
"""Get the key or return the default value if provided
"""
try:
return self[key]
except __HOLE__:
if default is not None:
return default
else:
raise | KeyError | dataset/ETHPy150Open duerrp/pyexperiment/pyexperiment/utils/HierarchicalMapping.py/HierarchicalMapping.get |
3,083 | def get_or_set(self, key, value):
"""Either gets the value associated with key or set it
This can be useful as an easy way of
"""
try:
return self[key]
except __HOLE__:
self[key] = value
return value | KeyError | dataset/ETHPy150Open duerrp/pyexperiment/pyexperiment/utils/HierarchicalMapping.py/HierarchicalMapping.get_or_set |
3,084 | def asShape(context):
"""Adapts the context to a geometry interface. The coordinates remain
stored in the context.
"""
if hasattr(context, "__geo_interface__"):
ob = context.__geo_interface__
else:
ob = context
try:
geom_type = ob.get("type").lower()
except __HOLE__:... | AttributeError | dataset/ETHPy150Open Toblerity/Shapely/shapely/geometry/geo.py/asShape |
3,085 | def __init__(self, filename, version=ID3V2_DEFAULT_VERSION):
"""
@param filename: the file to open or write to.
@type filename: string
@param version: if header doesn't exists, we need this to tell us what version \
header to use
@type version: float
... | IOError | dataset/ETHPy150Open Ciantic/pytagger/tagger/id3v2.py/ID3v2.__init__ |
3,086 | def __hash__(self):
try:
return self._hash
except __HOLE__:
self._hash = hash(self._comparison_key)
return self._hash | AttributeError | dataset/ETHPy150Open nltk/nltk/nltk/parse/chart.py/EdgeI.__hash__ |
3,087 | def to_internal_value(self, data):
if data is None:
return None
try:
return next(
user for user in
self.get_queryset()
if user._id == data
)
except __HOLE__:
self.fail('invalid_data') | StopIteration | dataset/ETHPy150Open CenterForOpenScience/osf.io/api/files/serializers.py/CheckoutField.to_internal_value |
3,088 | def is_uuid_like(val):
"""Returns validation of a value as a UUID.
For our purposes, a UUID is a canonical form string:
aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa
"""
try:
return str(uuid.UUID(val)) == val
except (TypeError, __HOLE__, AttributeError):
return False | ValueError | dataset/ETHPy150Open Havate/havate-openstack/proto-build/gui/horizon/Horizon_GUI/openstack_dashboard/openstack/common/uuidutils.py/is_uuid_like |
3,089 | def __lt__(self, other):
try:
return self.nums < other.nums
except __HOLE__:
return self.nums[0] < other | AttributeError | dataset/ETHPy150Open tabatkins/bikeshed/bikeshed/config.py/HierarchicalNumber.__lt__ |
3,090 | def __eq__(self, other):
try:
return self.nums == other.nums
except __HOLE__:
return self.nums[0] == other | AttributeError | dataset/ETHPy150Open tabatkins/bikeshed/bikeshed/config.py/HierarchicalNumber.__eq__ |
3,091 | def retrieveDataFile(filename, quiet=False, str=False):
cacheLocation = scriptPath + "/spec-data/" + filename
fallbackLocation = scriptPath + "/spec-data/readonly/" + filename
try:
fh = open(cacheLocation, 'r')
except __HOLE__:
try:
fh = open(fallbackLocation, 'r')
ex... | IOError | dataset/ETHPy150Open tabatkins/bikeshed/bikeshed/config.py/retrieveDataFile |
3,092 | def retrieveBoilerplateFile(self, name, group=None, status=None, error=True):
# Looks in three locations, in order:
# the folder the spec source is in, the group's boilerplate folder, and the generic boilerplate folder.
# In each location, it first looks for the file specialized on status, and then for the ... | IOError | dataset/ETHPy150Open tabatkins/bikeshed/bikeshed/config.py/retrieveBoilerplateFile |
3,093 | def runAnalysis(self):
""" Compute all the features that are currently selected, for the nodule and/or for
the surrounding spheres
"""
# build list of features and feature classes based on what is checked by the user
self.selectedMainFeaturesKeys = set()
self.selectedFeat... | StopIteration | dataset/ETHPy150Open acil-bwh/SlicerCIP/Scripted/CIP_LesionModel/CIP_LesionModel.py/CIP_LesionModelWidget.runAnalysis |
3,094 | def kill_kernel(self):
""" Kill the running kernel. """
if self.has_kernel:
# Pause the heart beat channel if it exists.
if self._hb_channel is not None:
self._hb_channel.pause()
# Attempt to kill the kernel.
try:
self.kern... | OSError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/zmq/kernelmanager.py/KernelManager.kill_kernel |
3,095 | def mkdirsp(path):
try:
os.makedirs(path)
except __HOLE__ as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise | OSError | dataset/ETHPy150Open openaddresses/machine/openaddr/cache.py/mkdirsp |
3,096 | def download(self, source_urls, workdir, conform=None):
output_files = []
download_path = os.path.join(workdir, 'esri')
mkdirsp(download_path)
query_fields = self.field_names_to_request(conform)
for source_url in source_urls:
size = 0
file_path = self.ge... | ValueError | dataset/ETHPy150Open openaddresses/machine/openaddr/cache.py/EsriRestDownloadTask.download |
3,097 | def run(statement, filename=None, sort=-1):
"""Run statement under profiler optionally saving results in filename
This function takes a single argument that can be passed to the
"exec" statement, and an optional file name. In all cases this
routine attempts to "exec" its first argument and gather prof... | SystemExit | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/profile.py/run |
3,098 | def runctx(statement, globals, locals, filename=None, sort=-1):
"""Run statement under profiler, supplying your own globals and locals,
optionally saving results in filename.
statement and filename have the same semantics as profile.run
"""
prof = Profile()
try:
prof = prof.runctx(state... | SystemExit | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/profile.py/runctx |
3,099 | def __init__(self, timer=None, bias=None):
self.timings = {}
self.cur = None
self.cmd = ""
self.c_func_name = ""
if bias is None:
bias = self.bias
self.bias = bias # Materialize in local dict for lookup speed.
if not timer:
if _has_re... | TypeError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/profile.py/Profile.__init__ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.