Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
5,600 | def parse_item(self, item):
"""
:param item: str, json-encoded string
"""
item = item.decode("utf-8")
try:
parsed_item = json.loads(item)
except __HOLE__:
parsed_item = None
else:
# append here just in case .get bellow fails
... | ValueError | dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/util.py/CommandResult.parse_item |
5,601 | def wait_for_command(logs_generator):
"""
using given generator, wait for it to raise StopIteration, which
indicates that docker has finished with processing
:return: list of str, logs
"""
logger.info("wait_for_command")
cr = CommandResult()
while True:
try:
item = n... | StopIteration | dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/util.py/wait_for_command |
5,602 | def clone_git_repo(git_url, target_dir, commit=None):
"""
clone provided git repo to target_dir, optionally checkout provided commit
:param git_url: str, git repo to clone
:param target_dir: str, filesystem path where the repo should be cloned
:param commit: str, commit to checkout, SHA-1 or ref
... | AttributeError | dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/util.py/clone_git_repo |
5,603 | def escape_dollar(v):
try:
str_type = unicode
except __HOLE__:
str_type = str
if isinstance(v, str_type):
return v.replace('$', r'\$')
else:
return v | NameError | dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/util.py/escape_dollar |
5,604 | def _process_plugin_substitution(mapping, key_parts, value):
try:
plugin_type, plugin_name, arg_name = key_parts
except __HOLE__:
logger.error("invalid absolute path '%s': it requires exactly three parts: "
"plugin type, plugin name, argument name (dot separated)",
... | ValueError | dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/util.py/_process_plugin_substitution |
5,605 | def get_version_of_tools():
"""
get versions of tools reactor is using (specified in constants.TOOLS_USED)
:returns list of dicts, [{"name": "docker-py", "version": "1.2.3"}, ...]
"""
response = []
for tool in TOOLS_USED:
pkg_name = tool["pkg_name"]
try:
tool_module ... | ImportError | dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/util.py/get_version_of_tools |
5,606 | def get_build_json():
try:
return json.loads(os.environ["BUILD"])
except __HOLE__:
logger.error("No $BUILD env variable. Probably not running in build container")
raise
# copypasted and slightly modified from
# http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-rea... | KeyError | dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/util.py/get_build_json |
5,607 | def decode_eventdata(sensor_type, offset, eventdata, sdr):
"""Decode extra event data from an alert or log
Provide a textual summary of eventdata per descriptions in
Table 42-3 of the specification. This is for sensor specific
offset events only.
:param sensor_type: The sensor type number from th... | KeyError | dataset/ETHPy150Open openstack/pyghmi/pyghmi/ipmi/events.py/decode_eventdata |
5,608 | def _populate_event(self, deassertion, event, event_data, event_type,
sensor_type, sensorid):
event['component_id'] = sensorid
try:
event['component'] = self._sdr.sensors[sensorid].name
except __HOLE__:
if sensorid == 0:
event['comp... | KeyError | dataset/ETHPy150Open openstack/pyghmi/pyghmi/ipmi/events.py/EventHandler._populate_event |
5,609 | def _get_user_model():
"""
Get the User Document class user for MongoEngine authentication.
Use the model defined in SOCIAL_AUTH_USER_MODEL if defined, or
defaults to MongoEngine's configured user document class.
"""
custom_model = getattr(settings, setting_name('USER_MODEL'), None)
if cust... | ImportError | dataset/ETHPy150Open omab/python-social-auth/social/apps/django_app/me/models.py/_get_user_model |
5,610 | def __init__(self, url, serverName, transporter,
entitlementDir, callLog):
try:
util.ServerProxy.__init__(self, url=url, transport=transporter)
except __HOLE__, e:
raise errors.OpenError('Error occurred opening repository '
'%s: %s' % (url, e)... | IOError | dataset/ETHPy150Open sassoftware/conary/conary/repository/netclient.py/ServerProxy.__init__ |
5,611 | def iterFilesInTrove(self, troveName, version, flavor,
sortByPath = False, withFiles = False,
capsules = False):
# XXX this code should most likely go away, and anything that
# uses it should be written to use other functions
l = [(troveName, (No... | KeyError | dataset/ETHPy150Open sassoftware/conary/conary/repository/netclient.py/NetworkRepositoryClient.iterFilesInTrove |
5,612 | @api.publicApi
def getTroves(self, troves, withFiles = True, callback = None):
"""
@param troves: List of troves to be retrieved
@type troves: list
@param withFiles: If set (default), retrieve files.
@type withFiles: bool
@raise RepositoryError: if a repository error ... | KeyError | dataset/ETHPy150Open sassoftware/conary/conary/repository/netclient.py/NetworkRepositoryClient.getTroves |
5,613 | def _getChangeSet(self, chgSetList, recurse = True, withFiles = True,
withFileContents = True, target = None,
excludeAutoSource = False, primaryTroveList = None,
callback = None, forceLocalGeneration = False,
changesetVersion = None... | IOError | dataset/ETHPy150Open sassoftware/conary/conary/repository/netclient.py/NetworkRepositoryClient._getChangeSet |
5,614 | def __init__(self, *args, **kwargs):
attrs = kwargs.setdefault('attrs', {})
try:
attrs['class'] = "%s autoresize" % (attrs['class'],)
except __HOLE__:
attrs['class'] = 'autoresize'
attrs.setdefault('cols', 80)
attrs.setdefault('rows', 5)
super(Auto... | KeyError | dataset/ETHPy150Open carljm/django-form-utils/form_utils/widgets.py/AutoResizeTextarea.__init__ |
5,615 | def __init__(self, *args, **kwargs):
attrs = kwargs.setdefault('attrs', {})
try:
attrs['class'] = "%s inline" % (attrs['class'],)
except __HOLE__:
attrs['class'] = 'inline'
attrs.setdefault('cols', 40)
attrs.setdefault('rows', 2)
super(InlineAutoRe... | KeyError | dataset/ETHPy150Open carljm/django-form-utils/form_utils/widgets.py/InlineAutoResizeTextarea.__init__ |
5,616 | def run (self):
self.daemon.daemonise()
# Make sure we create processes once we have closed file descriptor
# unfortunately, this must be done before reading the configuration file
# so we can not do it with dropped privileges
self.processes = Processes(self)
# we have to read the configuration possibly w... | KeyboardInterrupt | dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/reactor/loop.py/Reactor.run |
5,617 | def schedule (self):
try:
# read at least on message per process if there is some and parse it
for service,command in self.processes.received():
self.api.text(self,service,command)
# if we have nothing to do, return or save the work
if not self._running:
if not self._pending:
return False
... | KeyboardInterrupt | dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/reactor/loop.py/Reactor.schedule |
5,618 | def celery_teardown_request(error=None):
if error is not None:
_local.queue = []
return
try:
if queue():
if settings.USE_CELERY:
group(queue()).apply_async()
else:
for task in queue():
task.apply()
except __H... | AttributeError | dataset/ETHPy150Open CenterForOpenScience/osf.io/framework/celery_tasks/handlers.py/celery_teardown_request |
5,619 | def _get_checksum(path):
""" Generates a md5 checksum of the file at the specified path.
`path`
Path to file for checksum.
Returns string or ``None``
"""
# md5 uses a 512-bit digest blocks, let's scale by defined block_size
_md5 = hashlib.md5()
chunk_size = 128 * _... | IOError | dataset/ETHPy150Open xtrementl/focus/focus/plugin/modules/apps.py/_get_checksum |
5,620 | def _get_user_processes():
""" Gets process information owned by the current user.
Returns generator of tuples: (``psutil.Process`` instance, path).
"""
uid = os.getuid()
for proc in psutil.process_iter():
try:
# yield processes that match current user
if p... | OSError | dataset/ETHPy150Open xtrementl/focus/focus/plugin/modules/apps.py/_get_user_processes |
5,621 | def mkdir_p(path):
"""Create potentially nested directories as required.
Does nothing if the path already exists and is a directory.
"""
try:
os.makedirs(path)
except __HOLE__ as e:
if e.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise | OSError | dataset/ETHPy150Open radhermit/vimball/vimball/base.py/mkdir_p |
5,622 | def is_vimball(fd):
"""Test for vimball archive format compliance.
Simple check to see if the first line of the file starts with standard
vimball archive header.
"""
fd.seek(0)
try:
header = fd.readline()
except __HOLE__:
# binary files will raise exceptions when trying to d... | UnicodeDecodeError | dataset/ETHPy150Open radhermit/vimball/vimball/base.py/is_vimball |
5,623 | def __del__(self):
try:
self.fd.close()
except __HOLE__:
return | AttributeError | dataset/ETHPy150Open radhermit/vimball/vimball/base.py/Vimball.__del__ |
5,624 | @property
def files(self):
"""Yields archive file information."""
# try new file header format first, then fallback on old
for header in (r"(.*)\t\[\[\[1\n", r"^(\d+)\n$"):
header = re.compile(header)
filename = None
self.fd.seek(0)
line = self... | ValueError | dataset/ETHPy150Open radhermit/vimball/vimball/base.py/Vimball.files |
5,625 | def extract(self, extractdir=None, verbose=False):
"""Extract archive files to a directory."""
if extractdir is None:
filebase, ext = os.path.splitext(self.path)
if ext in ('.gz', '.bz2', '.xz'):
filebase, _ext = os.path.splitext(filebase)
extractdir =... | OSError | dataset/ETHPy150Open radhermit/vimball/vimball/base.py/Vimball.extract |
5,626 | def doctree_resolved(app, doctree, docname):
# replace numfig nodes with links
if app.builder.name in ('html', 'singlehtml', 'epub'):
env = app.builder.env
docname_figs = getattr(env, 'docname_figs', {})
docnames_by_figname = env.docnames_by_figname
figids = get... | IndexError | dataset/ETHPy150Open xraypy/xraylarch/doc/sphinx/ext/numfig.py/doctree_resolved |
5,627 | @pytest.fixture
def NINLayer_c01b(self):
try:
from lasagne.layers.cuda_convnet import NINLayer_c01b
except __HOLE__:
pytest.skip("cuda_convnet not available")
return NINLayer_c01b | ImportError | dataset/ETHPy150Open Lasagne/Lasagne/lasagne/tests/layers/test_dense.py/TestNINLayer_c01b.NINLayer_c01b |
5,628 | def RenderAFF4Object(obj, args=None):
"""Renders given AFF4 object into JSON-friendly data structure."""
args = args or []
cache_key = obj.__class__.__name__
try:
candidates = RENDERERS_CACHE[cache_key]
except __HOLE__:
candidates = []
for candidate in ApiAFF4ObjectRendererBase.classes.values():... | KeyError | dataset/ETHPy150Open google/grr/grr/gui/api_aff4_object_renderers.py/RenderAFF4Object |
5,629 | def is_string(var):
try:
return isinstance(var, basestring)
except __HOLE__:
return isinstance(var, str) | NameError | dataset/ETHPy150Open joke2k/faker/faker/utils/__init__.py/is_string |
5,630 | def autotype(s):
'''Automatively detect the type (int, float or string) of `s` and convert
`s` into it.'''
if not isinstance(s, str):
return s
if s.isdigit():
return int(s)
try:
return float(s)
except __HOLE__:
return s | ValueError | dataset/ETHPy150Open moskytw/clime/clime/util.py/autotype |
5,631 | @register.assignment_tag(name='webpack')
def webpack_template_tag(path_to_config):
"""
A template tag that will output a webpack bundle.
Usage:
{% load webpack %}
{% webpack 'path/to/webpack.config.js' as bundle %}
{{ bundle.render_css|safe }}
{{ bundle.render_js... | ValueError | dataset/ETHPy150Open markfinger/python-webpack/webpack/templatetags/webpack.py/webpack_template_tag |
5,632 | def main():
sc_prefs = SCPreferences()
from optparse import OptionParser
parser = OptionParser(__doc__.strip())
parser.add_option('--enable', dest='enable', action="store_true", default=True,
help='Enable proxy for the specified protocol'
)
parser.add_option('--disable', dest='enabl... | RuntimeError | dataset/ETHPy150Open MacSysadmin/pymacadmin/bin/set-proxy.py/main |
5,633 | def add_prefix(self):
""" Add prefix according to the specification.
The following keys can be used:
vrf ID of VRF to place the prefix in
prefix the prefix to add if already known
family address family (4 or 6)
descripti... | ValueError | dataset/ETHPy150Open SpriteLink/NIPAP/nipap-www/nipapwww/controllers/xhr.py/XhrController.add_prefix |
5,634 | def edit_prefix(self, id):
""" Edit a prefix.
"""
try:
p = Prefix.get(int(id))
# extract attributes
if 'prefix' in request.params:
p.prefix = request.params['prefix']
if 'type' in request.params:
p.type = request.... | ValueError | dataset/ETHPy150Open SpriteLink/NIPAP/nipap-www/nipapwww/controllers/xhr.py/XhrController.edit_prefix |
5,635 | def test(webapp):
try:
Root().register(webapp)
urlopen(webapp.server.http.base)
except __HOLE__ as e:
assert e.code == 500
else:
assert False | HTTPError | dataset/ETHPy150Open circuits/circuits/tests/web/test_request_failure.py/test |
5,636 | def _get_module_name(self, options):
try:
module_name = options.module_name
except __HOLE__: # pragma: no cover
module_name = options.model_name
return module_name | AttributeError | dataset/ETHPy150Open ellmetha/django-machina/tests/functional/admin/test_forum.py/TestForumAdmin._get_module_name |
5,637 | def emit(self, record):
try:
if getattr(record, 'append', False):
if self.appending:
self.stream.write(record.getMessage())
else:
self.stream.write(self.format(record))
self.appending = True
else:
... | KeyboardInterrupt | dataset/ETHPy150Open boto/requestbuilder/requestbuilder/logging.py/ProgressiveStreamHandler.emit |
5,638 | def configure_root_logger(use_color=False):
logfmt = '%(asctime)s %(levelname)-7s %(name)s %(message)s'
rootlogger = logging.getLogger('')
handler = ProgressiveStreamHandler()
if use_color:
formatter = ColoringFormatter(logfmt)
else:
formatter = logging.Formatter(logfmt)
handler.... | AttributeError | dataset/ETHPy150Open boto/requestbuilder/requestbuilder/logging.py/configure_root_logger |
5,639 | def stop(so, out, err):
basedir = so["basedir"]
dbfile = os.path.join(basedir, "petmail.db")
if not (os.path.isdir(basedir) and os.path.exists(dbfile)):
print >>err, "'%s' doesn't look like a Petmail basedir, quitting" % basedir
return 1
print >>out, "STOPPING", basedir
pidfile = os.... | OSError | dataset/ETHPy150Open warner/petmail/petmail/scripts/startstop.py/stop |
5,640 | def _cursor(self):
settings_dict = self.settings_dict
if self.connection is None or connection_pools[self.alias]['settings'] != settings_dict:
# Is this the initial use of the global connection_pools dictionary for
# this python interpreter? Build a ThreadedConnectionPool instan... | AttributeError | dataset/ETHPy150Open gmcguire/django-db-pool/dbpool/db/backends/postgresql_psycopg2/base.py/DatabaseWrapper14and15._cursor |
5,641 | def parse_address(rest):
if rest.startswith('['):
# remove first [] for ip
rest = rest.replace('[', '', 1).replace(']', '', 1)
pos = 0
while (pos < len(rest) and
not (rest[pos] == 'R' or rest[pos] == '/')):
pos += 1
address = rest[:pos]
rest = rest[pos:]
port... | TypeError | dataset/ETHPy150Open openstack/swift/swift/common/ring/utils.py/parse_address |
5,642 | def to_pydot(N, strict=True):
"""Return a pydot graph from a NetworkX graph N.
Parameters
----------
N : NetworkX graph
A graph created with NetworkX
Examples
--------
>>> K5 = nx.complete_graph(5)
>>> P = nx.nx_pydot.to_pydot(K5)
Notes
-----
"""
import pydotplu... | KeyError | dataset/ETHPy150Open networkx/networkx/networkx/drawing/nx_pydot.py/to_pydot |
5,643 | def setup_module(module):
from nose import SkipTest
try:
import pydotplus
except __HOLE__:
raise SkipTest("pydotplus not available") | ImportError | dataset/ETHPy150Open networkx/networkx/networkx/drawing/nx_pydot.py/setup_module |
5,644 | def parse (self, vstring):
# I've given up on thinking I can reconstruct the version string
# from the parsed tuple -- so I just store the string here for
# use by __str__
self.vstring = vstring
components = filter(lambda x: x and x != '.',
self.compon... | ValueError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/distutils/version.py/LooseVersion.parse |
5,645 | def include(self,tokens):
# Try to extract the filename and then process an include file
if not tokens:
return
if tokens:
if tokens[0].value != '<' and tokens[0].type != self.t_STRING:
tokens = self.expand_macros(tokens)
if tokens[0].value == ... | IOError | dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/maya/site-packages/pymel-1.0.3/pymel/util/external/ply/cpp.py/Preprocessor.include |
5,646 | def token(self):
try:
while True:
tok = self.parser.next()
if tok.type not in self.ignore: return tok
except __HOLE__:
self.parser = None
return None | StopIteration | dataset/ETHPy150Open CountZer0/PipelineConstructionSet/python/maya/site-packages/pymel-1.0.3/pymel/util/external/ply/cpp.py/Preprocessor.token |
5,647 | def start(self):
"""Start collecting trace information."""
if self._collectors:
self._collectors[-1].pause()
self._collectors.append(self)
#print("Started: %r" % self._collectors, file=sys.stderr)
# Check to see whether we had a fullcoverage tracer installed.
... | TypeError | dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/coverage/collector.py/Collector.start |
5,648 | def BuildTable(self, start_row, end_row, request):
"""Builds table of ClientCrash'es."""
crashes_urn = str(self.state.get("crashes_urn") or
request.REQ.get("crashes_urn"))
try:
collection = aff4.FACTORY.Open(crashes_urn,
aff4_type="PackedVers... | IOError | dataset/ETHPy150Open google/grr/grr/gui/plugins/crash_view.py/ClientCrashCollectionRenderer.BuildTable |
5,649 | def _get_failed_targets(self, tests_and_targets):
"""Return a mapping of target -> set of individual test cases that failed.
Targets with no failed tests are omitted.
Analyzes JUnit XML files to figure out which test had failed.
The individual test cases are formatted strings of the form org.foo.bar.... | ValueError | dataset/ETHPy150Open pantsbuild/pants/src/python/pants/backend/jvm/tasks/junit_run.py/JUnitRun._get_failed_targets |
5,650 | def __new__(cls, obj, sentinel=''):
try:
iterator = iter(obj)
except __HOLE__:
return IterI(obj, sentinel)
return IterO(iterator, sentinel) | TypeError | dataset/ETHPy150Open Eforcers/gae-flask-todo/lib/werkzeug/contrib/iterio.py/IterIO.__new__ |
5,651 | def seek(self, pos, mode=0):
if self.closed:
raise ValueError('I/O operation on closed file')
if mode == 1:
pos += self.pos
elif mode == 2:
self.read()
self.pos = min(self.pos, self.pos + pos)
return
elif mode != 0:
... | StopIteration | dataset/ETHPy150Open Eforcers/gae-flask-todo/lib/werkzeug/contrib/iterio.py/IterO.seek |
5,652 | def read(self, n=-1):
if self.closed:
raise ValueError('I/O operation on closed file')
if n < 0:
self._buf_append(_mixed_join(self._gen, self.sentinel))
result = self._buf[self.pos:]
self.pos += len(result)
return result
new_pos = self.... | StopIteration | dataset/ETHPy150Open Eforcers/gae-flask-todo/lib/werkzeug/contrib/iterio.py/IterO.read |
5,653 | def readline(self, length=None):
if self.closed:
raise ValueError('I/O operation on closed file')
nl_pos = -1
if self._buf:
nl_pos = self._buf.find(_newline(self._buf), self.pos)
buf = []
try:
pos = self.pos
while nl_pos < 0:
... | StopIteration | dataset/ETHPy150Open Eforcers/gae-flask-todo/lib/werkzeug/contrib/iterio.py/IterO.readline |
5,654 | @classmethod
def _validate(cls, value):
if not isinstance(value, basestring):
raise ValueError(value)
try:
return unicode(value)
except __HOLE__:
return unicode(value, 'utf-8') | UnicodeDecodeError | dataset/ETHPy150Open stepank/pyws/src/pyws/functions/args/types/simple.py/String._validate |
5,655 | @classmethod
def _validate(cls, value):
value, offset = cls.get_offset(value)
tz = cls.get_tzinfo(offset)
try:
return cls._parse(value).replace(tzinfo=tz)
except __HOLE__:
mo = re.search('\\.\d+$', value)
if not mo:
raise
... | ValueError | dataset/ETHPy150Open stepank/pyws/src/pyws/functions/args/types/simple.py/DateTime._validate |
5,656 | def run_only_if_boto_is_available(func):
try:
import boto
except __HOLE__:
boto = None
pred = lambda: boto is not None
return run_only(func, pred) | ImportError | dataset/ETHPy150Open BrightcoveOS/Diamond/src/collectors/elb/test/testelb.py/run_only_if_boto_is_available |
5,657 | def __getitem__(self, index):
"""
Retrieve a specific `BoundColumn` object.
*index* can either be 0-indexed or the name of a column
.. code-block:: python
columns['speed'] # returns a bound column with name 'speed'
columns[0] # returns the first column
... | StopIteration | dataset/ETHPy150Open bradleyayers/django-tables2/django_tables2/columns/base.py/BoundColumns.__getitem__ |
5,658 | @classmethod
def read(cls, reader, dump=None):
code = reader.read_u1()
# Create an index of all known opcodes.
if Opcode.opcodes is None:
Opcode.opcodes = {}
for name in globals():
klass = globals()[name]
try:
if nam... | TypeError | dataset/ETHPy150Open pybee/voc/voc/java/opcodes.py/Opcode.read |
5,659 | def tearDown(self):
try: os.unlink(self.fname1)
except OSError: pass
try: os.unlink(self.fname2)
except __HOLE__: pass | OSError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_binhex.py/BinHexTestCase.tearDown |
5,660 | @classmethod
def GetFilter(cls, filter_name):
"""Return an initialized filter. Only initialize filters once.
Args:
filter_name: The name of the filter, as a string.
Returns:
an initialized instance of the filter.
Raises:
DefinitionError if the type of filter has not been defined.
... | KeyError | dataset/ETHPy150Open google/grr/grr/lib/checks/filters.py/Filter.GetFilter |
5,661 | def Validate(self, expression):
"""Validates that a parsed rule entry is valid for fschecker.
Args:
expression: A rule expression.
Raises:
DefinitionError: If the filter definition could not be validated.
Returns:
True if the expression validated OK.
"""
parsed = self._Load(... | TypeError | dataset/ETHPy150Open google/grr/grr/lib/checks/filters.py/StatFilter.Validate |
5,662 | def py_encode_basestring_ascii(s):
if isinstance(s, str) and HAS_UTF8.search(s) is not None:
s = s.decode('utf-8')
def replace(match):
s = match.group(0)
try:
return ESCAPE_DCT[s]
except __HOLE__:
n = ord(s)
if n < 0x10000:
... | KeyError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/json/encoder.py/py_encode_basestring_ascii |
5,663 | def get_installed_libraries():
"""
Return the built-in template tag libraries and those from installed
applications. Libraries are stored in a dictionary where keys are the
individual module names, not the full module paths. Example:
django.templatetags.i18n is stored as i18n.
"""
libraries ... | ImportError | dataset/ETHPy150Open django/django/django/template/backends/django.py/get_installed_libraries |
5,664 | def get_package_libraries(pkg):
"""
Recursively yield template tag libraries defined in submodules of a
package.
"""
for entry in walk_packages(pkg.__path__, pkg.__name__ + '.'):
try:
module = import_module(entry[1])
except __HOLE__ as e:
raise InvalidTemplate... | ImportError | dataset/ETHPy150Open django/django/django/template/backends/django.py/get_package_libraries |
5,665 | def on_query_completions(self, view, prefix, locations):
results = []
try:
pos = locations[0]
env = getenv()
p = openProcess(["gocode", "-sock=tcp", "-addr=localhost:37777", "-f=json", "autocomplete", view.file_name().encode('utf-8'), str(pos)], env=env, stdin=subproc... | ValueError | dataset/ETHPy150Open newhook/gomode/gomode.py/GoModeAutocomplete.on_query_completions |
5,666 | def skip_if_not_available(modules=None, datasets=None, configurations=None):
"""Raises a SkipTest exception when requirements are not met.
Parameters
----------
modules : list
A list of strings of module names. If one of the modules fails to
import, the test will be skipped.
dataset... | IOError | dataset/ETHPy150Open mila-udem/fuel/tests/__init__.py/skip_if_not_available |
5,667 | def __new__(cls, library_path=''):
if library_path == '':
errs = []
for path in cls.get_library_paths():
try:
return cls(path)
except __HOLE__ as e:
logger.debug('Could not open VISA library %s: %s', path, str(e))
... | OSError | dataset/ETHPy150Open hgrecco/pyvisa/pyvisa/highlevel.py/VisaLibraryBase.__new__ |
5,668 | def get_last_status_in_session(self, session):
"""Last status in session.
Helper function to be called by resources properties.
"""
try:
return self._last_status_in_session[session]
except __HOLE__:
raise errors.Error('The session %r does not seem to be v... | KeyError | dataset/ETHPy150Open hgrecco/pyvisa/pyvisa/highlevel.py/VisaLibraryBase.get_last_status_in_session |
5,669 | def install_visa_handler(self, session, event_type, handler, user_handle=None):
"""Installs handlers for event callbacks.
:param session: Unique logical identifier to a session.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to... | TypeError | dataset/ETHPy150Open hgrecco/pyvisa/pyvisa/highlevel.py/VisaLibraryBase.install_visa_handler |
5,670 | def parse_resource_extended(self, session, resource_name):
"""Parse a resource string to get extended interface information.
Corresponds to viParseRsrcEx function of the VISA library.
:param session: Resource Manager session (should always be the Default Resource Manager for VISA
... | ValueError | dataset/ETHPy150Open hgrecco/pyvisa/pyvisa/highlevel.py/VisaLibraryBase.parse_resource_extended |
5,671 | def get_wrapper_class(backend_name):
"""Return the WRAPPER_CLASS for a given backend.
:rtype: pyvisa.highlevel.VisaLibraryBase
"""
try:
return _WRAPPERS[backend_name]
except __HOLE__:
if backend_name == 'ni':
from .ctwrapper import NIVisaLibrary
_WRAPPERS['ni... | KeyError | dataset/ETHPy150Open hgrecco/pyvisa/pyvisa/highlevel.py/get_wrapper_class |
5,672 | def open_visa_library(specification):
"""Helper function to create a VISA library wrapper.
In general, you should not use the function directly. The VISA library
wrapper will be created automatically when you create a ResourceManager object.
"""
try:
argument, wrapper = specification.split... | ValueError | dataset/ETHPy150Open hgrecco/pyvisa/pyvisa/highlevel.py/open_visa_library |
5,673 | def open_resource(self, resource_name,
access_mode=constants.AccessModes.no_lock,
open_timeout=constants.VI_TMO_IMMEDIATE,
resource_pyclass=None,
**kwargs):
"""Return an instrument for the resource name.
:param reso... | AttributeError | dataset/ETHPy150Open hgrecco/pyvisa/pyvisa/highlevel.py/ResourceManager.open_resource |
5,674 | def script_paths(self, script_name):
"""Returns the sys.path prefix appropriate for this script.
Args:
script_name: the basename of the script, for example 'appcfg.py'.
"""
try:
return self._script_to_paths[script_name]
except __HOLE__:
raise KeyError('Script name %s not recognize... | KeyError | dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/wrapper_util.py/Paths.script_paths |
5,675 | def test_makepyfile_unicode(testdir):
global unichr
try:
unichr(65)
except __HOLE__:
unichr = chr
testdir.makepyfile(unichr(0xfffd)) | NameError | dataset/ETHPy150Open pytest-dev/pytest/testing/test_pytester.py/test_makepyfile_unicode |
5,676 | @register.tag(name='change_currency')
def change_currency(parser, token):
try:
tag_name, current_price, new_currency = token.split_contents()
except __HOLE__:
raise template.TemplateSyntaxError, \
'%r tag requires exactly two arguments' % token.contents.split()[0]
return ChangeCu... | ValueError | dataset/ETHPy150Open hassanch/django-currencies/currencies/templatetags/currency.py/change_currency |
5,677 | def can_user_vote(self, user):
"""
Test whether the passed user is allowed to vote on this
review
"""
if not user.is_authenticated():
return False, _(u"Only signed in users can vote")
vote = self.votes.model(review=self, user=user, delta=1)
try:
... | ValidationError | dataset/ETHPy150Open django-oscar/django-oscar/src/oscar/apps/catalogue/reviews/abstract_models.py/AbstractProductReview.can_user_vote |
5,678 | def switch(name, ip=None, netmask=None, gateway=None, dhcp=None,
password=None, snmp=None):
'''
Manage switches in a Dell Chassis.
name
The switch designation (e.g. switch-1, switch-2)
ip
The Static IP Address of the switch
netmask
The netmask for the stati... | AttributeError | dataset/ETHPy150Open saltstack/salt/salt/states/dellchassis.py/switch |
5,679 | def update_ca_bundle(
target=None,
source=None,
opts=None,
merge_files=None,
):
'''
Attempt to update the CA bundle file from a URL
If not specified, the local location on disk (``target``) will be
auto-detected, if possible. If it is not found, then a new location o... | IOError | dataset/ETHPy150Open saltstack/salt/salt/utils/http.py/update_ca_bundle |
5,680 | def _get_datastore(self, datastore_name=None):
"""
Returns the couch datastore instance and datastore name.
This caches the datastore instance to avoid an explicit lookup to save on http request.
The consequence is that if another process deletes the datastore in the meantime, we will fa... | ValueError | dataset/ETHPy150Open ooici/pyon/pyon/datastore/couchbase/base_store.py/CouchbaseDataStore._get_datastore |
5,681 | def _cache_morlist_process(self, instance):
""" Empties the self.morlist_raw by popping items and running asynchronously
the _cache_morlist_process_atomic operation that will get the available
metrics for this MOR and put it in self.morlist
"""
i_key = self._instance_key(instance... | KeyError | dataset/ETHPy150Open serverdensity/sd-agent/checks.d/vsphere.py/VSphereCheck._cache_morlist_process |
5,682 | def get_i18n_js(self):
"""Generates a Javascript body for i18n in Javascript.
If you want to load these javascript code from a static HTML
file, you need to create another handler which just returns
the code generated by this function.
Returns:
Actual javascript cod... | IOError | dataset/ETHPy150Open GoogleCloudPlatform/python-docs-samples/appengine/i18n/i18n_utils.py/BaseHandler.get_i18n_js |
5,683 | def escapeChar(match):
c=match.group(0)
try:
replacement = CharReplacements[c]
return replacement
except __HOLE__:
d = ord(c)
if d < 32:
return '\\u%04x' % d
else:
return c | KeyError | dataset/ETHPy150Open blinktrade/bitex/libs/jsonrpc/json.py/escapeChar |
5,684 | def loads(s):
stack = []
chars = iter(s)
value = None
currCharIsNext=False
try:
while(1):
skip = False
if not currCharIsNext:
c = chars.next()
while(c in [' ', '\t', '\r','\n']):
c = chars.next()
currCharIsNext=... | StopIteration | dataset/ETHPy150Open blinktrade/bitex/libs/jsonrpc/json.py/loads |
5,685 | def downloadBooks(self,titles=None,formats=None): #titles= list('C# tutorial', 'c++ Tutorial') ; format=tuple('pdf','mobi','epub','code')
try:
#download ebook
if formats is None:
formats=('pdf','mobi','epub','code')
if titles is not None:
te... | IOError | dataset/ETHPy150Open igbt6/Packt-Publishing-Free-Learning/packtFreeBookDownloader.py/MyPacktPublishingBooksDownloader.downloadBooks |
5,686 | def process(self, event):
if self.field in event:
data = event[self.field]
try:
fields = self._decode(data)
self.logger.debug('syslog decoded: %s' % fields)
event.update(fields)
if self.consume:
del even... | ValueError | dataset/ETHPy150Open artirix/logcabin/logcabin/filters/syslog.py/Syslog.process |
5,687 | def _decode(self, data):
m = self.re_syslog.match(data)
if m:
d = m.groupdict()
prio = int(d.pop('prio'))
try:
d['facility'] = self.facilities[prio >> 3]
except __HOLE__:
d['facility'] = 'unkn... | IndexError | dataset/ETHPy150Open artirix/logcabin/logcabin/filters/syslog.py/Syslog._decode |
5,688 | def store_assertion(self, assertion, to_sign):
self.assertion[assertion.id] = (assertion, to_sign)
key = sha1(code(assertion.subject.name_id)).hexdigest()
try:
self.authn[key].append(assertion.authn_statement)
except __HOLE__:
self.authn[key] = [assertion.authn_st... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/sdb.py/SessionStorage.store_assertion |
5,689 | def get_authn_statements(self, name_id, session_index=None,
requested_context=None):
"""
:param name_id:
:param session_index:
:param requested_context:
:return:
"""
result = []
key = sha1(code(name_id)).hexdigest()
tr... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/sdb.py/SessionStorage.get_authn_statements |
5,690 | def removeObserver(self, observer):
"""
Unregisters an observer with this publisher.
@param observer: An L{ILogObserver} to remove.
"""
try:
self._observers.remove(observer)
except __HOLE__:
pass | ValueError | dataset/ETHPy150Open twisted/twisted/twisted/logger/_observer.py/LogPublisher.removeObserver |
5,691 | @staticmethod
def coerce(a, b):
if isinstance(a, string_types) and isinstance(b, string_types):
return sort_normalize_string(a), sort_normalize_string(b)
if type(a) is type(b):
return a, b
if isinstance(a, Undefined) or isinstance(b, Undefined):
if isinsta... | ValueError | dataset/ETHPy150Open lektor/lektor/lektor/db.py/_CmpHelper.coerce |
5,692 | def __lt__(self, other):
a, b = self.coerce(self.value, other.value)
try:
if self.reverse:
return b < a
return a < b
except __HOLE__:
# Put None at the beginning if reversed, else at the end.
if self.reverse:
return ... | TypeError | dataset/ETHPy150Open lektor/lektor/lektor/db.py/_CmpHelper.__lt__ |
5,693 | def __eval__(self, record):
try:
return record[self.__field]
except __HOLE__:
return Undefined(obj=record, name=self.__field) | KeyError | dataset/ETHPy150Open lektor/lektor/lektor/db.py/_RecordQueryField.__eval__ |
5,694 | def __getitem__(self, name):
try:
return self.__getattr__(name)
except __HOLE__:
raise KeyError(name) | AttributeError | dataset/ETHPy150Open lektor/lektor/lektor/db.py/_RecordQueryProxy.__getitem__ |
5,695 | @cached_property
def _siblings(self):
parent = self.parent
pagination_enabled = parent.datamodel.pagination_config.enabled
# Don't track dependencies for this part.
with Context(pad=self.pad):
if pagination_enabled:
pagination = parent.pagination
... | ValueError | dataset/ETHPy150Open lektor/lektor/lektor/db.py/Page._siblings |
5,696 | def load_raw_data(self, path, alt=PRIMARY_ALT, cls=None,
fallback=True):
"""Internal helper that loads the raw record data. This performs
very little data processing on the data.
"""
path = cleanup_path(path)
if cls is None:
cls = dict
... | IOError | dataset/ETHPy150Open lektor/lektor/lektor/db.py/Database.load_raw_data |
5,697 | def iter_items(self, path, alt=PRIMARY_ALT):
"""Iterates over all items below a path and yields them as
tuples in the form ``(id, alt, is_attachment)``.
"""
fn_base = self.to_fs_path(path)
if alt is None:
alts = self.config.list_alternatives()
single_alt ... | IOError | dataset/ETHPy150Open lektor/lektor/lektor/db.py/Database.iter_items |
5,698 | def persist(self, record):
"""Persists a record. This will put it into the persistent cache."""
cache_key = self._get_cache_key(record)
self.persistent[cache_key] = record
try:
del self.ephemeral[cache_key]
except __HOLE__:
pass | KeyError | dataset/ETHPy150Open lektor/lektor/lektor/db.py/RecordCache.persist |
5,699 | def kill(self, sig):
"""Attempt to kill the process if it still seems to be running. """
if self._exit_status is not None:
raise OSError(errno.ESRCH, os.strerror(errno.ESRCH))
try:
result = os.kill(self.pid(), sig)
except __HOLE__, e:
# not much we can... | OSError | dataset/ETHPy150Open boakley/robotframework-workbench/rwb/runner/tsubprocess.py/Process.kill |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.