Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
4,300 | def decompressing_file(FILE_TO_DECOMPRESS):
try:
f_in = gzip.open(FILE_TO_DECOMPRESS, 'rb')
contend = f_in.read()
f_in.close()
file_dec = FILE_TO_DECOMPRESS.split('.')[0] + '.txt'
f_out = open(file_dec, 'w')
f_out.writelines(contend)
f_out.close()
r... | IOError | dataset/ETHPy150Open bt3gl/Neat-Problems-in-Python-and-Flask/Version-Control/src/system_operations.py/decompressing_file |
4,301 | def handle_label(self, project_name, **options):
# Determine the project_name a bit naively -- by looking at the name of
# the parent directory.
directory = os.getcwd()
# Check that the project_name cannot be imported.
try:
import_module(project_name)
except ... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/core/management/commands/startproject.py/Command.handle_label |
4,302 | def ensure_asyncio():
try:
import asyncio
except __HOLE__:
file, pathname, description = imp.find_module('trollius')
try:
asyncio = imp.load_module('asyncio', file, pathname, description)
finally:
if file is not None:
try:
... | ImportError | dataset/ETHPy150Open foxdog-studios/pyddp/ddp/utils.py/ensure_asyncio |
4,303 | def _has_property(self, subject, name, *args):
if args:
try:
value = getattr(subject, name)
except __HOLE__:
return False, 'property {0!r} not found'.format(name)
else:
expected_value = default_matcher(args[0])
r... | AttributeError | dataset/ETHPy150Open jaimegildesagredo/expects/expects/matchers/built_in/have_properties.py/_PropertyMatcher._has_property |
4,304 | def __init__(self, *args, **kwargs):
try:
self._expected = (), dict(*args, **kwargs)
except (__HOLE__, ValueError):
self._expected = args, kwargs | TypeError | dataset/ETHPy150Open jaimegildesagredo/expects/expects/matchers/built_in/have_properties.py/have_properties.__init__ |
4,305 | def get_buf_by_path(self, path):
try:
p = utils.to_rel_path(path)
except __HOLE__:
return
buf_id = self.paths_to_ids.get(p)
if buf_id:
return self.bufs.get(buf_id) | ValueError | dataset/ETHPy150Open Floobits/floobits-sublime/floo/common/handlers/floo_handler.py/FlooHandler.get_buf_by_path |
4,306 | def _on_delete_buf(self, data):
buf_id = data['id']
try:
buf = self.bufs.get(buf_id)
if buf:
del self.paths_to_ids[buf['path']]
del self.bufs[buf_id]
except __HOLE__:
msg.debug('KeyError deleting buf id ', buf_id)
# TODO... | KeyError | dataset/ETHPy150Open Floobits/floobits-sublime/floo/common/handlers/floo_handler.py/FlooHandler._on_delete_buf |
4,307 | def _on_saved(self, data):
buf_id = data['id']
buf = self.bufs.get(buf_id)
if not buf:
return
on_view_load = self.on_load.get(buf_id)
if on_view_load:
try:
del on_view_load['patch']
except __HOLE__:
pass
... | KeyError | dataset/ETHPy150Open Floobits/floobits-sublime/floo/common/handlers/floo_handler.py/FlooHandler._on_saved |
4,308 | def _rate_limited_upload(self, paths_iter, total_bytes, bytes_uploaded=0.0, upload_func=None):
reactor.tick()
upload_func = upload_func or (lambda x: self._upload(utils.get_full_path(x)))
if len(self.proto) > 0:
self.upload_timeout = utils.set_timeout(self._rate_limited_upload, 10, p... | StopIteration | dataset/ETHPy150Open Floobits/floobits-sublime/floo/common/handlers/floo_handler.py/FlooHandler._rate_limited_upload |
4,309 | def _upload(self, path, text=None):
size = 0
try:
if text is None:
with open(path, 'rb') as buf_fd:
buf = buf_fd.read()
else:
try:
# work around python 3 encoding issue
buf = text.encode('... | OSError | dataset/ETHPy150Open Floobits/floobits-sublime/floo/common/handlers/floo_handler.py/FlooHandler._upload |
4,310 | def quit(self, quit_command='qa!'):
"""Send a quit command to Nvim.
By default, the quit command is 'qa!' which will make Nvim quit without
saving anything.
"""
try:
self.command(quit_command)
except __HOLE__:
# sending a quit command will raise a... | IOError | dataset/ETHPy150Open neovim/python-client/neovim/api/nvim.py/Nvim.quit |
4,311 | def main(argv=sys.argv[1:]):
"""Parses the command line comments."""
usage = 'usage: %prog [options] FILE\n\n' + __doc__
parser = OptionParser(usage)
# options
parser.add_option("-f", "--force",
action='store_true', default=False,
help="make changes even ... | IOError | dataset/ETHPy150Open neovim/python-client/scripts/logging_statement_modifier.py/main |
4,312 | def first_arg_to_level_name(arg):
"""Decide what level the argument specifies and return it. The argument
must contain (case-insensitive) one of the values in LEVELS or be an integer
constant. Otherwise None will be returned."""
try:
return int(arg)
except __HOLE__:
arg = arg.upper... | ValueError | dataset/ETHPy150Open neovim/python-client/scripts/logging_statement_modifier.py/first_arg_to_level_name |
4,313 | def get_level_value(level):
"""Returns the logging value associated with a particular level name. The
argument must be present in LEVELS_DICT or be an integer constant.
Otherwise None will be returned."""
try:
# integral constants also work: they are the level value
return int(level)
... | ValueError | dataset/ETHPy150Open neovim/python-client/scripts/logging_statement_modifier.py/get_level_value |
4,314 | def _loop_until(self, predicate):
self._until_predicate = predicate
try:
# this runs self._next ONE time, but
# self._next re-runs itself until
# the predicate says to quit.
self._loop.add_callback(self._next)
self._loop.start()
except ... | KeyboardInterrupt | dataset/ETHPy150Open bokeh/bokeh/bokeh/client/_connection.py/ClientConnection._loop_until |
4,315 | @gen.coroutine
def _pop_message(self):
while True:
if self._socket is None:
raise gen.Return(None)
# log.debug("Waiting for fragment...")
fragment = None
try:
fragment = yield self._socket.read_message()
except Exce... | ValidationError | dataset/ETHPy150Open bokeh/bokeh/bokeh/client/_connection.py/ClientConnection._pop_message |
4,316 | def do_full_push(self):
try:
bundle = {"labels": {}}
for key, value in self.wallet.labels.iteritems():
encoded = self.encode(key)
bundle["labels"][encoded] = self.encode(value)
params = json.dumps(bundle)
connection = httplib.HTTPC... | ValueError | dataset/ETHPy150Open bitxbay/BitXBay/electru/build/lib/electrum_plugins/labels.py/Plugin.do_full_push |
4,317 | def do_full_pull(self, force = False):
try:
connection = httplib.HTTPConnection(self.target_host)
connection.request("GET", ("/api/wallets/%s/labels.json?auth_token=%s" % (self.wallet_id, self.auth_token())),"", {'Content-Type': 'application/json'})
response = connection.getr... | ValueError | dataset/ETHPy150Open bitxbay/BitXBay/electru/build/lib/electrum_plugins/labels.py/Plugin.do_full_pull |
4,318 | def upgrade(self):
if not os.path.exists(self.folder_path):
print("Error: instance folder does not exist")
sys.exit(1)
try:
actual_path = iepy.setup(self.folder_path, _safe_mode=True)
except __HOLE__ as err:
print(err)
sys.exit(1)
... | ValueError | dataset/ETHPy150Open machinalis/iepy/iepy/instantiation/instance_admin.py/InstanceManager.upgrade |
4,319 | def RenderBranch(self, path, request):
"""Renders tree leafs for flows."""
# Retrieve the user's GUI mode preferences.
self.user = request.user
try:
user_record = aff4.FACTORY.Open(
aff4.ROOT_URN.Add("users").Add(self.user), "GRRUser",
token=request.token)
user_preferenc... | IOError | dataset/ETHPy150Open google/grr/grr/gui/plugins/flow_management.py/FlowTree.RenderBranch |
4,320 | def Layout(self, request, response):
"""Update the progress bar based on the progress reported."""
self.flow_name = request.REQ.get("flow_path", "").split("/")[-1]
try:
flow_class = flow.GRRFlow.classes[self.flow_name]
if not aff4.issubclass(flow_class, flow.GRRFlow):
return response
... | KeyError | dataset/ETHPy150Open google/grr/grr/gui/plugins/flow_management.py/FlowInformation.Layout |
4,321 | def RenderAjax(self, request, response):
"""Parse the flow args from the form and launch the flow."""
self.flow_name = self._GetFlowName(request)
self.client_id = request.REQ.get("client_id", None)
self.dom_node = request.REQ.get("dom_node")
flow_cls = flow.GRRFlow.classes.get(self.flow_name)
i... | ValueError | dataset/ETHPy150Open google/grr/grr/gui/plugins/flow_management.py/SemanticProtoFlowForm.RenderAjax |
4,322 | def Layout(self, request, response):
try:
self.icon, self.title = self.state_map[str(self.proxy)]
except (__HOLE__, ValueError):
pass
super(FlowStateIcon, self).Layout(request, response) | KeyError | dataset/ETHPy150Open google/grr/grr/gui/plugins/flow_management.py/FlowStateIcon.Layout |
4,323 | def _GetCreationTime(self, obj):
try:
return obj.state.context.get("create_time")
except __HOLE__:
return obj.Get(obj.Schema.LAST, 0) | AttributeError | dataset/ETHPy150Open google/grr/grr/gui/plugins/flow_management.py/ListFlowsTable._GetCreationTime |
4,324 | def BuildTable(self, start_row, end_row, request):
"""Renders the table."""
depth = request.REQ.get("depth", 0)
flow_urn = self.state.get("value", request.REQ.get("value"))
if flow_urn is None:
client_id = request.REQ.get("client_id")
if not client_id: return
flow_urn = rdf_client.Cl... | AttributeError | dataset/ETHPy150Open google/grr/grr/gui/plugins/flow_management.py/ListFlowsTable.BuildTable |
4,325 | def Layout(self, request, response):
"""Introspect the Schema for flow objects."""
try:
self.state["flow"] = session_id = request.REQ["flow"]
self.fd = aff4.FACTORY.Open(session_id, token=request.token,
age=aff4.ALL_TIMES)
self.classes = self.RenderAFF4Attribu... | KeyError | dataset/ETHPy150Open google/grr/grr/gui/plugins/flow_management.py/ShowFlowInformation.Layout |
4,326 | @wsgi.action("disassociate")
def _disassociate_host_and_project(self, req, id, body):
context = req.environ['nova.context']
authorize(context)
# NOTE(shaohe-feng): back-compatible with db layer hard-code
# admin permission checks. call db API objects.Network.associate
nova_c... | NotImplementedError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/api/openstack/compute/legacy_v2/contrib/os_networks.py/NetworkController._disassociate_host_and_project |
4,327 | def add(self, req, body):
context = req.environ['nova.context']
authorize(context)
# NOTE(shaohe-feng): back-compatible with db layer hard-code
# admin permission checks. call db API objects.Network.associate
nova_context.require_admin_context(context)
if not body:
... | NotImplementedError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/api/openstack/compute/legacy_v2/contrib/os_networks.py/NetworkController.add |
4,328 | def legal_moves(self, position):
""" Obtain legal moves and where they lead.
Parameters
----------
position : tuple of int (x, y)
the position to start at
Returns
-------
legal_moves_dict : dict mapping strings (moves) to positions (x, y)
... | IndexError | dataset/ETHPy150Open ASPP/pelita/pelita/datamodel.py/CTFUniverse.legal_moves |
4,329 | def cache(time_to_wait = None, resource_manager = None):
""" cache(time in float seconds) -> decorator
Given "time" seconds (float), this decorator will cache during that
time the output of the decorated function. This way, if someone calls
the cache object with the same input within the next "time" ti... | KeyError | dataset/ETHPy150Open weblabdeusto/weblabdeusto/server/src/voodoo/cache.py/cache |
4,330 | def __call__(self, *args):
try:
if self._inst is not None:
args = (self._inst(),) + args
if args in self.cache:
return self.cache[args]
else:
return_value = self.func(*args)
self.cache[args] = return_value
... | TypeError | dataset/ETHPy150Open weblabdeusto/weblabdeusto/server/src/voodoo/cache.py/fast_cache.__call__ |
4,331 | @property
def status(self):
try:
return self.result.status
except __HOLE__:
return _('Undecided') | ObjectDoesNotExist | dataset/ETHPy150Open pinax/symposion/symposion/proposals/models.py/ProposalBase.status |
4,332 | def test_issue_7754(self):
try:
old_cwd = os.getcwd()
except OSError:
# Jenkins throws an OSError from os.getcwd()??? Let's not worry
# about it
old_cwd = None
config_dir = os.path.join(integration.TMP, 'issue-7754')
if not os.path.isdir(c... | AssertionError | dataset/ETHPy150Open saltstack/salt/tests/integration/shell/cp.py/CopyTest.test_issue_7754 |
4,333 | def decode(self, jwt, key='', verify=True, algorithms=None, options=None,
**kwargs):
payload, signing_input, header, signature = self._load(jwt)
decoded = super(PyJWT, self).decode(jwt, key, verify, algorithms,
options, **kwargs)
try:
... | ValueError | dataset/ETHPy150Open jpadilla/pyjwt/jwt/api_jwt.py/PyJWT.decode |
4,334 | def _validate_iat(self, payload, now, leeway):
try:
iat = int(payload['iat'])
except __HOLE__:
raise DecodeError('Issued At claim (iat) must be an integer.')
if iat > (now + leeway):
raise InvalidIssuedAtError('Issued At claim (iat) cannot be in'
... | ValueError | dataset/ETHPy150Open jpadilla/pyjwt/jwt/api_jwt.py/PyJWT._validate_iat |
4,335 | def _validate_nbf(self, payload, now, leeway):
try:
nbf = int(payload['nbf'])
except __HOLE__:
raise DecodeError('Not Before claim (nbf) must be an integer.')
if nbf > (now + leeway):
raise ImmatureSignatureError('The token is not yet valid (nbf)') | ValueError | dataset/ETHPy150Open jpadilla/pyjwt/jwt/api_jwt.py/PyJWT._validate_nbf |
4,336 | def _validate_exp(self, payload, now, leeway):
try:
exp = int(payload['exp'])
except __HOLE__:
raise DecodeError('Expiration Time claim (exp) must be an'
' integer.')
if exp < (now - leeway):
raise ExpiredSignatureError('Signatur... | ValueError | dataset/ETHPy150Open jpadilla/pyjwt/jwt/api_jwt.py/PyJWT._validate_exp |
4,337 | def _apply_skill(self, skill):
if skill.auto_start:
skill.invoke(self)
else:
self.enhance_soul(skill)
try:
self.fight.update_skills()
except __HOLE__:
pass | AttributeError | dataset/ETHPy150Open genzgd/Lampost-Mud/lampost/lpmud/entity.py/EntityLP._apply_skill |
4,338 | def remove_skill(self, skill_id):
try:
skill = self.skills.pop(skill_id)
if skill.auto_start:
skill.revoke(self)
else:
self.diminish_soul(skill)
self.fight.update_skills()
except __HOLE__:
raise ActionError('{} ... | KeyError | dataset/ETHPy150Open genzgd/Lampost-Mud/lampost/lpmud/entity.py/EntityLP.remove_skill |
4,339 | def check_status(self):
if self.health <= 0:
self._cancel_actions()
self.fight.end_all()
self.die()
else:
self.start_refresh()
self.status_change()
try:
self.last_opponent.status_change()
except __HOLE__:
pas... | AttributeError | dataset/ETHPy150Open genzgd/Lampost-Mud/lampost/lpmud/entity.py/EntityLP.check_status |
4,340 | def _cancel_actions(self):
if self._current_action:
unregister(self._current_action[2])
del self._current_action
try:
del self._action_target
except __HOLE__:
pass
if self._next_command:
del self._next_command | AttributeError | dataset/ETHPy150Open genzgd/Lampost-Mud/lampost/lpmud/entity.py/EntityLP._cancel_actions |
4,341 | def parse_body(self):
try:
js = json.loads(self.body)
return js
except __HOLE__:
return self.body | ValueError | dataset/ETHPy150Open secondstory/dewpoint/libcloud/drivers/vpsnet.py/VPSNetResponse.parse_body |
4,342 | def parse_error(self):
try:
errors = json.loads(self.body)['errors'][0]
except __HOLE__:
return self.body
else:
return "\n".join(errors) | ValueError | dataset/ETHPy150Open secondstory/dewpoint/libcloud/drivers/vpsnet.py/VPSNetResponse.parse_error |
4,343 | def __init__(self, *args, **kwargs):
self._fname = None
if 'file_path' in kwargs:
self.file_path = kwargs.pop('file_path')
else:
self.file_path = getattr(settings, 'EMAIL_FILE_PATH',None)
# Make sure self.file_path is a string.
if not isinstance(self.file_... | OSError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/core/mail/backends/filebased.py/EmailBackend.__init__ |
4,344 | def __django_version_setup():
"""Selects a particular Django version to load."""
django_version = _config_handle.django_version
if django_version is not None:
from google.appengine.dist import use_library
use_library('django', str(django_version))
else:
from google.appengine.dist import _libra... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/ext/webapp/__init__.py/__django_version_setup |
4,345 | def _django_setup():
"""Imports and configures Django.
This can be overridden by defining a function named
webapp_django_setup() in the app's appengine_config.py file (see
lib_config docs). Such a function should import and configure
Django.
In the Python 2.5 runtime, you can also just configure the Djan... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/ext/webapp/__init__.py/_django_setup |
4,346 | def read(self, n=None):
self.nbytes = n
try:
str = next(self.read_it)
except __HOLE__:
str = ""
return str
# required by postgres2 driver, but not used | StopIteration | dataset/ETHPy150Open PyTables/PyTables/bench/postgres_backend.py/StreamChar.read |
4,347 | def _toint(self, it):
try:
return int(it)
except __HOLE__:
return it | ValueError | dataset/ETHPy150Open kdart/pycopia/core/pycopia/OS/Win32/procfs.py/ProcStat._toint |
4,348 | def get_stat(self, name):
if not self.stats:
raise ValueError, "no stats - run read(pid)"
try:
return self.stats[self._STATINDEX[name]]
except __HOLE__:
raise ValueError, "no attribute %s" % name | KeyError | dataset/ETHPy150Open kdart/pycopia/core/pycopia/OS/Win32/procfs.py/ProcStat.get_stat |
4,349 | def __getattr__(self, name):
try:
return self.get_stat(name)
except __HOLE__, err:
raise AttributeError, err | ValueError | dataset/ETHPy150Open kdart/pycopia/core/pycopia/OS/Win32/procfs.py/ProcStat.__getattr__ |
4,350 | def __getitem__(self, name):
try:
return getattr(self, name)
except __HOLE__, err:
raise KeyError, err | AttributeError | dataset/ETHPy150Open kdart/pycopia/core/pycopia/OS/Win32/procfs.py/ProcStat.__getitem__ |
4,351 | def tree(self):
self.read()
for p in self._ptable.values():
try:
self._ptable[p.ppid]._children.append(p.pid)
except __HOLE__: # no child list yet
self._ptable[p.ppid]._children = sortedlist([p.pid])
pslist = self._tree_helper(self._ptabl... | AttributeError | dataset/ETHPy150Open kdart/pycopia/core/pycopia/OS/Win32/procfs.py/ProcStatTable.tree |
4,352 | def __getattr__ (self, key):
try:
return getattr (self.cursor, key)
except __HOLE__:
try:
val = self.cursor[unicode (key)]
if (type (val) == list) or (type (val) == dict):
return MongoWrapper (self.cursor[unicode (key)])
... | AttributeError | dataset/ETHPy150Open dotskapes/dotSkapes/models/001_db.py/MongoWrapper.__getattr__ |
4,353 | def validate_positive_float(option, value):
"""Validates that 'value' is a float, or can be converted to one, and is
positive.
"""
errmsg = "%s must be an integer or float" % (option,)
try:
value = float(value)
except __HOLE__:
raise ValueError(errmsg)
except TypeError:
... | ValueError | dataset/ETHPy150Open mongodb/mongo-python-driver/pymongo/common.py/validate_positive_float |
4,354 | def validate_read_preference_mode(dummy, name):
"""Validate read preference mode for a MongoReplicaSetClient.
"""
try:
return read_pref_mode_from_name(name)
except __HOLE__:
raise ValueError("%s is not a valid read preference" % (name,)) | ValueError | dataset/ETHPy150Open mongodb/mongo-python-driver/pymongo/common.py/validate_read_preference_mode |
4,355 | def validate_uuid_representation(dummy, value):
"""Validate the uuid representation option selected in the URI.
"""
try:
return _UUID_REPRESENTATIONS[value]
except __HOLE__:
raise ValueError("%s is an invalid UUID representation. "
"Must be one of "
... | KeyError | dataset/ETHPy150Open mongodb/mongo-python-driver/pymongo/common.py/validate_uuid_representation |
4,356 | def validate_auth_mechanism_properties(option, value):
"""Validate authMechanismProperties."""
value = validate_string(option, value)
props = {}
for opt in value.split(','):
try:
key, val = opt.split(':')
except __HOLE__:
raise ValueError("auth mechanism propertie... | ValueError | dataset/ETHPy150Open mongodb/mongo-python-driver/pymongo/common.py/validate_auth_mechanism_properties |
4,357 | def get_validated_options(options, warn=True):
"""Validate each entry in options and raise a warning if it is not valid.
Returns a copy of options with invalid entries removed
"""
validated_options = {}
for opt, value in iteritems(options):
lower = opt.lower()
try:
valida... | ValueError | dataset/ETHPy150Open mongodb/mongo-python-driver/pymongo/common.py/get_validated_options |
4,358 | def makedir(path, ignored=None, uid=-1, gid=-1):
ignored = ignored or []
try:
os.makedirs(path)
except __HOLE__ as error:
if error.errno in ignored:
pass
else:
# re-raise the original exception
raise
else:
os.chown(path, uid, gid); | OSError | dataset/ETHPy150Open ceph/ceph-deploy/ceph_deploy/hosts/remotes.py/makedir |
4,359 | def get_file(path):
""" fetch remote file """
try:
with file(path, 'rb') as f:
return f.read()
except __HOLE__:
pass | IOError | dataset/ETHPy150Open ceph/ceph-deploy/ceph_deploy/hosts/remotes.py/get_file |
4,360 | def make_mon_removed_dir(path, file_name):
""" move old monitor data """
try:
os.makedirs('/var/lib/ceph/mon-removed')
except __HOLE__, e:
if e.errno != errno.EEXIST:
raise
shutil.move(path, os.path.join('/var/lib/ceph/mon-removed/', file_name)) | OSError | dataset/ETHPy150Open ceph/ceph-deploy/ceph_deploy/hosts/remotes.py/make_mon_removed_dir |
4,361 | def safe_mkdir(path, uid=-1, gid=-1):
""" create path if it doesn't exist """
try:
os.mkdir(path)
except __HOLE__, e:
if e.errno == errno.EEXIST:
pass
else:
raise
else:
os.chown(path, uid, gid) | OSError | dataset/ETHPy150Open ceph/ceph-deploy/ceph_deploy/hosts/remotes.py/safe_mkdir |
4,362 | def safe_makedirs(path, uid=-1, gid=-1):
""" create path recursively if it doesn't exist """
try:
os.makedirs(path)
except __HOLE__, e:
if e.errno == errno.EEXIST:
pass
else:
raise
else:
os.chown(path, uid, gid) | OSError | dataset/ETHPy150Open ceph/ceph-deploy/ceph_deploy/hosts/remotes.py/safe_makedirs |
4,363 | def do_test_verbosity(self, parser, line, expected_verbosity):
try:
args = parser.parse_args(line.split())
except __HOLE__:
self.fail("Parsing arguments failed")
self.assertEqual(args.verbosity, expected_verbosity) | SystemExit | dataset/ETHPy150Open ViDA-NYU/reprozip/scripts/test_bug_23058.py/Test23058.do_test_verbosity |
4,364 | def popitem(self):
"""
Remove and return last item (key, value) duple
If odict is empty raise KeyError
"""
try:
key = self._keys[-1]
except __HOLE__:
raise KeyError('Empty odict.')
value = dict.__getitem__(self, key)
del self[key]
... | IndexError | dataset/ETHPy150Open ioflo/ioflo/ioflo/aid/odicting.py/odict.popitem |
4,365 | def pop(self, key, *pa, **kwa):
"""
If key exists remove and return the indexed element of the key element
list else return the optional following positional argument.
If the optional positional arg is not provided and key does not exit
then raise KeyError. If provided the index ... | KeyError | dataset/ETHPy150Open ioflo/ioflo/ioflo/aid/odicting.py/modict.pop |
4,366 | def poplist(self, key, *pa):
"""
If key exists remove and return keyed item's value list,
else return the optional following positional argument.
If the optional positional arg is not provided and key does not exit
then raise KeyError.
"""
try:
val = ... | KeyError | dataset/ETHPy150Open ioflo/ioflo/ioflo/aid/odicting.py/modict.poplist |
4,367 | @expose('error.html')
def error(self, status):
try:
status = int(status)
except __HOLE__: # pragma: no cover
status = 500
message = getattr(status_map.get(status), 'explanation', '')
return dict(status=status, message=message) | ValueError | dataset/ETHPy150Open openstack/wsme/tests/pecantest/test/controllers/root.py/RootController.error |
4,368 | def __init__(self, maxsize=0):
try:
import threading
except __HOLE__:
import dummy_threading as threading
self._init(maxsize)
# mutex must be held whenever the queue is mutating. All methods
# that acquire mutex must release it before returning. mutex
... | ImportError | dataset/ETHPy150Open babble/babble/include/jython/Lib/Queue.py/Queue.__init__ |
4,369 | def load(self, stream):
""" Load properties from an open file stream """
# For the time being only accept file input streams
if type(stream) is not file:
raise TypeError,'Argument should be a file object!'
# Check for the opened mode
if stream.mode != 'r':
... | IOError | dataset/ETHPy150Open GluuFederation/community-edition-setup/Properties.py/Properties.load |
4,370 | def store(self, out, header=""):
""" Write the properties list to the stream 'out' along
with the optional 'header' """
if out.mode[0] != 'w':
raise ValueError,'Steam should be opened in write mode!'
try:
out.write(''.join(('#',header,'\n')))
# Write... | IOError | dataset/ETHPy150Open GluuFederation/community-edition-setup/Properties.py/Properties.store |
4,371 | def __getattr__(self, name):
""" For attributes not found in self, redirect
to the properties dictionary """
try:
return self.__dict__[name]
except __HOLE__:
if hasattr(self._props,name):
return getattr(self._props, name) | KeyError | dataset/ETHPy150Open GluuFederation/community-edition-setup/Properties.py/Properties.__getattr__ |
4,372 | def static_image(relative_path, alt, **html_attrs):
"""Create an <img> tag for a path relative to the public directory.
If keyword arg ``use_cache`` is false, don't use the global dimensions
cache.
"""
use_cache = html_attrs.pop("use_cache", True)
if "width" not in html_attrs or "height"... | IOError | dataset/ETHPy150Open mikeorr/WebHelpers2/unfinished/multimedia.py/static_image |
4,373 | def open_image(image_path):
"""Open an image file in PIL, return the Image object.
Return None if PIL doesn't recognize the file type.
"""
try:
im = Image.open(image_path)
except __HOLE__, e:
if str(e) == "cannot identify image file":
return None
else:
... | IOError | dataset/ETHPy150Open mikeorr/WebHelpers2/unfinished/multimedia.py/open_image |
4,374 | def make_thumb(image_path, width):
"""Make a thumbnail and save it in the same directory as the original.
See get_thumb_path() for the arguments.
@return The thumbnail filename, or None if PIL
didn't recognize the image type.
Does NOT work with PDF originals; use make_thumb_from_pd... | IOError | dataset/ETHPy150Open mikeorr/WebHelpers2/unfinished/multimedia.py/make_thumb |
4,375 | def test_empty_cell(self):
def f(): print(a)
try:
f.__closure__[0].cell_contents
except __HOLE__:
pass
else:
self.fail("shouldn't be able to read an empty cell")
a = 12 | ValueError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_funcattrs.py/FunctionPropertiesTest.test_empty_cell |
4,376 | def test___code__(self):
num_one, num_two = 7, 8
def a(): pass
def b(): return 12
def c(): return num_one
def d(): return num_two
def e(): return num_one, num_two
for func in [a, b, c, d, e]:
self.assertEqual(type(func.__code__), types.CodeType)
... | ValueError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_funcattrs.py/FunctionPropertiesTest.test___code__ |
4,377 | def test_func_default_args(self):
def first_func(a, b):
return a+b
def second_func(a=1, b=2):
return a+b
self.assertEqual(first_func.__defaults__, None)
self.assertEqual(second_func.__defaults__, (1, 2))
first_func.__defaults__ = (1, 2)
self.assert... | TypeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_funcattrs.py/FunctionPropertiesTest.test_func_default_args |
4,378 | def test___func___non_method(self):
# Behavior should be the same when a method is added via an attr
# assignment
self.fi.id = types.MethodType(id, self.fi)
self.assertEqual(self.fi.id(), id(self.fi))
# Test usage
try:
self.fi.id.unknown_attr
except __... | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_funcattrs.py/InstancemethodAttrTest.test___func___non_method |
4,379 | def test_set_attr(self):
self.b.known_attr = 7
self.assertEqual(self.b.known_attr, 7)
try:
self.fi.a.known_attr = 7
except __HOLE__:
pass
else:
self.fail("setting attributes on methods should raise error") | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_funcattrs.py/ArbitraryFunctionAttrTest.test_set_attr |
4,380 | def test_delete_unknown_attr(self):
try:
del self.b.unknown_attr
except __HOLE__:
pass
else:
self.fail("deleting unknown attribute should raise TypeError") | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_funcattrs.py/ArbitraryFunctionAttrTest.test_delete_unknown_attr |
4,381 | def test_unset_attr(self):
for func in [self.b, self.fi.a]:
try:
func.non_existent_attr
except __HOLE__:
pass
else:
self.fail("using unknown attributes should raise "
"AttributeError") | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_funcattrs.py/ArbitraryFunctionAttrTest.test_unset_attr |
4,382 | def test_delete___dict__(self):
try:
del self.b.__dict__
except __HOLE__:
pass
else:
self.fail("deleting function dictionary should raise TypeError") | TypeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_funcattrs.py/FunctionDictsTest.test_delete___dict__ |
4,383 | def got_cancel(self, index, begin, length):
try:
self.buffer.remove((index, begin, length))
except __HOLE__:
pass | ValueError | dataset/ETHPy150Open Cclleemm/FriendlyTorrent/src/tornado/BitTornado/BT1/Uploader.py/Upload.got_cancel |
4,384 | def __init__(self, filename, width=None, height=None, kind='direct',
mask=None, lazy=True, srcinfo=None):
client, uri = srcinfo
cache = self.source_filecache.setdefault(client, {})
pdffname = cache.get(filename)
if pdffname is None:
tmpf, pdff... | OSError | dataset/ETHPy150Open rst2pdf/rst2pdf/rst2pdf/extensions/inkscape_r2p.py/InkscapeImage.__init__ |
4,385 | @classmethod
def raster(self, filename, client):
"""Returns a URI to a rasterized version of the image"""
cache = self.source_filecache.setdefault(client, {})
pngfname = cache.get(filename+'_raster')
if pngfname is None:
tmpf, pngfname = tempfile.mkstemp(suffix='.png')
... | OSError | dataset/ETHPy150Open rst2pdf/rst2pdf/rst2pdf/extensions/inkscape_r2p.py/InkscapeImage.raster |
4,386 | def formatday(
self, day, weekday,
day_template='happenings/partials/calendar/day_cell.html',
noday_template='happenings/partials/calendar/day_noday_cell.html',
popover_template='happenings/partials/calendar/popover.html',
):
"""Return a day as a table... | ValueError | dataset/ETHPy150Open wreckage/django-happenings/happenings/utils/calendars.py/EventCalendar.formatday |
4,387 | def _load_assets(self):
try:
with open(self.config['STATS_FILE']) as f:
return json.load(f)
except __HOLE__:
raise IOError(
'Error reading {0}. Are you sure webpack has generated '
'the file and the path is correct?'.format(
... | IOError | dataset/ETHPy150Open owais/django-webpack-loader/webpack_loader/loader.py/WebpackLoader._load_assets |
4,388 | def sort_fields(fields):
"""Sort fields by their column_number but put children after parents.
"""
fathers = [(key, val) for key, val in
sorted(fields.items(), key=lambda k: k[1]['column_number'])
if 'auto_generated' not in val]
children = [(key, val) for key, val in
... | ValueError | dataset/ETHPy150Open bigmlcom/python/bigml/util.py/sort_fields |
4,389 | def cast(input_data, fields):
"""Checks expected type in input data values, strips affixes and casts
"""
for (key, value) in input_data.items():
if (
(fields[key]['optype'] == 'numeric' and
isinstance(value, basestring)) or
(fields[key]['optype'] != ... | ValueError | dataset/ETHPy150Open bigmlcom/python/bigml/util.py/cast |
4,390 | def maybe_save(resource_id, path,
code=None, location=None,
resource=None, error=None):
"""Builds the resource dict response and saves it if a path is provided.
The resource is saved in a local repo json file in the given path.
"""
resource = resource_structure(code, reso... | ValueError | dataset/ETHPy150Open bigmlcom/python/bigml/util.py/maybe_save |
4,391 | def synchronized(obj, lock=None):
assert not isinstance(obj, SynchronizedBase), 'object already synchronized'
if isinstance(obj, ctypes._SimpleCData):
return Synchronized(obj, lock)
elif isinstance(obj, ctypes.Array):
if obj._type_ is ctypes.c_char:
return SynchronizedStr... | KeyError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/multiprocessing/sharedctypes.py/synchronized |
4,392 | def make_property(name):
try:
return prop_cache[name]
except __HOLE__:
d = {}
exec template % ((name,)*7) in d
prop_cache[name] = d[name]
return d[name] | KeyError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/multiprocessing/sharedctypes.py/make_property |
4,393 | def test_elementwise_multiply_broadcast(self):
A = array([4])
B = array([[-9]])
C = array([1,-1,0])
D = array([[7,9,-9]])
E = array([[3],[2],[1]])
F = array([[8,6,3],[-4,3,2],[6,6,6]])
G = [1, 2, 3]
H = np.ones((3, 4))
J = H.T
K = array([[0... | ValueError | dataset/ETHPy150Open scipy/scipy/scipy/sparse/tests/test_base.py/_TestCommon.test_elementwise_multiply_broadcast |
4,394 | def test_copy(self):
# Check whether the copy=True and copy=False keywords work
A = self.datsp
# check that copy preserves format
assert_equal(A.copy().format, A.format)
assert_equal(A.__class__(A,copy=True).format, A.format)
assert_equal(A.__class__(A,copy=False).format... | NotImplementedError | dataset/ETHPy150Open scipy/scipy/scipy/sparse/tests/test_base.py/_TestCommon.test_copy |
4,395 | def test_binary_ufunc_overrides(self):
# data
a = np.array([[1, 2, 3],
[4, 5, 0],
[7, 8, 9]])
b = np.array([[9, 8, 7],
[6, 0, 0],
[3, 2, 1]])
c = 1.0
d = 1 + 2j
e = 5
asp = se... | NotImplementedError | dataset/ETHPy150Open scipy/scipy/scipy/sparse/tests/test_base.py/_TestCommon.test_binary_ufunc_overrides |
4,396 | def test_non_unit_stride_2d_indexing(self):
# Regression test -- used to silently ignore the stride.
v0 = np.random.rand(50, 50)
try:
v = self.spmatrix(v0)[0:25:2, 2:30:3]
except __HOLE__:
# if unsupported
raise nose.SkipTest("feature not implemented")... | ValueError | dataset/ETHPy150Open scipy/scipy/scipy/sparse/tests/test_base.py/_TestSlicing.test_non_unit_stride_2d_indexing |
4,397 | def _possibly_unimplemented(cls, require=True):
"""
Construct a class that either runs tests as usual (require=True),
or each method raises SkipTest if it encounters a common error.
"""
if require:
return cls
else:
def wrap(fc):
def wrapper(*a, **kw):
... | ValueError | dataset/ETHPy150Open scipy/scipy/scipy/sparse/tests/test_base.py/_possibly_unimplemented |
4,398 | def test_scalar_idx_dtype(self):
# Check that index dtype takes into account all parameters
# passed to sparsetools, including the scalar ones
indptr = np.zeros(2, dtype=np.int32)
indices = np.zeros(0, dtype=np.int32)
vals = np.zeros((0, 1, 1))
a = bsr_matrix((vals, indic... | ValueError | dataset/ETHPy150Open scipy/scipy/scipy/sparse/tests/test_base.py/TestBSR.test_scalar_idx_dtype |
4,399 | def clean(self, value):
super(CAProvinceField, self).clean(value)
if value in EMPTY_VALUES:
return ''
try:
value = value.strip().lower()
except __HOLE__:
pass
else:
# Load data in memory only when it is required, see also #17275
... | AttributeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/localflavor/ca/forms.py/CAProvinceField.clean |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.