Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
4,400 | def test_abort_and_reset(self):
"""
Test that a barrier can be reset after being broken.
"""
results1 = []
results2 = []
results3 = []
barrier2 = self.barriertype(self.N)
def f():
try:
i = self.barrier.wait()
if ... | RuntimeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/lock_tests.py/BarrierTests.test_abort_and_reset |
4,401 | def web_method_wrapper(func):
@functools.wraps(func)
@gen.coroutine
def wrapper(self, *args, **kwargs):
self.init_rsp_json()
try:
yield func(self, *args, **kwargs)
yield self.finished()
except BaseError as e:
self.rsp_json['code'] = e.e_code
... | StopIteration | dataset/ETHPy150Open bufferx/twork/twork/web/action_wrapper.py/web_method_wrapper |
4,402 | def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except __HOLE__:
return self.__missing__(key) | KeyError | dataset/ETHPy150Open cournape/Bento/bento/compat/_collections.py/defaultdict.__getitem__ |
4,403 | def move_to_group(self, item, target_group, quantity):
try:
target_item = target_group.items.get(
product=item.product, product_name=item.product_name,
product_sku=item.product_sku)
except __HOLE__:
target_group.items.create(
delive... | ObjectDoesNotExist | dataset/ETHPy150Open mirumee/saleor/saleor/order/models.py/OrderedItemManager.move_to_group |
4,404 | def load_server_key():
try:
key_path = settings.PQAUTH_SERVER_KEY
except AttributeError:
msg = "You must set settings.PQUATH_SERVER_KEY"
raise ImproperlyConfigured(msg)
key_password = None
try:
key_password = settings.PQAUTH_SERVER_KEY_PASSWORD
except __HOLE__:
... | AttributeError | dataset/ETHPy150Open teddziuba/pqauth/python/pqauth/pqauth_django_server/keys.py/load_server_key |
4,405 | def _get_parent_modeladmin(self):
# HACK: accessing private field.
try:
parentadmin = self.admin_site._registry[self.parent_model]
except __HOLE__:
raise ImproperlyConfigured("Model admin for '{0}' not found in admin_site!".format(self.parent_model.__name__))
# D... | KeyError | dataset/ETHPy150Open edoburu/django-fluent-contents/fluent_contents/admin/placeholdereditor.py/PlaceholderEditorInline._get_parent_modeladmin |
4,406 | def _get_url_format(opts):
try:
return opts.app_label, opts.model_name # Django 1.7 format
except __HOLE__:
return opts.app_label, opts.module_name | AttributeError | dataset/ETHPy150Open edoburu/django-fluent-contents/fluent_contents/admin/placeholdereditor.py/_get_url_format |
4,407 | def extract_filters(term, opts=None):
"""
Pulls all the filtering options out of the term and returns a cleaned term
and a dictionary of filter names and filter values. Term filters override
filters found in opts.
"""
opts = opts or {}
filters = {}
params = {}
# Type filters.
t... | ValueError | dataset/ETHPy150Open mozilla/addons-server/src/olympia/legacy_api/utils.py/extract_filters |
4,408 | def parse_docstring(api_doc, docindex):
"""
Process the given C{APIDoc}'s docstring. In particular, populate
the C{APIDoc}'s C{descr} and C{summary} attributes, and add any
information provided by fields in the docstring.
@param docindex: A DocIndex, used to find the containing
module ... | ValueError | dataset/ETHPy150Open ardekantur/pyglet/tools/epydoc/epydoc/docstringparser.py/parse_docstring |
4,409 | def add_metadata_from_var(api_doc, field):
if not field.multivalue:
for (f,a,d) in api_doc.metadata:
if field == f:
return # We already have a value for this metadata.
for varname in field.varnames:
# Check if api_doc has a variable w/ the given name.
if varna... | KeyboardInterrupt | dataset/ETHPy150Open ardekantur/pyglet/tools/epydoc/epydoc/docstringparser.py/add_metadata_from_var |
4,410 | def process_deffield_field(api_doc, docindex, tag, arg, descr):
"""Define a new custom field."""
_check(api_doc, tag, arg, expect_arg=True)
if api_doc.extra_docstring_fields is UNKNOWN:
api_doc.extra_docstring_fields = []
try:
docstring_field = _descr_to_docstring_field(arg, descr)
... | ValueError | dataset/ETHPy150Open ardekantur/pyglet/tools/epydoc/epydoc/docstringparser.py/process_deffield_field |
4,411 | def calendar_view(request, year=datetime.now().year, month=datetime.now().month, channel_slug=None, page=1):
"""
Shows a grid (similar in appearance to a physical calendar) of podcasts for either a specific podcast channel or no
channel at all. Based on the GridOne layout originally developed for Calendars... | ValueError | dataset/ETHPy150Open albatrossandco/brubeck_cms/brubeck/podcasts/views.py/calendar_view |
4,412 | def calendar_day_view(request, year=datetime.now().year, month=datetime.now().month, day=datetime.now().day, channel_slug=None, page=1):
"""
Shows a grid (similar in appearance to a physical calendar) of podcasts for either a specific podcast channel or no
channel at all. Based on the GridOne layout origin... | ValueError | dataset/ETHPy150Open albatrossandco/brubeck_cms/brubeck/podcasts/views.py/calendar_day_view |
4,413 | def main():
"""Main function for specchio
Example: specchio test/ user@host:test/
:return: None
"""
init_logger()
_popen_str = os.popen("whereis ssh").read().strip()
if _popen_str == "" or _popen_str == "ssh:":
return logger.error("Specchio need `ssh`, "
... | KeyboardInterrupt | dataset/ETHPy150Open brickgao/specchio/specchio/main.py/main |
4,414 | def makeExcludesDict(self):
"""
@return: A C{dict} that maps each option name appearing in
self.mutuallyExclusive to a list of those option names that
is it mutually exclusive with (can't appear on the cmd line with)
"""
#create a mapping of long option name -> single ch... | IndexError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/python/zshcomp.py/ArgumentsGenerator.makeExcludesDict |
4,415 | def getDescription(self, longname):
"""
Return the description to be used for this argument
@return: C{str}
"""
#check if we have an alternate descr for this arg, and if so use it
if longname in self.altArgDescr:
return self.altArgDescr[longname]
#oth... | KeyError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/python/zshcomp.py/ArgumentsGenerator.getDescription |
4,416 | def getShortOption(self, longname):
"""
Return the short option letter or None
@return: C{str} or C{None}
"""
optList = self.optAll_d[longname]
try:
return optList[0] or None
except __HOLE__:
pass | IndexError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/python/zshcomp.py/ArgumentsGenerator.getShortOption |
4,417 | def descrFromDoc(obj):
"""
Generate an appropriate description from docstring of the given object
"""
if obj.__doc__ is None:
return None
lines = obj.__doc__.split("\n")
descr = None
try:
if lines[0] != "" and not lines[0].isspace():
descr = lines[0].lstrip()
... | IndexError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/python/zshcomp.py/descrFromDoc |
4,418 | def firstLine(s):
"""
Return the first line of the given string
"""
try:
i = s.index('\n')
return s[:i]
except __HOLE__:
return s | ValueError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/python/zshcomp.py/firstLine |
4,419 | def readlines(self, sizehint=-1):
self._close_check()
lines = []
try:
while True:
line = self.readline(sizehint)
if not line:
break
lines.append(line)
if sizehint >... | StopIteration | dataset/ETHPy150Open openstack/storlets/Engine/swift/storlet_gateway/storlet_docker_gateway.py/StorletGatewayDocker.IterLike.readlines |
4,420 | @classmethod
def validate_dependency_registration(cls, params, name):
mandatory = ['Dependency-Version']
StorletGatewayDocker._check_mandatory_params(params, mandatory)
perm = params.get('Dependency-Permissions')
if perm is not None:
try:
perm_int = int(p... | ValueError | dataset/ETHPy150Open openstack/storlets/Engine/swift/storlet_gateway/storlet_docker_gateway.py/StorletGatewayDocker.validate_dependency_registration |
4,421 | def update_wrapper(new_fn, fn):
"""
Copy as much of the function detail from fn to new_fn
as we can.
"""
try:
new_fn.__name__ = fn.__name__
new_fn.__dict__.update(fn.__dict__)
new_fn.__doc__ = fn.__doc__
new_fn.__module__ = fn.__module__
except __HOLE__:
p... | TypeError | dataset/ETHPy150Open AnyMesh/anyMesh-Python/example/urwid/widget.py/update_wrapper |
4,422 | def parse_date_delta(value):
"""
like parse_date, but also handle delta seconds
"""
if not value:
return None
try:
value = int(value)
except __HOLE__:
return parse_date(value)
else:
return _now() + timedelta(seconds=value) | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/webob-1.1.1/webob/datetime_utils.py/parse_date_delta |
4,423 | def read(self, amt=None):
try:
result = next(self.resp_iter)
return result
except __HOLE__:
return '' | StopIteration | dataset/ETHPy150Open openstack/swift/test/unit/proxy/test_sysmeta.py/FakeServerConnection.read |
4,424 | def _data_range_changed(self, value):
try:
self.lut.set_range(value[0], value[1])
except TypeError:
self.lut.set_range((value[0], value[1]))
except __HOLE__:
self.lut.range = value
self.scalar_bar.modified()
self.render() | AttributeError | dataset/ETHPy150Open enthought/mayavi/mayavi/core/lut_manager.py/LUTManager._data_range_changed |
4,425 | def load_lut_from_file(self, file_name):
lut_list = []
if len(file_name) > 0:
try:
f = open(file_name, 'r')
except IOError:
msg = "Cannot open Lookup Table file: %s\n"%file_name
error(msg)
else:
f.close()... | IOError | dataset/ETHPy150Open enthought/mayavi/mayavi/core/lut_manager.py/LUTManager.load_lut_from_file |
4,426 | def write(dictionary, args, output_file_path):
# result to be returned
result = None
# get absolute path
output_file_path_absolute = os.path.abspath(output_file_path)
# sort by headword, optionally ignoring case
dictionary.sort(by_headword=True, ignore_case=args.sort_ignore_case)
# create... | OSError | dataset/ETHPy150Open pettarin/penelope/penelope/format_mobi.py/write |
4,427 | def read(self, istream):
super(Attribute, self).read(istream)
tstream = BytearrayStream(istream.read(self.length))
# Read the name of the attribute
self.attribute_name = Attribute.AttributeName()
self.attribute_name.read(tstream)
# Read the attribute index if it is next... | KeyError | dataset/ETHPy150Open OpenKMIP/PyKMIP/kmip/core/objects.py/Attribute.read |
4,428 | def InsertVideoEntry(self, video_entry, filename_or_handle,
youtube_username='default',
content_type='video/quicktime'):
"""Upload a new video to YouTube using the direct upload mechanism.
Needs authentication.
Args:
video_entry: The YouTubeVideoEntry to... | AssertionError | dataset/ETHPy150Open acil-bwh/SlicerCIP/Scripted/attic/PicasaSnap/gdata/youtube/service.py/YouTubeService.InsertVideoEntry |
4,429 | def calcdesc(self, descnames=None):
"""Calculate descriptor values.
Optional parameter:
descnames -- a list of names of descriptors
If descnames is not specified, all available descriptors are
calculated. See the descs variable for a list of available
descriptors.
... | KeyError | dataset/ETHPy150Open oddt/oddt/oddt/toolkits/rdk.py/Molecule.calcdesc |
4,430 | def try_again(f):
def _(self, *a, **kw):
for i in range(3):
try:
return f(self, *a, **kw)
except __HOLE__ as e:
self.close()
logger.warning("mfs master connection: %s", e)
time.sleep(2**i * 0.1)
else:
... | IOError | dataset/ETHPy150Open douban/dpark/dpark/moosefs/master.py/try_again |
4,431 | def recv_thread(self):
while True:
with self.lock:
if not self.is_ready:
time.sleep(0.01)
continue
try:
r = self.recv_cmd()
self.reply.put(r)
except __HOLE__ as e:
self.rep... | IOError | dataset/ETHPy150Open douban/dpark/dpark/moosefs/master.py/MasterConn.recv_thread |
4,432 | def py_import(module_name, dependency_dictionary, store_in_config=False):
"""Tries to import a python module, installing if necessary.
If the import doesn't succeed, we guess which system we are running on and
install the corresponding package from the dictionary. We then run the
import again.
If t... | ImportError | dataset/ETHPy150Open VisTrails/VisTrails/vistrails/core/bundles/pyimport.py/py_import |
4,433 | def _process(commands, callback=None, stdin=None, settings=None, working_dir=None, wait_for_completion=None, **kwargs):
'''Process one or more OS commands.'''
if wait_for_completion is None:
wait_for_completion = False
# We're expecting a list of commands, so if we only have one, convert
# it ... | OSError | dataset/ETHPy150Open markbirbeck/sublime-text-shell-command/OsShell.py/_process |
4,434 | def cli_commands(obj, namef, clizer):
cmds = util.OrderedDict()
cmd_by_name = {}
try:
names = util.dict_from_names(obj).items()
except __HOLE__:
raise ValueError("Cannot guess name for anonymous objects "
"(lists, dicts, etc)")
for key, val in names:
... | AttributeError | dataset/ETHPy150Open epsy/clize/clize/runner.py/cli_commands |
4,435 | @classmethod
def get_cli(cls, obj, **kwargs):
"""Makes an attempt to discover a command-line interface for the
given object.
.. _cli-object:
The process used is as follows:
1. If the object has a ``cli`` attribute, it is used with no further
transformation.
... | TypeError | dataset/ETHPy150Open epsy/clize/clize/runner.py/Clize.get_cli |
4,436 | def __get__(self, obj, owner=None):
try:
func = self.func.__get__(obj, owner)
except __HOLE__:
func = self.func
if func is self.func:
return self
params = self.parameters()
params['owner'] = obj
return type(self)(func, **params) | AttributeError | dataset/ETHPy150Open epsy/clize/clize/runner.py/Clize.__get__ |
4,437 | @Clize(helper_class=_dispatcher_helper)
@annotate(name=parameters.pass_name,
command=(lowercase, parser.Parameter.LAST_OPTION))
def cli(self, name, command, *args):
try:
func = self.cmds_by_name[command]
except __HOLE__:
raise errors.ArgumentError('Unknwon c... | KeyError | dataset/ETHPy150Open epsy/clize/clize/runner.py/SubcommandDispatcher.cli |
4,438 | def fix_argv(argv, path, main):
"""Properly display ``python -m`` invocations"""
if not path[0]:
try:
name = main_module_name(main)
except __HOLE__:
pass
else:
argv = argv[:]
argv[0] = '{0} -m {1}'.format(
get_executable(sys... | AttributeError | dataset/ETHPy150Open epsy/clize/clize/runner.py/fix_argv |
4,439 | def get_executable(path, default):
if not path:
return default
if path.endswith('.py'):
return path
basename = os.path.basename(path)
try:
which = shutil.which
except __HOLE__:
which = None
else:
if which(basename) == path:
return basename
... | AttributeError | dataset/ETHPy150Open epsy/clize/clize/runner.py/get_executable |
4,440 | def parse_opts(buf):
"""Parse TCP option buffer into a list of (option, data) tuples."""
opts = []
while buf:
o = ord(buf[0])
if o > TCP_OPT_NOP:
try:
l = ord(buf[1])
d, buf = buf[2:l], buf[l:]
except __HOLE__:
#print 'b... | ValueError | dataset/ETHPy150Open dragondjf/QMarkdowner/dpkt/tcp.py/parse_opts |
4,441 | def test_execfile_traceback(self):
globals = {}
try:
execfile(self.basename1, globals)
except __HOLE__:
tb = sys.exc_info()[2]
self.assertEqual(tb.tb_next.tb_frame.f_code.co_filename,
self.basename1) | NotImplementedError | dataset/ETHPy150Open babble/babble/include/jython/Lib/test/test_chdir.py/ExecfileTracebackTestCase.test_execfile_traceback |
4,442 | def tearDown(self):
try:
super(ImportJarTestCase, self).tearDown()
except __HOLE__:
# XXX: Windows raises an error here when deleting the jar
# because SyspathArchive holds onto its file handle (and you
# can't delete a file in use on Windows). We may not ... | OSError | dataset/ETHPy150Open babble/babble/include/jython/Lib/test/test_chdir.py/ImportJarTestCase.tearDown |
4,443 | def __init__(self, **kwargs):
self.kwargs = kwargs
if CONF.fatal_exception_format_errors:
assert isinstance(self.msg_fmt, six.text_type)
try:
self.message = self.msg_fmt % kwargs
except __HOLE__:
# kwargs doesn't match a variable in the message
... | KeyError | dataset/ETHPy150Open openstack/solum/solum/common/exception.py/SolumException.__init__ |
4,444 | def get_default_columns(self, with_aliases=False, col_aliases=None,
start_alias=None, opts=None, as_pairs=False):
"""
Computes the default columns for selecting every field in the base
model. Will sometimes be called to pull in related models (e.g. via
select_related), in whi... | KeyError | dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/models/sql/query.py/BaseQuery.get_default_columns |
4,445 | def get_from_clause(self):
"""
Returns a list of strings that are joined together to go after the
"FROM" part of the query, as well as a list any extra parameters that
need to be included. Sub-classes, can override this to create a
from-clause via a "select".
This should... | KeyError | dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/models/sql/query.py/BaseQuery.get_from_clause |
4,446 | def setup_joins(self, names, opts, alias, dupe_multis, allow_many=True,
allow_explicit_fk=False, can_reuse=None, negate=False,
process_extras=True):
"""
Compute the necessary table joins for the passage through the fields
given in 'names'. 'opts' is the Options class for ... | NameError | dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/models/sql/query.py/BaseQuery.setup_joins |
4,447 | def update_dupe_avoidance(self, opts, col, alias):
"""
For a column that is one of multiple pointing to the same table, update
the internal data structures to note that this alias shouldn't be used
for those other columns.
"""
ident = id(opts)
for name in opts.dup... | KeyError | dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/models/sql/query.py/BaseQuery.update_dupe_avoidance |
4,448 | def get(self, name, **kwargs):
try:
cls = self.providers[name]
except __HOLE__:
raise InvalidProvider(name)
return cls(**kwargs) | KeyError | dataset/ETHPy150Open getsentry/freight/freight/providers/manager.py/ProviderManager.get |
4,449 | def execute_directives(self):
global __KV_INCLUDES__
for ln, cmd in self.directives:
cmd = cmd.strip()
if __debug__:
trace('Parser: got directive <%s>' % cmd)
if cmd[:5] == 'kivy ':
version = cmd[5:].strip()
if len(versi... | ImportError | dataset/ETHPy150Open kivy/kivy/kivy/lang/parser.py/Parser.execute_directives |
4,450 | @app.get('/dossier/v1/feature-collection/<cid>/search/<engine_name>')
@app.post('/dossier/v1/feature-collection/<cid>/search/<engine_name>')
def v1_search(request, response, visid_to_dbid, config,
search_engines, filters, cid, engine_name):
'''Search feature collections.
The route for this endpoi... | KeyError | dataset/ETHPy150Open dossier/dossier.web/dossier/web/routes.py/v1_search |
4,451 | @app.get('/dossier/v1/folder/<fid>/subfolder', json=True)
def v1_subfolder_list(request, response, kvlclient, fid):
'''Retrieves a list of subfolders in a folder for the current user.
The route for this endpoint is:
``GET /dossier/v1/folder/<fid>/subfolder``.
(Temporarily, the "current user" can be se... | KeyError | dataset/ETHPy150Open dossier/dossier.web/dossier/web/routes.py/v1_subfolder_list |
4,452 | @app.get('/dossier/v1/folder/<fid>/subfolder/<sfid>', json=True)
def v1_subtopic_list(request, response, kvlclient, fid, sfid):
'''Retrieves a list of items in a subfolder.
The route for this endpoint is:
``GET /dossier/v1/folder/<fid>/subfolder/<sfid>``.
(Temporarily, the "current user" can be set vi... | KeyError | dataset/ETHPy150Open dossier/dossier.web/dossier/web/routes.py/v1_subtopic_list |
4,453 | def str_to_max_int(s, maximum):
try:
return min(maximum, int(s))
except (__HOLE__, TypeError):
return maximum | ValueError | dataset/ETHPy150Open dossier/dossier.web/dossier/web/routes.py/str_to_max_int |
4,454 | def new_folders(kvlclient, request):
try:
config = yakonfig.get_global_config('dossier.folders')
# For old configs.
if 'prefix' in config:
config['namespace'] = config.pop('prefix')
except __HOLE__:
config = {}
if 'annotator_id' in request.query:
config['o... | KeyError | dataset/ETHPy150Open dossier/dossier.web/dossier/web/routes.py/new_folders |
4,455 | def init(
dist='dist',
minver=None,
maxver=None,
use_markdown_readme=True,
use_stdeb=False,
use_distribute=False,
):
"""Imports and returns a setup function.
If use_markdown_readme is set,
then README.md is added to setuptools READMES list.
If use_stdeb is set on a Debian b... | ImportError | dataset/ETHPy150Open salsita/flask-raml/setup.py/init |
4,456 | def read_array(filename):
"""Reads an array from a file.
The first line must be a header with labels and units in a particular
format.
"""
unused_, filetype = os.path.splitext(filename)
fo = open(filename, "rU")
try:
if filetype == ".txt":
header = map(eval, fo.readline... | ValueError | dataset/ETHPy150Open kdart/pycopia/QA/pycopia/dataset.py/read_array |
4,457 | def flush(self):
"""Flushes the stream"""
try:
stream = self.get_wsgierrors()
except __HOLE__:
pass
else:
if stream:
stream.flush() | TypeError | dataset/ETHPy150Open Pylons/pylons/pylons/log.py/WSGIErrorsHandler.flush |
4,458 | def emit(self, record):
"""Emit a record"""
try:
stream = self.get_wsgierrors()
except TypeError:
pass
else:
if not stream:
return
try:
msg = self.format(record)
fs = "%s\n"
if... | KeyboardInterrupt | dataset/ETHPy150Open Pylons/pylons/pylons/log.py/WSGIErrorsHandler.emit |
4,459 | def make_unauthorized_request(self, request_url):
response = urllib.urlopen(request_url)
try:
json_response = json.load(response)
except __HOLE__, e:
logging.error('Invalid response: %s (%d)' % (e,
response.getcode()))
return None
ret... | ValueError | dataset/ETHPy150Open dasevilla/tumblr-python/tumblr/__init__.py/TumblrClient.make_unauthorized_request |
4,460 | def make_oauth_request(self, request_url, method='GET', body=None):
if not self.consumer or not self.token:
logging.error('Missing OAuth credentials')
return None
oauth_client = oauth2.Client(self.consumer, self.token)
if body:
response, content = oauth_clien... | ValueError | dataset/ETHPy150Open dasevilla/tumblr-python/tumblr/__init__.py/TumblrClient.make_oauth_request |
4,461 | def get_shared_cache_folder():
"""
Look in the registry for the configured cache folder.
If there is no entry, then we create one.
:return:
"""
_winreg.aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER)
try:
key = _winreg.OpenKey(_winreg.aReg, r"SOFTWARE\CCP\EVEONLINE")
... | OSError | dataset/ETHPy150Open ccpgames/rescache/paths_win.py/get_shared_cache_folder |
4,462 | def set_shared_cache_folder(folder_path):
if not os.path.isdir(folder_path):
try:
os.makedirs(folder_path)
except __HOLE__:
raise ValueError("Could not create directory {}".format(folder_path))
folder_path = os.path.normpath(folder_path) + os.sep
key_eveonline = _win... | OSError | dataset/ETHPy150Open ccpgames/rescache/paths_win.py/set_shared_cache_folder |
4,463 | def setMode (key, newval):
try:
if (type(newval) is not int):
newval = int(newval)
except __HOLE__, e:
raise UnknownApprovalMode(newval)
if (newval < 0) or (newval > 2):
raise UnknownApprovalMode(newval)
if newval == RULES:
item = ConfigDB.getConfigItemByKey("geni.openflow.analysis-engin... | ValueError | dataset/ETHPy150Open fp7-ofelia/ocf/ofam/src/src/foam/geni/approval.py/setMode |
4,464 | @ensure_template_arg
def get_variables_from_template(template):
variable_nodes = [n for n in template.nodelist if isinstance(n, DefineNode)]
variables = SortedDict()
for node in variable_nodes:
if node.variable_name in variables:
raise TemplateSyntaxError('%s defined multiple times - %s'... | KeyError | dataset/ETHPy150Open KristianOellegaard/cmsplugin-text-ng/cmsplugin_text_ng/utils.py/get_variables_from_template |
4,465 | def test_already_exists_rollback_file(self):
# Test the rollback feature by attempting to create two files, the
# second of which already exists.
# Test that the first file gets deleted on the rollback.
tempdir = tempfile.mkdtemp()
try:
file_one = os.path.join(tempdir... | IOError | dataset/ETHPy150Open zerovm/zerovm-cli/zpmlib/tests/test_util.py/TestAtomicFileCreator.test_already_exists_rollback_file |
4,466 | def test_already_exists_rollback_dir(self):
# Test the rollback feature by attempting to create a dir and a file,
# the second of which already exists.
# Test that the dir gets deleted on the rollback.
tempdir = tempfile.mkdtemp()
try:
dir_one = os.path.join(tempdir, ... | IOError | dataset/ETHPy150Open zerovm/zerovm-cli/zpmlib/tests/test_util.py/TestAtomicFileCreator.test_already_exists_rollback_dir |
4,467 | def test_context_manager_failure_case(self):
tempdir = tempfile.mkdtemp()
try:
dir_one = os.path.join(tempdir, 'dir_one')
# This tests creating files inside created dirs:
file_one = os.path.join(dir_one, 'one.txt')
file_two = os.path.join(tempdir, 'two.tx... | IOError | dataset/ETHPy150Open zerovm/zerovm-cli/zpmlib/tests/test_util.py/TestAtomicFileCreator.test_context_manager_failure_case |
4,468 | def transform_csv(self):
self.log(" Transforming source CSV")
grouped = {}
form2field = {
# F460
'A-1': 'itemized_monetary_contributions',
'A-2': 'unitemized_monetary_contributions',
'A-3': 'total_monetary_contributions',
'F460-4': 'non... | KeyError | dataset/ETHPy150Open california-civic-data-coalition/django-calaccess-campaign-browser/calaccess_campaign_browser/management/commands/loadcalaccesscampaignsummaries.py/Command.transform_csv |
4,469 | def tearDown(self):
try:
self.cnx.close()
self.removefile()
except __HOLE__:
pass
except sqlite.ProgrammingError:
pass | AttributeError | dataset/ETHPy150Open sassoftware/conary/conary/pysqlite3/test/api_tests.py/moduleTestCases.tearDown |
4,470 | def CheckCursorIterator(self):
self.cur.execute("create table test (id, name)")
self.cur.executemany("insert into test (id) values (?)",
[(1,), (2,), (3,)])
self.cur.execute("select id from test")
if sys.version_info[:2] >= (2,2):
counter = 0
... | IndexError | dataset/ETHPy150Open sassoftware/conary/conary/pysqlite3/test/api_tests.py/moduleTestCases.CheckCursorIterator |
4,471 | def echo(self, request, *args, **kwargs):
response = HttpResponse("echo")
try:
response.data = request.data
except __HOLE__:
response.data = request.DATA
return response | AttributeError | dataset/ETHPy150Open kevin-brown/drf-json-api/tests/views.py/EchoMixin.echo |
4,472 | def get_all_addrs(self, name):
'''
Returns the all addresses which the logical name would resolve to,
or raises NameNotFound if there is no known address for the given name.
'''
ctx = context.get_context()
address_groups = self.address_groups or ctx.address_groups
... | KeyError | dataset/ETHPy150Open paypal/support/support/connection_mgr.py/ConnectionManager.get_all_addrs |
4,473 | def _edit(self, filename, line=None):
""" Opens a Python script for editing.
Parameters:
-----------
filename : str
A path to a local system file.
line : int, optional
A line of interest in the file.
"""
if self.custom_edit:
s... | KeyError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/frontend/qt/console/ipython_widget.py/IPythonWidget._edit |
4,474 | def _read(self):
try:
profile_f = open(self.fname)
except __HOLE__:
return
for lineno, line in enumerate(profile_f):
line = line.strip()
if not line or line.startswith("#"):
continue
test_key, platform_key, counts = lin... | IOError | dataset/ETHPy150Open zzzeek/sqlalchemy/lib/sqlalchemy/testing/profiling.py/ProfileStatsFile._read |
4,475 | def find_pdh_counter_localized_name(english_name, machine_name = None):
if not counter_english_map:
import win32api, win32con
counter_reg_value = win32api.RegQueryValueEx(win32con.HKEY_PERFORMANCE_DATA,
"Counter 009")
counter_list = c... | ValueError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/win32/lib/win32pdhutil.py/find_pdh_counter_localized_name |
4,476 | def FindPerformanceAttributesByName(instanceName, object = None,
counter = None,
format = win32pdh.PDH_FMT_LONG,
machine = None, bRefresh=0):
"""Find peformance attributes by (case insensitive) instance n... | KeyError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/win32/lib/win32pdhutil.py/FindPerformanceAttributesByName |
4,477 | def ShowAllProcesses():
object = find_pdh_counter_localized_name("Process")
items, instances = win32pdh.EnumObjectItems(None,None,object,
win32pdh.PERF_DETAIL_WIZARD)
# Need to track multiple instances of the same name.
instance_dict = {}
for ins... | KeyError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/win32/lib/win32pdhutil.py/ShowAllProcesses |
4,478 | def loadHooks(self):
target = self.target
config = self.target.config
lib = self.target.library
platform = self.target.project.platform
# Collect hooks in various locations
for fileName in config.get("hooks", []):
Log.notice("Parsing hooks from '%s'." % fileName)
source... | ValueError | dataset/ETHPy150Open skyostil/tracy/src/generator/Target.py/ParserTool.loadHooks |
4,479 | def prepare(self):
# Shorthand for various objects
config = self.config
lib = self.library
# Parse the sources
for fileName in config.get("apiheaders", []):
Log.notice("Parsing functions from '%s'." % fileName)
source = self.parserTool.readSource(fileName)
newLib = Parser.p... | AttributeError | dataset/ETHPy150Open skyostil/tracy/src/generator/Target.py/CodeTarget.prepare |
4,480 | def _samefile(src, dst):
# Macintosh, Unix.
if hasattr(os.path, 'samefile'):
try:
return os.path.samefile(src, dst)
except __HOLE__:
return False
# All other platforms: check for same pathname.
return (os.path.normcase(os.path.abspath(src)) ==
os.path... | OSError | dataset/ETHPy150Open django/django/django/core/files/move.py/_samefile |
4,481 | def file_move_safe(old_file_name, new_file_name, chunk_size=1024 * 64, allow_overwrite=False):
"""
Moves a file from one location to another in the safest way possible.
First, tries ``os.rename``, which is simple but will break across filesystems.
If that fails, streams manually from one file to anothe... | OSError | dataset/ETHPy150Open django/django/django/core/files/move.py/file_move_safe |
4,482 | def __init__(self):
self.nmap_path = "/usr/bin/nmap"
self.lib = True
if not os.path.exists(self.nmap_path):
try:
import nmap
self.lib = False
except __HOLE__:
mess = "Please install the python-nmap module (pip install nmap)... | ImportError | dataset/ETHPy150Open galkan/crowbar/lib/nmap.py/Nmap.__init__ |
4,483 | def configure(args):
if args.switch:
change_default_profile(args.switch)
return
config = ConfigParser()
config.add_section('profiles')
config['profiles']['host[1]'] = input('>> MPD host [localhost]: ') or \
'localhost'
config['profiles']['port[1]']... | IOError | dataset/ETHPy150Open nhrx/mpdc/mpdc/mpdc_configure.py/configure |
4,484 | def change_default_profile(profile):
config = ConfigParser()
filepath = os.path.expanduser('~/.mpdc')
if not config.read(filepath):
warning('Cannot read the configuration file, run mpdc-configure')
return
config['profiles']['default'] = str(profile)
try:
with open(filepath, '... | IOError | dataset/ETHPy150Open nhrx/mpdc/mpdc/mpdc_configure.py/change_default_profile |
4,485 | def retry_using_http_NTLM_auth(self, req, auth_header_field, realm, headers):
user, pw = self.passwd.find_user_password(realm, req.get_full_url())
debug_output(user, pw)
if pw is not None:
user_parts = user.split('\\', 1)
if len(user_parts) == 1:
UserName ... | TypeError | dataset/ETHPy150Open genzj/pybingwallpaper/src/ntlmauth/HTTPNtlmAuthHandler.py/AbstractNtlmAuthHandler.retry_using_http_NTLM_auth |
4,486 | def user_data(self, token, *args, **kwargs):
"""Loads user data from service"""
url = 'https://nodeapi.classlink.com/v2/my/info'
auth_header = {"Authorization": "Bearer %s" % token}
try:
return self.get_json(url, headers=auth_header)
except __HOLE__:
retur... | ValueError | dataset/ETHPy150Open omab/python-social-auth/social/backends/classlink.py/ClasslinkOAuth.user_data |
4,487 | def __init__(self):
try:
super(HTML2PlainParser, self).__init__()
except __HOLE__:
self.reset()
self.text = '' # Used to push the results into a variable
self.links = [] # List of aggregated links
# Settings
self.ignored_elements = getattr(
... | TypeError | dataset/ETHPy150Open bitmazk/django-libs/django_libs/utils/converter.py/HTML2PlainParser.__init__ |
4,488 | def _filter_coverage_for_added_lines(self, diff, coverage):
"""
This function takes a diff (text based) and a map of file names to the coverage for those files and
returns an ordered list of the coverage for each "addition" line in the diff.
If we don't have coverage for a specific file... | IndexError | dataset/ETHPy150Open dropbox/changes/changes/api/source_details.py/SourceDetailsAPIView._filter_coverage_for_added_lines |
4,489 | def __getitem__(self, field):
try:
self.refresh()
return self.data.get(field)
except __HOLE__:
return None | KeyError | dataset/ETHPy150Open petrvanblokland/Xierpa3/xierpa3/toolbox/session/session.py/Session.__getitem__ |
4,490 | def cleanUp(self):
"""
Clean up the session for objects that can't be cpickled:
1. parsed node trees with weakrefs cannot be cpickled;
python v 2.4 raises a TypeError instead of pickle.UnpickleableError, so catch this exception
>>> from xpyth.xmlparser import ... | KeyError | dataset/ETHPy150Open petrvanblokland/Xierpa3/xierpa3/toolbox/session/session.py/Session.cleanUp |
4,491 | def test_unicode_libraries():
try:
unicode
except __HOLE__:
py.test.skip("for python 2.x")
#
import math
lib_m = "m"
if sys.platform == 'win32':
#there is a small chance this fails on Mingw via environ $CC
import distutils.ccompiler
if distutils.ccompiler.... | NameError | dataset/ETHPy150Open johncsnyder/SwiftKitten/cffi/testing/cffi1/test_recompiler.py/test_unicode_libraries |
4,492 | def parseRange(text):
articles = text.split('-')
if len(articles) == 1:
try:
a = int(articles[0])
return a, a
except __HOLE__:
return None, None
elif len(articles) == 2:
try:
if len(articles[0]):
l = int(articles[0])
... | ValueError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/news/nntp.py/parseRange |
4,493 | def extractCode(line):
line = line.split(' ', 1)
if len(line) != 2:
return None
try:
return int(line[0]), line[1]
except __HOLE__:
return None | ValueError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/news/nntp.py/extractCode |
4,494 | def lineReceived(self, line):
if self.inputHandler is not None:
self.inputHandler(line)
else:
parts = line.strip().split()
if len(parts):
cmd, parts = parts[0].upper(), parts[1:]
if cmd in NNTPServer.COMMANDS:
func =... | TypeError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/news/nntp.py/NNTPServer.lineReceived |
4,495 | def articleWork(self, article, cmd, func):
if self.currentGroup is None:
self.sendLine('412 no newsgroup has been selected')
else:
if not article:
if self.currentIndex is None:
self.sendLine('420 no current article has been selected')
... | ValueError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/news/nntp.py/NNTPServer.articleWork |
4,496 | @property
def _case_property_queries(self):
"""
Returns all current case_property queries
"""
try:
return self.es_query['query']['filtered']['query']['bool']['must']
except (__HOLE__, TypeError):
return [] | KeyError | dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/es/case_search.py/CaseSearchES._case_property_queries |
4,497 | def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if not argv:
argv = sys.argv
# setup command line parser
parser = E.OptionParser(version="%prog version: $Id: maf2psl.py 2879 2010-04-06 14:44:34Z andreas $",
... | ValueError | dataset/ETHPy150Open CGATOxford/cgat/scripts/maf2psl.py/main |
4,498 | def serve(self):
self.serverTransport.listen()
while True:
try:
client = self.serverTransport.accept()
t = threading.Thread(target = self.handle, args=(client,))
t.setDaemon(self.daemon)
t.start()
except __HOLE__:
raise
except Exception, x:
loggi... | KeyboardInterrupt | dataset/ETHPy150Open JT5D/Alfred-Popclip-Sublime/Sublime Text 2/SublimeEvernote/lib/thrift/server/TServer.py/TThreadedServer.serve |
4,499 | def serve(self):
def try_close(file):
try:
file.close()
except __HOLE__, e:
logging.warning(e, exc_info=True)
self.serverTransport.listen()
while True:
client = self.serverTransport.accept()
try:
pid = os.fork()
if pid: # parent
# add befo... | IOError | dataset/ETHPy150Open JT5D/Alfred-Popclip-Sublime/Sublime Text 2/SublimeEvernote/lib/thrift/server/TServer.py/TForkingServer.serve |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.