Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
2,300 | @contextlib.contextmanager
def print_output():
try:
yield
except __HOLE__ as e:
if STATUS:
print(STATUS)
raise
except Exception as e:
logging.exception('The plugin %s has failed with an unhandled '
'exception', sys.argv[0])
status... | SystemExit | dataset/ETHPy150Open rcbops/rpc-openstack/maas/plugins/maas_common.py/print_output |
2,301 | def parse_cpu_spec(spec):
"""Parse a CPU set specification.
:param spec: cpu set string eg "1-4,^3,6"
Each element in the list is either a single
CPU number, a range of CPU numbers, or a
caret followed by a CPU number to be excluded
from a previous range.
:returns: a set of CPU indexes
... | ValueError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/hardware.py/parse_cpu_spec |
2,302 | def get_number_of_serial_ports(flavor, image_meta):
"""Get the number of serial consoles from the flavor or image
:param flavor: Flavor object to read extra specs from
:param image_meta: nova.objects.ImageMeta object instance
If flavor extra specs is not set, then any image meta value is permitted.
... | ValueError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/hardware.py/get_number_of_serial_ports |
2,303 | def _numa_get_pagesize_constraints(flavor, image_meta):
"""Return the requested memory page size
:param flavor: a Flavor object to read extra specs from
:param image_meta: nova.objects.ImageMeta object instance
:raises: MemoryPagesSizeInvalid or MemoryPageSizeForbidden
:returns: a page size reques... | ValueError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/hardware.py/_numa_get_pagesize_constraints |
2,304 | def host_topology_and_format_from_host(host):
"""Convenience method for getting the numa_topology out of hosts
Since we may get a host as either a dict, a db object, or an actual
ComputeNode object, or an instance of HostState class, this makes sure we
get beck either None, or an instance of objects.NU... | AttributeError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/hardware.py/host_topology_and_format_from_host |
2,305 | def _process_bulk_chunk(client, bulk_actions, raise_on_exception=True, raise_on_error=True, **kwargs):
"""
Send a bulk request to elasticsearch and process the output.
"""
# if raise on error is set, we need to collect errors per chunk before raising them
errors = []
try:
# send the act... | StopIteration | dataset/ETHPy150Open elastic/elasticsearch-py/elasticsearch/helpers/__init__.py/_process_bulk_chunk |
2,306 | def __init__(self, text=None, filename=None, exclude=None):
"""
Source can be provided as `text`, the text itself, or `filename`, from
which the text will be read. Excluded lines are those that match
`exclude`, a regex.
"""
assert text or filename, "CodeParser needs eit... | IOError | dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/coverage/parser.py/CodeParser.__init__ |
2,307 | def _opcode_set(*names):
"""Return a set of opcodes by the names in `names`."""
s = set()
for name in names:
try:
s.add(_opcode(name))
except __HOLE__:
pass
return s
# Opcodes that leave the code object. | KeyError | dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/coverage/parser.py/_opcode_set |
2,308 | @transform( thresholdFoldChange, suffix(".foldchange"), ".shared.foldchange")
def sharedIntervalsFoldChangeThreshold(infile, outfile):
'''identify shared intervals between datasets at different foldchange thresholds'''
# Open foldchange file and read
fc_file = open(infile, "r")
foldchange = []
for ... | OSError | dataset/ETHPy150Open CGATOxford/cgat/obsolete/pipeline_proj012_chipseq.py/sharedIntervalsFoldChangeThreshold |
2,309 | def fromMessage(klass, message, op_endpoint=UNUSED):
"""Construct me from an OpenID Message.
@param message: The OpenID associate request
@type message: openid.message.Message
@returntype: L{AssociateRequest}
"""
if message.isOpenID1():
session_type = messag... | ValueError | dataset/ETHPy150Open CollabQ/CollabQ/openid/server/server.py/AssociateRequest.fromMessage |
2,310 | def verify(self, assoc_handle, message):
"""Verify that the signature for some data is valid.
@param assoc_handle: The handle of the association used to sign the
data.
@type assoc_handle: str
@param message: The signed message to verify
@type message: openid.message... | ValueError | dataset/ETHPy150Open CollabQ/CollabQ/openid/server/server.py/Signatory.verify |
2,311 | def get_page():
""" Get current page
Get current page from query string `page=x`,
if page not given returns `1` instead.
"""
try:
page = request.args.get('page', 1)
return int(page)
except __HOLE__:
return 1 | ValueError | dataset/ETHPy150Open DoubleCiti/daimaduan.com/daimaduan/utils/pagination.py/get_page |
2,312 | def post_template_populate(self):
current_post = getattr(self.request, get_setting('CURRENT_POST_IDENTIFIER'), None)
if current_post and self.request.user.has_perm('djangocms_blog.change_post'): # pragma: no cover # NOQA
# removing page meta menu, if present, to avoid confusion
... | ImportError | dataset/ETHPy150Open nephila/djangocms-blog/djangocms_blog/cms_toolbar.py/BlogToolbar.post_template_populate |
2,313 | def _split_mod_var_names(resource_name):
""" Return (module_name, class_name) pair from given string. """
try:
dot_index = resource_name.rindex('.')
except __HOLE__:
# no dot found
return '', resource_name
return resource_name[:dot_index], resource_name[dot_index + 1:] | ValueError | dataset/ETHPy150Open wuher/devil/devil/perm/management.py/_split_mod_var_names |
2,314 | def _instantiate_resource(item):
try:
res = item()
except __HOLE__:
return None
else:
return res if _is_resource_obj(res) else None | TypeError | dataset/ETHPy150Open wuher/devil/devil/perm/management.py/_instantiate_resource |
2,315 | def get_resources():
from django.conf import settings
try:
acl_resources = settings.ACL_RESOURCES
except __HOLE__:
# ACL_RESOURCES is not specified in settings
return []
else:
return _handle_list(acl_resources) | AttributeError | dataset/ETHPy150Open wuher/devil/devil/perm/management.py/get_resources |
2,316 | def GetApplication():
'''Return app environment as: ARCMAP, ARCGIS_PRO, OTHER'''
global app_found
if app_found != 'NOT_SET':
return app_found
try:
from arcpy import mp
except __HOLE__:
try:
from arcpy import mapping
mxd = arcpy.mapping.MapDocumen... | ImportError | dataset/ETHPy150Open Esri/solutions-geoprocessing-toolbox/operational_graphics/toolboxes/scripts/Utilities.py/GetApplication |
2,317 | @task
def watch_docs():
"""Run build the docs when a file changes."""
try:
import sphinx_autobuild # noqa
except __HOLE__:
print('ERROR: watch task requires the sphinx_autobuild package.')
print('Install it with:')
print(' pip install sphinx-autobuild')
sys.exit(1... | ImportError | dataset/ETHPy150Open jmcarp/nplusone/tasks.py/watch_docs |
2,318 | def erase_in_display(self, type_of=0, private=False):
"""Erases display in a specific way.
:param int type_of: defines the way the line should be erased in:
* ``0`` -- Erases from cursor to end of screen, including
cursor position.
* ``1`` -- Erases from beginning... | IndexError | dataset/ETHPy150Open jonathanslenders/pymux/pymux/screen.py/BetterScreen.erase_in_display |
2,319 | def select_graphic_rendition(self, *attrs):
""" Support 256 colours """
replace = {}
if not attrs:
attrs = [0]
else:
attrs = list(attrs[::-1])
while attrs:
attr = attrs.pop()
if attr in self._fg_colors:
replace["c... | IndexError | dataset/ETHPy150Open jonathanslenders/pymux/pymux/screen.py/BetterScreen.select_graphic_rendition |
2,320 | def __ReadPickled(self, filename):
"""Reads a pickled object from the given file and returns it.
"""
self.__file_lock.acquire()
try:
try:
if (filename and
filename != '/dev/null' and
os.path.isfile(filename) and
os.stat(filename).st_size > 0):
... | TypeError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/datastore_file_stub.py/DatastoreFileStub.__ReadPickled |
2,321 | def __WritePickled(self, obj, filename):
"""Pickles the object and writes it to the given file.
"""
if not filename or filename == '/dev/null' or not obj:
return
descriptor, tmp_filename = tempfile.mkstemp(dir=os.path.dirname(filename))
tmpfile = os.fdopen(descriptor, 'wb')
pickler ... | OSError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/datastore_file_stub.py/DatastoreFileStub.__WritePickled |
2,322 | def _Get(self, key):
app_kind, _, k = self._GetEntityLocation(key)
try:
return datastore_stub_util.LoadEntity(
self.__entities_by_kind[app_kind][k].protobuf)
except __HOLE__:
pass | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/datastore_file_stub.py/DatastoreFileStub._Get |
2,323 | def _Delete(self, key):
app_kind, eg_k, k = self._GetEntityLocation(key)
self.__entities_lock.acquire()
try:
del self.__entities_by_kind[app_kind][k]
del self.__entities_by_group[eg_k][k]
if not self.__entities_by_kind[app_kind]:
del self.__entities_by_kind[app_kind]
if not... | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/datastore_file_stub.py/DatastoreFileStub._Delete |
2,324 | def _GetQueryCursor(self, query, filters, orders, index_list):
app_id = query.app()
namespace = query.name_space()
pseudo_kind = None
if query.has_kind() and query.kind() in self._pseudo_kinds:
pseudo_kind = self._pseudo_kinds[query.kind()]
self.__entities_lock.acquire()
try:
ap... | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/datastore_file_stub.py/DatastoreFileStub._GetQueryCursor |
2,325 | def test_csv_file_header_index_error_in_legislators_current(self):
try:
with open(LEGISLATORS_CURRENT_CSV_FILE, 'rU') as legislators_current_data:
reader = csv.reader(legislators_current_data) # Create a regular tuple reader
for index, legislator_row in enumerate(re... | IndexError | dataset/ETHPy150Open wevoteeducation/WeVoteBase/import_export_theunitedstatesio/tests.py/ImportExportTheUnitedStatesIoTests.test_csv_file_header_index_error_in_legislators_current |
2,326 | def issue(server, account, domains, key_size, key_file=None, csr_file=None, output_path=None):
if not output_path or output_path == '.':
output_path = os.getcwd()
# Load key or generate
if key_file:
try:
with open(key_file, 'rb') as f:
certificate_key = load_priv... | IOError | dataset/ETHPy150Open veeti/manuale/manuale/issue.py/issue |
2,327 | def run(plotIt=True):
"""
EM: FDEM: 1D: Inversion
=======================
Here we will create and run a FDEM 1D inversion.
"""
cs, ncx, ncz, npad = 5., 25, 15, 15
hx = [(cs,ncx), (cs,npad,1.3)]
hz = [(cs,npad,-1.3), (cs,ncz), (cs,npad,1.3)]
mesh = Mesh.CylMesh([hx,1,hz... | ImportError | dataset/ETHPy150Open simpeg/simpeg/SimPEG/Examples/EM_FDEM_1D_Inversion.py/run |
2,328 | def tearDown(self):
"""
Remove all remaining triggers from the reactor.
"""
while self.triggers:
trigger = self.triggers.pop()
try:
reactor.removeSystemEventTrigger(trigger)
except (ValueError, __HOLE__):
pass | KeyError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/test/test_internet.py/SystemEventTestCase.tearDown |
2,329 | def main(self, argv=None):
"""The main program controller."""
if argv is None:
argv = sys.argv
# Step 1: Determine the command and arguments.
try:
self.progName = progName = os.path.basename(argv[0])
self.command = command = optionDashesRE.s... | IndexError | dataset/ETHPy150Open skyostil/tracy/src/generator/Cheetah/CheetahWrapper.py/CheetahWrapper.main |
2,330 | @property
def container_id(self):
"""
Find a container id
If one isn't already set, we ask docker for the container whose name is
the same as the recorded container_name
"""
if getattr(self, "_container_id", None):
return self._container_id
try:
... | ValueError | dataset/ETHPy150Open realestate-com-au/harpoon/harpoon/option_spec/image_objs.py/Image.container_id |
2,331 | def headerData(self, section, orientation, role=Qt.DisplayRole):
"""defines which labels the view/user shall see.
Args:
section (int): the row or column number.
orientation (Qt.Orienteation): Either horizontal or vertical.
role (Qt.ItemDataRole, optional): Defaults t... | IndexError | dataset/ETHPy150Open datalyze-solutions/pandas-qt/pandasqt/models/ColumnDtypeModel.py/ColumnDtypeModel.headerData |
2,332 | def do_search(self, args):
try:
#add arguments
doParser = self.arg_search()
try:
doArgs = doParser.parse_args(args.split())
except __HOLE__ as e:
return
#call UForge API
printer.out("Search package '"+doArgs.... | SystemExit | dataset/ETHPy150Open usharesoft/hammr/src/hammr/commands/os/os.py/Os.do_search |
2,333 | @filters("sqlite", sqla_exc.IntegrityError,
(r"^.*columns?(?P<columns>[^)]+)(is|are)\s+not\s+unique$",
r"^.*UNIQUE\s+constraint\s+failed:\s+(?P<columns>.+)$",
r"^.*PRIMARY\s+KEY\s+must\s+be\s+unique.*$"))
def _sqlite_dupe_key_error(integrity_error, match, engine_name, is_disconnect):
""... | IndexError | dataset/ETHPy150Open openstack/oslo.db/oslo_db/sqlalchemy/exc_filters.py/_sqlite_dupe_key_error |
2,334 | @filters("sqlite", sqla_exc.IntegrityError,
r"(?i).*foreign key constraint failed")
@filters("postgresql", sqla_exc.IntegrityError,
r".*on table \"(?P<table>[^\"]+)\" violates "
"foreign key constraint \"(?P<constraint>[^\"]+)\".*\n"
"DETAIL: Key \((?P<key>.+)\)=\(.+\) "
"i... | IndexError | dataset/ETHPy150Open openstack/oslo.db/oslo_db/sqlalchemy/exc_filters.py/_foreign_key_error |
2,335 | @filters("postgresql", sqla_exc.IntegrityError,
r".*new row for relation \"(?P<table>.+)\" "
"violates check constraint "
"\"(?P<check_name>.+)\"")
def _check_constraint_error(
integrity_error, match, engine_name, is_disconnect):
"""Filter for check constraint errors."""
try:... | IndexError | dataset/ETHPy150Open openstack/oslo.db/oslo_db/sqlalchemy/exc_filters.py/_check_constraint_error |
2,336 | def resolve_model_string(model_string, default_app=None):
"""
Resolve an 'app_label.model_name' string into an actual model class.
If a model class is passed in, just return that.
Raises a LookupError if a model can not be found, or ValueError if passed
something that is neither a model or a string... | ValueError | dataset/ETHPy150Open torchbox/wagtail/wagtail/wagtailcore/utils.py/resolve_model_string |
2,337 | def run_scenario(user_asked_for, data_exists_as, allow_derivation=True,
allow_integration=False, allow_prefixes_in_denominator=False,
round_result=6):
userunit = unitconv.parse_unitname(user_asked_for, fold_scale_prefix=False)
prefixclass = unitconv.prefix_class_for(userunit['s... | KeyError | dataset/ETHPy150Open vimeo/graph-explorer/graph_explorer/test/test_unitconv.py/run_scenario |
2,338 | def conform_to_value(self, owner, value):
"""
When no root node has been set, we prompt the user to choose one from
the list of choices. Otherwise, we set the ``WidgyWidget`` class as
the widget we use for this field instance.
"""
self.owner = owner
if isinstance... | AttributeError | dataset/ETHPy150Open fusionbox/django-widgy/widgy/forms.py/WidgyFormField.conform_to_value |
2,339 | def __init__(self, *args, **kwargs):
super(WidgyFormMixin, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
if isinstance(field, WidgyFormField):
try:
value = getattr(self.instance, name)
except __HOLE__:
... | ObjectDoesNotExist | dataset/ETHPy150Open fusionbox/django-widgy/widgy/forms.py/WidgyFormMixin.__init__ |
2,340 | def setup_key_pair(self, context):
key_name = '%s%s' % (context.project_id, FLAGS.vpn_key_suffix)
try:
result = cloud._gen_key(context, context.user_id, key_name)
private_key = result['private_key']
key_dir = os.path.join(FLAGS.keys_path, context.user_id)
... | IOError | dataset/ETHPy150Open nii-cloud/dodai-compute/nova/cloudpipe/pipelib.py/CloudPipe.setup_key_pair |
2,341 | def _getResolver(self, serverResponses, maximumQueries=10):
"""
Create and return a new L{root.Resolver} modified to resolve queries
against the record data represented by C{servers}.
@param serverResponses: A mapping from dns server addresses to
mappings. The inner mapping... | KeyError | dataset/ETHPy150Open twisted/twisted/twisted/names/test/test_rootresolve.py/RootResolverTests._getResolver |
2,342 | def _load_plugin_config(self, plugin):
"""Loads a JSON or YAML config for a given plugin
Keyword arguments:
plugin -- Name of plugin to load config for.
Raises:
AmbiguousConfigError -- Raised when two configs exist for plugin.
ConfigNotFoundError -- Raised when ex... | IOError | dataset/ETHPy150Open JohnMaguire/Cardinal/cardinal/plugins.py/PluginManager._load_plugin_config |
2,343 | def get_object_from_date_based_view(request, *args, **kwargs): # noqa
"""
Get object from generic date_based.detail view
Parameters
----------
request : instance
An instance of HttpRequest
Returns
-------
instance
An instance of model object or None
"""
import ... | ValueError | dataset/ETHPy150Open lambdalisue/django-permission/src/permission/decorators/functionbase.py/get_object_from_date_based_view |
2,344 | def test_execute_failed(self):
task = Task(retries=3, async=True)
task.to_call(fail_task, 2, 7)
self.assertEqual(task.status, WAITING)
try:
self.gator.execute(task)
self.assertEqual(task.status, RETRYING)
self.gator.execute(task)
self.gato... | IOError | dataset/ETHPy150Open toastdriven/alligator/tests/test_gator.py/GatorTestCase.test_execute_failed |
2,345 | def test_execute_retries(self):
task = Task(retries=3, async=True)
task.to_call(eventual_success(), 2, 7)
try:
self.gator.execute(task)
except IOError:
pass
try:
self.gator.execute(task)
except __HOLE__:
pass
res ... | IOError | dataset/ETHPy150Open toastdriven/alligator/tests/test_gator.py/GatorTestCase.test_execute_retries |
2,346 | def get(self):
old = False
parse = urlparse(self.url)
if parse.netloc == "www.svtplay.se" or parse.netloc == "svtplay.se":
if parse.path[:6] != "/video" and parse.path[:6] != "/klipp":
yield ServiceError("This mode is not supported anymore. need the url with the vide... | KeyError | dataset/ETHPy150Open spaam/svtplay-dl/lib/svtplay_dl/service/svtplay.py/Svtplay.get |
2,347 | def _lock(self):
"""Lock the entire multistore."""
self._thread_lock.acquire()
try:
self._file.open_and_lock()
except __HOLE__ as e:
if e.errno == errno.ENOSYS:
logger.warn('File system does not support locking the '
'cr... | IOError | dataset/ETHPy150Open google/oauth2client/oauth2client/contrib/multistore_file.py/_MultiStore._lock |
2,348 | def _refresh_data_cache(self):
"""Refresh the contents of the multistore.
The multistore must be locked when this is called.
Raises:
NewerCredentialStoreError: Raised when a newer client has written
the store.
"""
self._data = {}
try:
... | TypeError | dataset/ETHPy150Open google/oauth2client/oauth2client/contrib/multistore_file.py/_MultiStore._refresh_data_cache |
2,349 | def _delete_credential(self, key):
"""Delete a credential and write the multistore.
This must be called when the multistore is locked.
Args:
key: The key used to retrieve the credential
"""
try:
del self._data[key]
except __HOLE__:
pa... | KeyError | dataset/ETHPy150Open google/oauth2client/oauth2client/contrib/multistore_file.py/_MultiStore._delete_credential |
2,350 | def update_result(self, context):
outfile = os.path.join(context.output_directory, 'hwuitest.output')
with open(outfile, 'w') as wfh:
wfh.write(self.output)
context.add_artifact('hwuitest', outfile, kind='raw')
normal = re.compile(r'(?P<value>\d*)(?P<unit>\w*)')
with... | ValueError | dataset/ETHPy150Open ARM-software/workload-automation/wlauto/workloads/hwuitest/__init__.py/HWUITest.update_result |
2,351 | def fetch():
try:
stream = _local.stream
except __HOLE__:
return ''
return stream.reset() | AttributeError | dataset/ETHPy150Open Eforcers/gae-flask-todo/lib/werkzeug/debug/console.py/ThreadedStream.fetch |
2,352 | def displayhook(obj):
try:
stream = _local.stream
except __HOLE__:
return _displayhook(obj)
# stream._write bypasses escaping as debug_repr is
# already generating HTML for us.
if obj is not None:
_local._current_ipy.locals['_'] = obj
... | AttributeError | dataset/ETHPy150Open Eforcers/gae-flask-todo/lib/werkzeug/debug/console.py/ThreadedStream.displayhook |
2,353 | def __getattribute__(self, name):
if name == '__members__':
return dir(sys.__stdout__)
try:
stream = _local.stream
except __HOLE__:
stream = sys.__stdout__
return getattr(stream, name) | AttributeError | dataset/ETHPy150Open Eforcers/gae-flask-todo/lib/werkzeug/debug/console.py/ThreadedStream.__getattribute__ |
2,354 | def get_source_by_code(self, code):
try:
return self._storage[id(code)]
except __HOLE__:
pass | KeyError | dataset/ETHPy150Open Eforcers/gae-flask-todo/lib/werkzeug/debug/console.py/_ConsoleLoader.get_source_by_code |
2,355 | def GetString(self, name, all=False):
"""Get the first value for a key, or None if it is not defined.
This configuration file is used first, if the key is not
defined or all = True then the defaults are also searched.
"""
try:
v = self._cache[_key(name)]
except __HOLE__:
if se... | KeyError | dataset/ETHPy150Open android/tools_repo/git_config.py/GitConfig.GetString |
2,356 | def SetString(self, name, value):
"""Set the value(s) for a key.
Only this configuration file is modified.
The supplied value should be either a string,
or a list of strings (to store multiple values).
"""
key = _key(name)
try:
old = self._cache[key]
except __HOLE__:
... | KeyError | dataset/ETHPy150Open android/tools_repo/git_config.py/GitConfig.SetString |
2,357 | def GetRemote(self, name):
"""Get the remote.$name.* configuration values as an object.
"""
try:
r = self._remotes[name]
except __HOLE__:
r = Remote(self, name)
self._remotes[r.name] = r
return r | KeyError | dataset/ETHPy150Open android/tools_repo/git_config.py/GitConfig.GetRemote |
2,358 | def GetBranch(self, name):
"""Get the branch.$name.* configuration values as an object.
"""
try:
b = self._branches[name]
except __HOLE__:
b = Branch(self, name)
self._branches[b.name] = b
return b | KeyError | dataset/ETHPy150Open android/tools_repo/git_config.py/GitConfig.GetBranch |
2,359 | def HasSection(self, section, subsection = ''):
"""Does at least one key in section.subsection exist?
"""
try:
return subsection in self._sections[section]
except __HOLE__:
return False | KeyError | dataset/ETHPy150Open android/tools_repo/git_config.py/GitConfig.HasSection |
2,360 | def _ReadPickle(self):
try:
if os.path.getmtime(self._pickle) \
<= os.path.getmtime(self.file):
os.remove(self._pickle)
return None
except OSError:
return None
try:
Trace(': unpickle %s', self.file)
fd = open(self._pickle, 'rb')
try:
return cPickle... | IOError | dataset/ETHPy150Open android/tools_repo/git_config.py/GitConfig._ReadPickle |
2,361 | def _SavePickle(self, cache):
try:
fd = open(self._pickle, 'wb')
try:
cPickle.dump(cache, fd, cPickle.HIGHEST_PROTOCOL)
finally:
fd.close()
except __HOLE__:
if os.path.exists(self._pickle):
os.remove(self._pickle)
except cPickle.PickleError:
if os.path.e... | IOError | dataset/ETHPy150Open android/tools_repo/git_config.py/GitConfig._SavePickle |
2,362 | def close_ssh():
global _master_keys_lock
terminate_ssh_clients()
for p in _master_processes:
try:
os.kill(p.pid, SIGTERM)
p.wait()
except OSError:
pass
del _master_processes[:]
_master_keys.clear()
d = ssh_sock(create=False)
if d:
try:
os.rmdir(os.path.dirname(d))
... | OSError | dataset/ETHPy150Open android/tools_repo/git_config.py/close_ssh |
2,363 | @property
def ReviewProtocol(self):
if self._review_protocol is None:
if self.review is None:
return None
u = self.review
if not u.startswith('http:') and not u.startswith('https:'):
u = 'http://%s' % u
if u.endswith('/Gerrit'):
u = u[:len(u) - len('/Gerrit')]
... | HTTPError | dataset/ETHPy150Open android/tools_repo/git_config.py/Remote.ReviewProtocol |
2,364 | @permission_required("core.manage_shop")
def manage_properties(request, product_id, template_name="manage/product/properties.html"):
"""Displays the UI for manage the properties for the product with passed
product_id.
"""
product = get_object_or_404(Product, pk=product_id)
# Generate lists of prope... | IndexError | dataset/ETHPy150Open diefenbach/django-lfs/lfs/manage/product/properties.py/manage_properties |
2,365 | @permission_required("core.manage_shop")
@require_POST
def update_property_groups(request, product_id):
"""Updates property groups for the product with passed id.
"""
selected_group_ids = request.POST.getlist("selected-property-groups")
product = Product.objects.get(pk=product_id)
for property_grou... | ObjectDoesNotExist | dataset/ETHPy150Open diefenbach/django-lfs/lfs/manage/product/properties.py/update_property_groups |
2,366 | def getreal(z):
try:
return z.real
except __HOLE__:
return z | AttributeError | dataset/ETHPy150Open sunlightlabs/clearspending/completeness/statlib/matfunc.py/getreal |
2,367 | def getimag(z):
try:
return z.imag
except __HOLE__:
return 0 | AttributeError | dataset/ETHPy150Open sunlightlabs/clearspending/completeness/statlib/matfunc.py/getimag |
2,368 | def getconj(z):
try:
return z.conjugate()
except __HOLE__:
return z | AttributeError | dataset/ETHPy150Open sunlightlabs/clearspending/completeness/statlib/matfunc.py/getconj |
2,369 | def lookup(self, service, **kwargs):
service_name = service.name
try:
instances = self.registry[service_name]
for data in instances:
service.update(data.get('id'), **data)
except __HOLE__:
raise LookupFailure()
return service | KeyError | dataset/ETHPy150Open deliveryhero/lymph/lymph/discovery/static.py/StaticServiceRegistryHub.lookup |
2,370 | def test_project_duplicate_creation(self):
orig_dir = os.getcwd()
tmp_dir = tempfile.mkdtemp()
try:
os.chdir(tmp_dir)
cli = StackStrapCLI()
cli.main(['template', 'add', 'test-template', repo_url])
cli.main(['create', 'test_project_creation', 'test... | SystemExit | dataset/ETHPy150Open stackstrap/stackstrap/tests/test_project.py/ProjectTestCase.test_project_duplicate_creation |
2,371 | def search(request):
query_string = prepare_solr_query_string(request.GET.get('q', ""))
search_terms = query_string.split()
index_query = SearchQuerySet().models(Project)
spelling_suggestion = None
#FIXME: Workaround for https://github.com/toastdriven/django-haystack/issues/364
# Only the else p... | TypeError | dataset/ETHPy150Open rvanlaar/easy-transifex/src/transifex/transifex/txcommon/views.py/search |
2,372 | def onFailure(self, failure):
"""
Clean up observers, parse the failure and errback the deferred.
@param failure: the failure protocol element. Holds details on
the error condition.
@type failure: L{domish.Element}
"""
self.xmlstream.removeObserv... | AttributeError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/words/protocols/jabber/sasl.py/SASLInitiatingInitializer.onFailure |
2,373 | def import_class(import_str):
"""Returns a class from a string including module and class."""
mod_str, _sep, class_str = import_str.rpartition('.')
try:
__import__(mod_str)
return getattr(sys.modules[mod_str], class_str)
except (ValueError, __HOLE__):
raise ImportError('Class %s ... | AttributeError | dataset/ETHPy150Open openstack-dev/heat-cfnclient/heat_cfnclient/openstack/common/importutils.py/import_class |
2,374 | def import_object_ns(name_space, import_str, *args, **kwargs):
"""Tries to import object from default namespace.
Imports a class and return an instance of it, first by trying
to find the class in a default namespace, then failing back to
a full path if not found in the default namespace.
"""
im... | ImportError | dataset/ETHPy150Open openstack-dev/heat-cfnclient/heat_cfnclient/openstack/common/importutils.py/import_object_ns |
2,375 | def try_import(import_str, default=None):
"""Try to import a module and if it fails return default."""
try:
return import_module(import_str)
except __HOLE__:
return default | ImportError | dataset/ETHPy150Open openstack-dev/heat-cfnclient/heat_cfnclient/openstack/common/importutils.py/try_import |
2,376 | def __init__(self):
try:
if settings.LDAP_MASTER_DISABLE == True: return
except __HOLE__: pass
try:
logger.debug("TLS AVAILABLE? %d" % (ldap.TLS_AVAIL))
print "LDAP SETTINGS->"+settings.LDAP_MASTER_URI
ldap.set_option(ldap.OPT_X_TLS_CACERTFILE, settings.L... | AttributeError | dataset/ETHPy150Open fp7-ofelia/ocf/expedient/src/python/expedient/common/ldapproxy/models.py/LdapProxy.__init__ |
2,377 | def create_or_replace (self, dn, entry):
try:
if settings.LDAP_MASTER_DISABLE == True: return
except __HOLE__: pass
count = 0
while 1:
try:
resultid = self.proxy.search(dn, ldap.SCOPE_BASE)
try:
t, data = self.pr... | AttributeError | dataset/ETHPy150Open fp7-ofelia/ocf/expedient/src/python/expedient/common/ldapproxy/models.py/LdapProxy.create_or_replace |
2,378 | def delete (self, dn):
try:
if settings.LDAP_MASTER_DISABLE == True: return
except __HOLE__: pass
try:
resultid = self.proxy.search(dn, ldap.SCOPE_BASE)
try:
t, data = self.proxy.result(resultid, 1)
logger.debug("LdapProxy.delet... | AttributeError | dataset/ETHPy150Open fp7-ofelia/ocf/expedient/src/python/expedient/common/ldapproxy/models.py/LdapProxy.delete |
2,379 | def __init__(self, exp, queue, payload, worker=None):
excc = sys.exc_info()[0]
self._exception = excc
try:
self._traceback = traceback.format_exc()
except __HOLE__:
self._traceback = None
self._worker = worker
self._queue = queue
self._pa... | AttributeError | dataset/ETHPy150Open binarydud/pyres/pyres/failure/base.py/BaseBackend.__init__ |
2,380 | def search(request, template="search_results.html", extra_context=None):
"""
Display search results. Takes an optional "contenttype" GET parameter
in the form "app-name.ModelName" to limit search results to a single model.
"""
query = request.GET.get("q", "")
page = request.GET.get("page", 1)
... | TypeError | dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/core/views.py/search |
2,381 | @staff_member_required
def static_proxy(request):
"""
Serves TinyMCE plugins inside the inline popups and the uploadify
SWF, as these are normally static files, and will break with
cross-domain JavaScript errors if ``STATIC_URL`` is an external
host. URL for the file is passed in via querystring in ... | IOError | dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/core/views.py/static_proxy |
2,382 | def __del__(self):
try:
if not self._socket.closed:
self.close()
except (__HOLE__, TypeError):
pass | AttributeError | dataset/ETHPy150Open 0rpc/zerorpc-python/zerorpc/events.py/Events.__del__ |
2,383 | def close(self):
try:
self._send.close()
except AttributeError:
pass
try:
self._recv.close()
except __HOLE__:
pass
self._socket.close() | AttributeError | dataset/ETHPy150Open 0rpc/zerorpc-python/zerorpc/events.py/Events.close |
2,384 | @cached_property
def metadata(self):
pathname = os.path.join(self.dirname, self.filename)
name_ver = '%s-%s' % (self.name, self.version)
info_dir = '%s.dist-info' % name_ver
wrapper = codecs.getreader('utf-8')
with ZipFile(pathname, 'r') as zf:
wheel_metadata = se... | KeyError | dataset/ETHPy150Open anzev/hedwig/build/pip/pip/_vendor/distlib/wheel.py/Wheel.metadata |
2,385 | def get_hash(self, data, hash_kind=None):
if hash_kind is None:
hash_kind = self.hash_kind
try:
hasher = getattr(hashlib, hash_kind)
except __HOLE__:
raise DistlibException('Unsupported hash algorithm: %r' % hash_kind)
result = hasher(data).digest()
... | AttributeError | dataset/ETHPy150Open anzev/hedwig/build/pip/pip/_vendor/distlib/wheel.py/Wheel.get_hash |
2,386 | def _get_extensions(self):
pathname = os.path.join(self.dirname, self.filename)
name_ver = '%s-%s' % (self.name, self.version)
info_dir = '%s.dist-info' % name_ver
arcname = posixpath.join(info_dir, 'EXTENSIONS')
wrapper = codecs.getreader('utf-8')
result = []
wit... | KeyError | dataset/ETHPy150Open anzev/hedwig/build/pip/pip/_vendor/distlib/wheel.py/Wheel._get_extensions |
2,387 | def get_namespace(self):
try:
return Namespace.get(self.kwargs['namespace_name'])
except __HOLE__:
raise Http404(
_('Namespace: %s, not found') % self.kwargs['namespace_name']
) | KeyError | dataset/ETHPy150Open mayan-edms/mayan-edms/mayan/apps/smart_settings/views.py/NamespaceDetailView.get_namespace |
2,388 | def check_bind2(self):
sp = self.pygrData.Bio.Seq.Swissprot.sp42()
hbb = sp['HBB1_TORMA']
exons = hbb.exons.keys()
assert len(exons)==1, 'number of expected annotations'
annoDB = self.pygrData.Bio.Annotation.annoDB()
exon = annoDB[1]
assert exons[0] == exon, 'test annotation comparison'
... | KeyError | dataset/ETHPy150Open cjlee112/pygr/tests/metabase_test.py/check_bind2 |
2,389 | def setUp(self):
TestBase.setUp(self)
logger.debug('accessing ensembldb.ensembl.org')
conn = sqlgraph.DBServerInfo(host='ensembldb.ensembl.org',
user='anonymous', passwd='')
try:
translationDB = sqlgraph.SQLTable(
'homo_sap... | ImportError | dataset/ETHPy150Open cjlee112/pygr/tests/metabase_test.py/DBServerInfo_Test.setUp |
2,390 | def test_xmlrpc(self):
"Test XMLRPC"
self.metabase.clear_cache() # force all requests to reload
self.metabase.update("http://localhost:%s" % self.server.port)
check_match(self)
check_dir(self)
check_dir_noargs(self)
check_dir_download(self)
check_dir_re(s... | ValueError | dataset/ETHPy150Open cjlee112/pygr/tests/metabase_test.py/XMLRPC_Test.test_xmlrpc |
2,391 | def GetKey():
"""Fetches rcpkey from metadata of the instance.
Returns:
RPC key in string.
"""
try:
response = urllib.urlopen(
'http://metadata/computeMetadata/v1beta1/instance/attributes/rpckey')
return response.read()
except __HOLE__:
return '' | IOError | dataset/ETHPy150Open GoogleCloudPlatform/Data-Pipeline/app/static/hadoop_scripts/rpc_daemon/__main__.py/GetKey |
2,392 | @app.route('/mapreduceasync', methods=['GET', 'POST'])
def MapReduceAsync():
"""Handler of MapReduce asynchronous request."""
app.logger.info('ACCESS URL: %s', flask.request.path)
try:
os.mkdir(MAPREDUCE_RESULT_DIR)
except __HOLE__:
# The result directory already exists. Do nothing.
pass
mapredu... | OSError | dataset/ETHPy150Open GoogleCloudPlatform/Data-Pipeline/app/static/hadoop_scripts/rpc_daemon/__main__.py/MapReduceAsync |
2,393 | def load_path_attr(path):
i = path.rfind(".")
module, attr = path[:i], path[i + 1:]
try:
mod = importlib.import_module(module)
except ImportError as e:
raise ImproperlyConfigured(
"Error importing {0}: '{1}'".format(module, e)
)
try:
attr = getattr(mod, at... | AttributeError | dataset/ETHPy150Open pinax/pinax-stripe/pinax/stripe/conf.py/load_path_attr |
2,394 | def importpath(path, error_text=None):
"""
Import value by specified ``path``.
Value can represent module, class, object, attribute or method.
If ``error_text`` is not None and import will
raise ImproperlyConfigured with user friendly text.
"""
result = None
attrs = []
parts = path.... | ImportError | dataset/ETHPy150Open bashu/django-easy-maps/easy_maps/utils.py/importpath |
2,395 | def __init__( self, toklist, name=None, asList=True, modal=True ):
if self.__doinit:
self.__doinit = False
self.__name = None
self.__parent = None
self.__accumNames = {}
if isinstance(toklist, list):
self.__toklist = toklist[:]
... | KeyError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/external/pyparsing/_pyparsing.py/ParseResults.__init__ |
2,396 | def _normalizeParseActionArgs( f ):
"""Internal method used to decorate parse actions that take fewer than 3 arguments,
so that all parse actions can be called as f(s,l,t)."""
STAR_ARGS = 4
try:
restore = None
if isinstance(f,type):
restore = f... | TypeError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/external/pyparsing/_pyparsing.py/ParserElement._normalizeParseActionArgs |
2,397 | def _parseNoCache( self, instring, loc, doActions=True, callPreParse=True ):
debugging = ( self.debug ) #and doActions )
if debugging or self.failAction:
#~ print ("Match",self,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) ))
if (self.debugActions[0] ):
... | IndexError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/external/pyparsing/_pyparsing.py/ParserElement._parseNoCache |
2,398 | def parseFile( self, file_or_filename, parseAll=False ):
"""Execute the parse expression on the given file or filename.
If a filename is specified (instead of a file object),
the entire file is opened, read, and closed before parsing.
"""
try:
file_contents = fi... | AttributeError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/external/pyparsing/_pyparsing.py/ParserElement.parseFile |
2,399 | def __init__( self, matchString ):
super(Literal,self).__init__()
self.match = matchString
self.matchLen = len(matchString)
try:
self.firstMatchChar = matchString[0]
except __HOLE__:
warnings.warn("null string passed to Literal; use Empty() instead",
... | IndexError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/external/pyparsing/_pyparsing.py/Literal.__init__ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.