Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
4,200 | def __init__(self, features, mask=None, specs=['kl'], Ks=[3],
cores=None, algorithm=None, min_dist=None,
status_fn=True, progressbar=None, **flann_args):
if progressbar is None:
progressbar = status_fn is True
self.status_fn = status_fn = get_status_fn(statu... | AttributeError | dataset/ETHPy150Open dougalsutherland/py-sdm/sdm/np_divs.py/_DivEstimator.__init__ |
4,201 | def inner_run(self, *args, **options):
from django.conf import settings
from django.utils import translation
threading = options.get('use_threading')
shutdown_message = options.get('shutdown_message', '')
quit_command = (sys.platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'
... | AttributeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/core/management/commands/runserver.py/BaseRunserverCommand.inner_run |
4,202 | def _convert_permissions(permissions):
if isinstance(permissions, (int, float)):
return int(permissions)
try:
permissions = int(permissions, 8)
except (__HOLE__, TypeError):
LOG.warning("Fail to process permissions %s, assuming %s",
permissions, DEFAULT_PERMISSION... | ValueError | dataset/ETHPy150Open openstack/cloudbase-init/cloudbaseinit/plugins/common/userdataplugins/cloudconfigplugins/write_files.py/_convert_permissions |
4,203 | def _process_content(content, encoding):
"""Decode the content taking into consideration the encoding."""
result = content
if six.PY3 and not isinstance(result, six.binary_type):
# At this point, content will be string, which is wrong for Python 3.
result = result.encode()
steps = _deco... | TypeError | dataset/ETHPy150Open openstack/cloudbase-init/cloudbaseinit/plugins/common/userdataplugins/cloudconfigplugins/write_files.py/_process_content |
4,204 | def _write_file(path, content, permissions=DEFAULT_PERMISSIONS,
open_mode="wb"):
"""Writes a file with the given content.
Also the function sets the file mode as specified.
The function arguments are the following:
path: The absolute path to the location on the filesystem where
... | OSError | dataset/ETHPy150Open openstack/cloudbase-init/cloudbaseinit/plugins/common/userdataplugins/cloudconfigplugins/write_files.py/_write_file |
4,205 | def get_locale():
'''
Get the current system locale
CLI Example:
.. code-block:: bash
salt '*' locale.get_locale
'''
cmd = ''
if salt.utils.systemd.booted(__context__):
params = _parse_dbus_locale() if HAS_DBUS else _parse_localectl()
return params.get('LANG', '')
... | IndexError | dataset/ETHPy150Open saltstack/salt/salt/modules/localemod.py/get_locale |
4,206 | def avail(locale):
'''
Check if a locale is available.
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' locale.avail 'en_US.UTF-8'
'''
try:
normalized_locale = salt.utils.locales.normalize_locale(locale)
except __HOLE__:
log.error('Unable ... | IndexError | dataset/ETHPy150Open saltstack/salt/salt/modules/localemod.py/avail |
4,207 | def gen_locale(locale, **kwargs):
'''
Generate a locale. Options:
.. versionadded:: 2014.7.0
:param locale: Any locale listed in /usr/share/i18n/locales or
/usr/share/i18n/SUPPORTED for Debian and Gentoo based distributions,
which require the charmap to be specified as part of the loca... | OSError | dataset/ETHPy150Open saltstack/salt/salt/modules/localemod.py/gen_locale |
4,208 | def updateTimer(self):
"""update the elapsed time of framer in current outline
use store.stamp for current time reference
"""
try:
self.elapsed = self.store.stamp - self.stamp
except __HOLE__: #one or both stamps are not numbers
self.stamp = self.store... | TypeError | dataset/ETHPy150Open ioflo/ioflo/ioflo/base/framing.py/Framer.updateTimer |
4,209 | def resolveOverLinks(self):
"""Starting with self.over climb over links resolving the links as needed along the way
"""
over = self.over
under = self
while over: #not beyond top
if not isinstance(over, Frame): #over is name of frame not ref so resolve
... | KeyError | dataset/ETHPy150Open ioflo/ioflo/ioflo/base/framing.py/Frame.resolveOverLinks |
4,210 | def start(self, *args, **kwargs):
"""Starts the instance.
:raises RuntimeError: has been already started.
:raises TypeError: :meth:`run` is not canonical.
"""
if self.is_running():
raise RuntimeError('Already started')
self._running = self.run(*args, **kwarg... | StopIteration | dataset/ETHPy150Open what-studio/profiling/profiling/utils.py/Runnable.start |
4,211 | def stop(self):
"""Stops the instance.
:raises RuntimeError: has not been started.
:raises TypeError: :meth:`run` is not canonical.
"""
if not self.is_running():
raise RuntimeError('Not started')
running, self._running = self._running, None
try:
... | StopIteration | dataset/ETHPy150Open what-studio/profiling/profiling/utils.py/Runnable.stop |
4,212 | def detect(self, callback):
self.context.request.prevent_result_storage = True
try:
if not Detector.detect_task:
celery_tasks = CeleryTasks(
self.context.config.SQS_QUEUE_KEY_ID,
self.context.config.SQS_QUEUE_KEY_SECRET,
... | RuntimeError | dataset/ETHPy150Open thumbor/thumbor/thumbor/detectors/queued_sqs_detector/__init__.py/Detector.detect |
4,213 | def translate(s, a, b=None, c=None):
"""Return ``s`` where characters have been replaced or deleted.
SYNTAX
======
translate(s, None, deletechars):
all characters in ``deletechars`` are deleted
translate(s, map [,deletechars]):
all characters in ``deletechars`` (if provided) are de... | TypeError | dataset/ETHPy150Open sympy/sympy/sympy/utilities/misc.py/translate |
4,214 | def close(self):
"""Closes all files. If you put real :class:`file` objects into the
:attr:`files` dict you can call this method to automatically close
them all in one go.
"""
if self.closed:
return
try:
files = self.files.itervalues()
exc... | AttributeError | dataset/ETHPy150Open IanLewis/kay/kay/lib/werkzeug/test.py/EnvironBuilder.close |
4,215 | def handle_write(self):
while True:
with self.deque_lock:
try:
next_msg = self.deque.popleft()
except __HOLE__:
self._writable = False
return
try:
sent = self.send(next_msg)
... | IndexError | dataset/ETHPy150Open datastax/python-driver/cassandra/io/asyncorereactor.py/AsyncoreConnection.handle_write |
4,216 | def _set_attributes(self):
self._attributes = {}
all_attributes = list(_get_all_attributes(self._root_node))
for key, value in all_attributes:
# commented since enketo forms may have the template attribute in
# multiple xml tags and I dont see the harm in overiding
... | AssertionError | dataset/ETHPy150Open kobotoolbox/kobocat/onadata/apps/logger/xform_instance_parser.py/XFormInstanceParser._set_attributes |
4,217 | def invalidate(self, func, *args, **kwargs):
"""Invalidate a cache decorated function. You must call this with
the same positional and keyword arguments as what you did when you
call the decorated function, otherwise the cache will not be deleted.
The usage is simple::
@cac... | AttributeError | dataset/ETHPy150Open fengsp/rc/rc/cache.py/BaseCache.invalidate |
4,218 | def rfc3339(dt_obj):
'''
dt_obj: datetime object or string
The filter use `datetime.datetime.isoformat()`, which is in ISO 8601
format, not in RFC 3339 format, but they have a lot in common, so I used
ISO 8601 format directly.
'''
if isinstance(dt_obj, datetime.datetime):
pass
e... | ValueError | dataset/ETHPy150Open tankywoo/simiki/simiki/jinja_exts.py/rfc3339 |
4,219 | def __getattr__(self, name):
try:
return self._fields[name].value
except __HOLE__:
raise AttributeError('No attribute %s' % name) | KeyError | dataset/ETHPy150Open correl/Transmission-XBMC/resources/lib/transmissionrpc/torrent.py/Torrent.__getattr__ |
4,220 | def __getattr__(self, name):
if name in self._PROXY_FUNCS:
try:
return getattr(self._adapter, name)
except __HOLE__:
pass
raise AttributeError(name) | AttributeError | dataset/ETHPy150Open openstack/requests-mock/requests_mock/mocker.py/MockerCore.__getattr__ |
4,221 | def _get_ipaddress(node):
"""Adds the ipaddress attribute to the given node object if not already
present and it is correctly given by ohai
Returns True if ipaddress is added, False otherwise
"""
if "ipaddress" not in node:
with settings(hide('stdout'), warn_only=True):
output =... | ValueError | dataset/ETHPy150Open tobami/littlechef/littlechef/chef.py/_get_ipaddress |
4,222 | def pop(self, num=1):
"""
Pops values from storage
"""
values = []
for i in range(0, num):
try:
values.append(self._list.pop(0))
except __HOLE__:
break
return values | IndexError | dataset/ETHPy150Open bbrodriges/pholcidae/pholcidae2.py/SyncStorage.pop |
4,223 | def _saferound(value, decimal_places):
"""
Rounds a float value off to the desired precision
"""
try:
f = float(value)
except __HOLE__:
return ''
format = '%%.%df' % decimal_places
return format % f | ValueError | dataset/ETHPy150Open eyeseast/python-tablefu/table_fu/formatting.py/_saferound |
4,224 | def dollar_signs(value, failure_string='N/A'):
"""
Converts an integer into the corresponding number of dollar sign symbols.
If the submitted value isn't a string, returns the `failure_string` keyword
argument.
Meant to emulate the illustration of price range on Yelp.
"""
try:
... | ValueError | dataset/ETHPy150Open eyeseast/python-tablefu/table_fu/formatting.py/dollar_signs |
4,225 | def percentage(value, decimal_places=1, multiply=True, failure_string='N/A'):
"""
Converts a floating point value into a percentage value.
Number of decimal places set by the `decimal_places` kwarg. Default is one.
By default the number is multiplied by 100. You can prevent it from doing
t... | ValueError | dataset/ETHPy150Open eyeseast/python-tablefu/table_fu/formatting.py/percentage |
4,226 | def percent_change(value, decimal_places=1, multiply=True, failure_string='N/A'):
"""
Converts a floating point value into a percentage change value.
Number of decimal places set by the `precision` kwarg. Default is one.
Non-floats are assumed to be zero division errors and are presented as
... | ValueError | dataset/ETHPy150Open eyeseast/python-tablefu/table_fu/formatting.py/percent_change |
4,227 | def ratio(value, decimal_places=0, failure_string='N/A'):
"""
Converts a floating point value a X:1 ratio.
Number of decimal places set by the `precision` kwarg. Default is one.
"""
try:
f = float(value)
except __HOLE__:
return failure_string
return _saferound(f, decimal... | ValueError | dataset/ETHPy150Open eyeseast/python-tablefu/table_fu/formatting.py/ratio |
4,228 | def __init__(self, *args, **kwargs):
try:
self.search_fields = kwargs.pop('search_fields')
except __HOLE__:
pass
super(LinkSearchField, self).__init__(*args, **kwargs) | KeyError | dataset/ETHPy150Open jrief/djangocms-cascade/cmsplugin_cascade/link/fields.py/LinkSearchField.__init__ |
4,229 | def main():
filename = os.path.join('hdf5', 'example_05.hdf5')
env = Environment(trajectory='Example_05_Euler_Integration',
filename=filename,
file_title='Example_05_Euler_Integration',
overwrite_file=True,
comment='Go for ... | ImportError | dataset/ETHPy150Open SmokinCaterpillar/pypet/examples/example_05_custom_parameter.py/main |
4,230 | @property
def full_filepath(self):
if self.filepath:
default_storage = get_storage_class()()
try:
return default_storage.path(self.filepath)
except __HOLE__:
# read file from s3
name, ext = os.path.splitext(self.filepath)
... | NotImplementedError | dataset/ETHPy150Open kobotoolbox/kobocat/onadata/apps/viewer/models/export.py/Export.full_filepath |
4,231 | def unmarshal(self, v):
"""
Convert the value from Strava API format to useful python representation.
If the value does not appear in the choices attribute we log an error rather
than raising an exception as this may be caused by a change to the API upstream
so we want to fail g... | KeyError | dataset/ETHPy150Open hozn/stravalib/stravalib/attributes.py/ChoicesAttribute.unmarshal |
4,232 | def __init__(self,
config,
module_dict,
app_code_path,
imp_module=imp,
os_module=os,
dummy_thread_module=dummy_thread,
pickle_module=pickle):
"""Initializer.
Args:
config: AppInfoExternal instance rep... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/dev_appserver_import_hook.py/HardenedModulesHook.__init__ |
4,233 | @Trace
def FindModuleRestricted(self,
submodule,
submodule_fullname,
search_path):
"""Locates a module while enforcing module import restrictions.
Args:
submodule: The short name of the submodule (i.e., the last section of... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/dev_appserver_import_hook.py/HardenedModulesHook.FindModuleRestricted |
4,234 | def FindPathHook(self, submodule, submodule_fullname, path_entry):
"""Helper for FindModuleRestricted to find a module in a sys.path entry.
Args:
submodule:
submodule_fullname:
path_entry: A single sys.path entry, or None representing the builtins.
Returns:
Either None (if nothing ... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/dev_appserver_import_hook.py/HardenedModulesHook.FindPathHook |
4,235 | @Trace
def FindAndLoadModule(self,
submodule,
submodule_fullname,
search_path):
"""Finds and loads a module, loads it, and adds it to the module dictionary.
Args:
submodule: Name of the module to import (e.g., baz).
submodule... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/dev_appserver_import_hook.py/HardenedModulesHook.FindAndLoadModule |
4,236 | def serve_status_page(self, port):
Handler.task_graph = self.task_graph
print("Starting server at http://localhost:%d" % port)
try:
httpd = SocketServer.TCPServer(("", port), Handler)
except socket.error, error:
raise CommandLineException(error.strerror)
t... | KeyboardInterrupt | dataset/ETHPy150Open deanmalmgren/flo/flo/commands/status.py/Command.serve_status_page |
4,237 | def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if argv is None:
argv = sys.argv
parser = E.OptionParser(
version="%prog version: $Id: split_fasta.py 1714 2007-12-11 16:51:12Z andreas $")
parser.add_option("-f", "--fil... | AttributeError | dataset/ETHPy150Open CGATOxford/cgat/scripts/split_fasta.py/main |
4,238 | def _match(S, N):
"""Structural matching of term S to discrimination net node N."""
stack = deque()
restore_state_flag = False
# matches are stored in a tuple, because all mutations result in a copy,
# preventing operations from changing matches stored on the stack.
matches = ()
while True:... | TypeError | dataset/ETHPy150Open dask/dask/dask/rewrite.py/_match |
4,239 | @classmethod
def _fetch_remote(cls, uri, depth_indicator=1):
"""
return remote document and actual remote uri
:type uri: str
:type depth_indicator: int
:rtype: (document: str | None, uri)
"""
cls._log("debug", "fetch remote(%d): %s" % (depth_indicator, uri))
... | AttributeError | dataset/ETHPy150Open k4cg/nichtparasoup/crawler/__init__.py/Crawler._fetch_remote |
4,240 | def close(self):
if not self.close_called:
self.close_called = True
try:
self.file.close()
except (OSError, __HOLE__):
pass
try:
self.unlink(self.name)
except (OSError)... | IOError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/_internal/django/core/files/temp.py/TemporaryFile.close |
4,241 | def load(self):
session_data = {}
try:
session_file = open(self._key_to_file(), "rb")
try:
file_data = session_file.read()
# Don't fail if there is no data in the session file.
# We may have opened the empty placeholder file.
... | IOError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/contrib/sessions/backends/file.py/SessionStore.load |
4,242 | def save(self, must_create=False):
# Get the session data now, before we start messing
# with the file it is stored within.
session_data = self._get_session(no_load=must_create)
session_file_name = self._key_to_file()
try:
# Make sure the file exists. If it does no... | OSError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/contrib/sessions/backends/file.py/SessionStore.save |
4,243 | def delete(self, session_key=None):
if session_key is None:
if self.session_key is None:
return
session_key = self.session_key
try:
os.unlink(self._key_to_file(session_key))
except __HOLE__:
pass | OSError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/contrib/sessions/backends/file.py/SessionStore.delete |
4,244 | def _get_mro(obj_class):
""" Get a reasonable method resolution order of a class and its superclasses
for both old-style and new-style classes.
"""
if not hasattr(obj_class, '__mro__'):
# Old-style class. Mix in object to make a fake new-style class.
try:
obj_class = type(obj... | TypeError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/lib/pretty.py/_get_mro |
4,245 | def pretty(self, obj):
"""Pretty print the given object."""
obj_id = id(obj)
cycle = obj_id in self.stack
self.stack.append(obj_id)
self.begin_group()
try:
obj_class = getattr(obj, '__class__', None) or type(obj)
# First try to find registered sing... | TypeError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/lib/pretty.py/RepresentationPrinter.pretty |
4,246 | def remove(self, group):
try:
self.queue[group.depth].remove(group)
except __HOLE__:
pass | ValueError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/lib/pretty.py/GroupQueue.remove |
4,247 | def _default_pprint(obj, p, cycle):
"""
The default print function. Used if an object does not provide one and
it's none of the builtin objects.
"""
klass = getattr(obj, '__class__', None) or type(obj)
if getattr(klass, '__repr__', None) != object.__repr__:
# A user-provided repr.
... | AttributeError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/lib/pretty.py/_default_pprint |
4,248 | def _votes(self, val):
"""
Returns cleaned version of votes or 0 if it's a non-numeric value.
"""
if val.strip() == '':
return 0
try:
return int(float(val))
except __HOLE__:
# Count'y convert value from string
return 0 | ValueError | dataset/ETHPy150Open openelections/openelections-core/openelex/us/wv/load.py/WVLoader._votes |
4,249 | def _writein(self, row):
# sometimes write-in field not present
try:
write_in = row['Write-In?'].strip()
except __HOLE__:
write_in = None
return write_in | KeyError | dataset/ETHPy150Open openelections/openelections-core/openelex/us/wv/load.py/WVLoader._writein |
4,250 | def __init__(self):
super().__init__()
self._handling_lock = Lock()
self._teardown_callback_stack = LifoQueue() # we execute callbacks in the reverse order that they were added
self._logger = log.get_logger(__name__)
self._handled_exceptions = Queue()
self._teardown_call... | ValueError | dataset/ETHPy150Open box/ClusterRunner/app/util/unhandled_exception_handler.py/UnhandledExceptionHandler.__init__ |
4,251 | def handle_modeladmin(self, modeladmin):
def datepublisher_admin(self, obj):
return '%s – %s' % (
format_date(obj.publication_date),
format_date(obj.publication_end_date, '∞'),
)
datepublisher_admin.allow_tags = True
datepublish... | ValueError | dataset/ETHPy150Open feincms/feincms/feincms/module/extensions/datepublisher.py/Extension.handle_modeladmin |
4,252 | def main():
test = TestUniqueChars()
test.test_unique_chars(unique_chars)
try:
test.test_unique_chars(unique_chars_hash)
test.test_unique_chars(unique_chars_inplace)
except __HOLE__:
# Alternate solutions are only defined
# in the solutions file
pass | NameError | dataset/ETHPy150Open donnemartin/interactive-coding-challenges/arrays_strings/unique_chars/test_unique_chars.py/main |
4,253 | def BuildDependentLibraries(env, src_dir): # pylint: disable=R0914
INCLUDES_RE = re.compile(
r"^\s*#include\s+(\<|\")([^\>\"\']+)(?:\>|\")", re.M)
LIBSOURCE_DIRS = [env.subst(d) for d in env.get("LIBSOURCE_DIRS", [])]
# start internal prototypes
class IncludeFinder(object):
def __in... | ValueError | dataset/ETHPy150Open platformio/platformio/platformio/builder/tools/platformio.py/BuildDependentLibraries |
4,254 | def __getattribute__(self, key):
"""overrides getattr's behaviour for the instance"""
try: return object.__getattribute__(self, key)
except __HOLE__:
try: return self.service.applicationContext[key]
except KeyError:
raise AttributeError("'%s' object has no... | AttributeError | dataset/ETHPy150Open OrbitzWorldwide/droned/droned/lib/droned/applications/__init__.py/StorageMixin.__getattribute__ |
4,255 | def loadAppPlugins(self):
"""load all of the application plugins"""
#find all application plugins
my_dir = os.path.dirname(__file__)
for filename in os.listdir(my_dir):
if not filename.endswith('.py'): continue
if filename == '__init__.py': continue
mo... | TypeError | dataset/ETHPy150Open OrbitzWorldwide/droned/droned/lib/droned/applications/__init__.py/_PluginFactory.loadAppPlugins |
4,256 | def _pluginSetup(self, plugin):
"""get romeo configuration bound in order to update the instance
This gets called by the factory below.
Note: ROMEO configuration always overrides the ApplicationPlugin's
default constructor!!!!
"""
plugin.log('applying configu... | AssertionError | dataset/ETHPy150Open OrbitzWorldwide/droned/droned/lib/droned/applications/__init__.py/_PluginFactory._pluginSetup |
4,257 | def clean_ldap_user_dn_template(self):
tpl = self.cleaned_data["ldap_user_dn_template"]
try:
test = tpl % {"user": "toto"}
except (__HOLE__, ValueError):
raise forms.ValidationError(_("Invalid syntax"))
return tpl | KeyError | dataset/ETHPy150Open tonioo/modoboa/modoboa/core/app_settings.py/GeneralParametersForm.clean_ldap_user_dn_template |
4,258 | def to_django_settings(self):
"""Apply LDAP related parameters to Django settings
Doing so, we can use the django_auth_ldap module.
"""
try:
import ldap
from django_auth_ldap.config import LDAPSearch, PosixGroupType
ldap_available = True
excep... | ImportError | dataset/ETHPy150Open tonioo/modoboa/modoboa/core/app_settings.py/GeneralParametersForm.to_django_settings |
4,259 | def __init__(self, config, prefix=None):
self.manager, self.Manager = None, None
self.Transport = None
self.running = False
self.config = config = Bunch(config)
if prefix is not None:
self.config = config = Bunch.partial(prefix, config)
if 'manager' in config and isinstance(config.manager, dict):
... | AttributeError | dataset/ETHPy150Open marrow/mailer/marrow/mailer/__init__.py/Mailer.__init__ |
4,260 | def isNumeric(num):
'''
Returns True if the string representation of num is numeric
Inputs:
=======
num : A string representation of a number.
Outputs:
========
True if num is numeric, False otherwise
'''
try:
float(num)
except __HOLE__, ... | ValueError | dataset/ETHPy150Open pivotalsoftware/pymadlib/pymadlib/utils.py/isNumeric |
4,261 | def textile(value):
"""
Textile processing.
"""
try:
import textile
except __HOLE__:
warnings.warn("The Python textile library isn't installed.",
RuntimeWarning)
return value
return textile.textile(force_text(value),
encod... | ImportError | dataset/ETHPy150Open Fantomas42/django-blog-zinnia/zinnia/markups.py/textile |
4,262 | def markdown(value, extensions=MARKDOWN_EXTENSIONS):
"""
Markdown processing with optionally using various extensions
that python-markdown supports.
`extensions` is an iterable of either markdown.Extension instances
or extension paths.
"""
try:
import markdown
except __HOLE__:
... | ImportError | dataset/ETHPy150Open Fantomas42/django-blog-zinnia/zinnia/markups.py/markdown |
4,263 | def restructuredtext(value, settings=RESTRUCTUREDTEXT_SETTINGS):
"""
RestructuredText processing with optionnally custom settings.
"""
try:
from docutils.core import publish_parts
except __HOLE__:
warnings.warn("The Python docutils library isn't installed.",
Run... | ImportError | dataset/ETHPy150Open Fantomas42/django-blog-zinnia/zinnia/markups.py/restructuredtext |
4,264 | def vcard(self, qs, out):
try:
import vobject
except __HOLE__:
print(self.style.ERROR("Please install python-vobject to use the vcard export format."))
import sys
sys.exit(1)
for ent in qs:
card = vobject.vCard()
card.add('f... | ImportError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/django-extensions-1.5.0/django_extensions/management/commands/export_emails.py/Command.vcard |
4,265 | def ast_walk(root, dispatcher, debug=False):
"""Walk the given tree and for each node apply the corresponding function
as defined by the dispatcher.
If one node type does not have any function defined for it, it simply
returns the node unchanged.
Parameters
----------
root : Node
... | KeyError | dataset/ETHPy150Open cournape/Bento/bento/parser/nodes.py/ast_walk |
4,266 | def __contains__(self, key):
try:
value = self[key]
except __HOLE__:
return False
return True | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.3/django/test/utils.py/ContextList.__contains__ |
4,267 | def setup_test_template_loader(templates_dict, use_cached_loader=False):
"""
Changes Django to only find templates from within a dictionary (where each
key is the template name and each value is the corresponding template
content to return).
Use meth:`restore_template_loaders` to restore the origin... | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.3/django/test/utils.py/setup_test_template_loader |
4,268 | def isNetflixInternal():
try:
open("/etc/profile.d/netflix_environment.sh", "r")
return True
except __HOLE__:
return False | IOError | dataset/ETHPy150Open Netflix/gcviz/root/apps/apache/htdocs/AdminGCViz/visualize-gc.py/isNetflixInternal |
4,269 | def try_to_draw_vms_cache_refresh_lines():
if(isNetflixInternal()):
try:
fp = open(vmsGCReportDirectory + os.path.sep + 'vms-cache-refresh-overall-events-milliseconds')
except IOError:
return
for line in fp:
line = line.rstrip('\r\n')
try:
... | ValueError | dataset/ETHPy150Open Netflix/gcviz/root/apps/apache/htdocs/AdminGCViz/visualize-gc.py/try_to_draw_vms_cache_refresh_lines |
4,270 | @listens_for(File, 'after_delete')
def del_file(mapper, connection, target):
if target.path:
try:
os.remove(op.join(file_path, target.path))
except __HOLE__:
# Don't care if was not deleted because it does not exist
pass | OSError | dataset/ETHPy150Open flask-admin/flask-admin/examples/forms/app.py/del_file |
4,271 | @listens_for(Image, 'after_delete')
def del_image(mapper, connection, target):
if target.path:
# Delete image
try:
os.remove(op.join(file_path, target.path))
except OSError:
pass
# Delete thumbnail
try:
os.remove(op.join(file_path,
... | OSError | dataset/ETHPy150Open flask-admin/flask-admin/examples/forms/app.py/del_image |
4,272 | def targets(self, tgt, tgt_type):
'''
Return a dict of {'id': {'ipv4': <ipaddr>}} data sets to be used as
targets given the passed tgt and tgt_type
'''
targets = {}
for back in self._gen_back():
f_str = '{0}.targets'.format(back)
if f_str not in se... | IOError | dataset/ETHPy150Open saltstack/salt/salt/roster/__init__.py/Roster.targets |
4,273 | def GetAppInfo(self, user_info):
"""Grabs the application info from the user_info dictionary.
Args:
user_info: dictionary of application info
Returns:
tuple of bundle_id, app_version, app_path
"""
bundle_id, app_version, app_path = None, None, None
try:
bundle_id = user_info[... | KeyError | dataset/ETHPy150Open google/macops/crankd/ApplicationUsage.py/ApplicationUsage.GetAppInfo |
4,274 | def logtail(fh, date_format, start_date, field, parser=None, delimiter=None,
**kwargs):
"""Tail rows from logfile, based on complex expressions such as a
date range."""
dt_start = dateutil.parser.parse(start_date)
_is_match = partial(_is_match_full, date_format=date_format, dt_s... | ValueError | dataset/ETHPy150Open adamhadani/logtools/logtools/_tail.py/logtail |
4,275 | def add_datapoints(self, stats):
"""Add all of the data points for a node
:param str stats: The stats content from Apache as a string
"""
matches = PATTERN.findall(stats or '')
for key, value in matches:
try:
value = int(value)
except __... | ValueError | dataset/ETHPy150Open MeetMe/newrelic-plugin-agent/newrelic_plugin_agent/plugins/apache_httpd.py/ApacheHTTPD.add_datapoints |
4,276 | def __validate_date_arg(self, cmd_arg):
try:
date = dateutil.parser.parse(self.command_args[cmd_arg])
return date
except __HOLE__:
raise AzureInvalidCommand(
cmd_arg + '=' + self.command_args[cmd_arg]
) | ValueError | dataset/ETHPy150Open SUSE/azurectl/azurectl/commands/storage_container.py/StorageContainerTask.__validate_date_arg |
4,277 | def _ProcessHost(self, d):
"""Retrieves recovery data from an LDAP host and escrows to CauliflowerVest.
Args:
d: a single ldap.conn.result3() result dictionary.
Raises:
InvalidDistinguishedName: the given host had an invalid DN.
InvalidRecoveryGuid: the given host had an invalid Recovery ... | ValueError | dataset/ETHPy150Open google/cauliflowervest/src/cauliflowervest/client/win/bitlocker_ad_sync.py/BitLockerAdSync._ProcessHost |
4,278 | def get_output(self):
try:
command = [self.config['bin'], 'sourcestats']
if self.config['use_sudo']:
command.insert(0, self.config['sudo_cmd'])
return subprocess.Popen(command,
stdout=subprocess.PIPE).communicate()[0]
... | OSError | dataset/ETHPy150Open BrightcoveOS/Diamond/src/collectors/chronyd/chronyd.py/ChronydCollector.get_output |
4,279 | def collect(self):
output = self.get_output()
for line in output.strip().split("\n"):
m = LINE_PATTERN.search(line)
if m is None:
continue
source = cleanup_source(m.group('source'))
offset = float(m.group('offset'))
unit = m.g... | NotImplementedError | dataset/ETHPy150Open BrightcoveOS/Diamond/src/collectors/chronyd/chronyd.py/ChronydCollector.collect |
4,280 | @api.login_required(oauth_scopes=['teams:write'])
@api.parameters(parameters.CreateTeamParameters())
@api.response(schemas.DetailedTeamSchema())
@api.response(code=http_exceptions.Conflict.code)
def post(self, args):
"""
Create a new team.
"""
try:
try:
... | ValueError | dataset/ETHPy150Open frol/flask-restplus-server-example/app/modules/teams/resources.py/Teams.post |
4,281 | @api.login_required(oauth_scopes=['teams:write'])
@api.resolve_object_by_model(Team, 'team')
@api.permission_required(
permissions.OwnerRolePermission,
kwargs_on_request=lambda kwargs: {'obj': kwargs['team']}
)
@api.permission_required(permissions.WriteAccessPermission())
@api.parame... | ValueError | dataset/ETHPy150Open frol/flask-restplus-server-example/app/modules/teams/resources.py/TeamByID.patch |
4,282 | @api.login_required(oauth_scopes=['teams:write'])
@api.resolve_object_by_model(Team, 'team')
@api.permission_required(
permissions.OwnerRolePermission,
kwargs_on_request=lambda kwargs: {'obj': kwargs['team']}
)
@api.permission_required(permissions.WriteAccessPermission())
@api.parame... | ValueError | dataset/ETHPy150Open frol/flask-restplus-server-example/app/modules/teams/resources.py/TeamMembers.post |
4,283 | def parse(self, stream, media_type=None, parser_context=None):
"""
Parses the incoming bytestream as XML and returns the resulting data.
"""
assert etree, 'XMLParser requires defusedxml to be installed'
parser_context = parser_context or {}
encoding = parser_context.get(... | ValueError | dataset/ETHPy150Open jpadilla/django-rest-framework-xml/rest_framework_xml/parsers.py/XMLParser.parse |
4,284 | def _type_convert(self, value):
"""
Converts the value returned by the XMl parse into the equivalent
Python type
"""
if value is None:
return value
try:
return datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
except ValueError:
... | ValueError | dataset/ETHPy150Open jpadilla/django-rest-framework-xml/rest_framework_xml/parsers.py/XMLParser._type_convert |
4,285 | def get(self, key, default=None):
try:
return self[key] # <4>
except __HOLE__:
return default # <5> | KeyError | dataset/ETHPy150Open fluentpython/example-code/03-dict-set/strkeydict0.py/StrKeyDict0.get |
4,286 | def _construct_tree(path):
if not op.exists(path):
try:
os.makedirs(op.dirname(path))
except __HOLE__:
pass | OSError | dataset/ETHPy150Open rossant/ipymd/ipymd/core/scripts.py/_construct_tree |
4,287 | def safe_rm(tgt):
'''
Safely remove a file
'''
try:
os.remove(tgt)
except (__HOLE__, OSError):
pass | IOError | dataset/ETHPy150Open saltstack/salt/salt/utils/__init__.py/safe_rm |
4,288 | def is_empty(filename):
'''
Is a file empty?
'''
try:
return os.stat(filename).st_size == 0
except __HOLE__:
# Non-existent file or permission denied to the parent dir
return False | OSError | dataset/ETHPy150Open saltstack/salt/salt/utils/__init__.py/is_empty |
4,289 | def get_uid(user=None):
"""
Get the uid for a given user name. If no user given,
the current euid will be returned. If the user
does not exist, None will be returned. On
systems which do not support pwd or os.geteuid
it will return None.
"""
if not HAS_PWD:
result = None
elif... | AttributeError | dataset/ETHPy150Open saltstack/salt/salt/utils/__init__.py/get_uid |
4,290 | def get_gid(group=None):
"""
Get the gid for a given group name. If no group given,
the current egid will be returned. If the group
does not exist, None will be returned. On
systems which do not support grp or os.getegid
it will return None.
"""
if grp is None:
result = None
... | AttributeError | dataset/ETHPy150Open saltstack/salt/salt/utils/__init__.py/get_gid |
4,291 | def daemonize(redirect_out=True):
'''
Daemonize a process
'''
try:
pid = os.fork()
if pid > 0:
# exit first parent
reinit_crypto()
sys.exit(salt.defaults.exitcodes.EX_OK)
except OSError as exc:
log.error(
'fork #1 failed: {0} ({... | OSError | dataset/ETHPy150Open saltstack/salt/salt/utils/__init__.py/daemonize |
4,292 | def profile_func(filename=None):
'''
Decorator for adding profiling to a nested function in Salt
'''
def proffunc(fun):
def profiled_func(*args, **kwargs):
logging.info('Profiling function {0}'.format(fun.__name__))
try:
profiler = cProfile.Profile()
... | IOError | dataset/ETHPy150Open saltstack/salt/salt/utils/__init__.py/profile_func |
4,293 | def which(exe=None):
'''
Python clone of /usr/bin/which
'''
def _is_executable_file_or_link(exe):
# check for os.X_OK doesn't suffice because directory may executable
return (os.access(exe, os.X_OK) and
(os.path.isfile(exe) or os.path.islink(exe)))
if exe:
if... | AttributeError | dataset/ETHPy150Open saltstack/salt/salt/utils/__init__.py/which |
4,294 | def output_profile(pr, stats_path='/tmp/stats', stop=False, id_=None):
if pr is not None and HAS_CPROFILE:
try:
pr.disable()
if not os.path.isdir(stats_path):
os.makedirs(stats_path)
date = datetime.datetime.now().isoformat()
if id_ is None:
... | OSError | dataset/ETHPy150Open saltstack/salt/salt/utils/__init__.py/output_profile |
4,295 | def dns_check(addr, safe=False, ipv6=False):
'''
Return the ip resolved by dns, but do not exit on failure, only raise an
exception. Obeys system preference for IPv4/6 address resolution.
'''
error = False
try:
# issue #21397: force glibc to re-read resolv.conf
if HAS_RESINIT:
... | TypeError | dataset/ETHPy150Open saltstack/salt/salt/utils/__init__.py/dns_check |
4,296 | def required_module_list(docstring=None):
'''
Return a list of python modules required by a salt module that aren't
in stdlib and don't exist on the current pythonpath.
'''
if not docstring:
return []
ret = []
modules = parse_docstring(docstring).get('deps', [])
for mod in module... | ImportError | dataset/ETHPy150Open saltstack/salt/salt/utils/__init__.py/required_module_list |
4,297 | def format_call(fun,
data,
initial_ret=None,
expected_extra_kws=()):
'''
Build the required arguments and keyword arguments required for the passed
function.
:param fun: The function to get the argspec from
:param data: A dictionary containing the req... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/utils/__init__.py/format_call |
4,298 | def istextfile(fp_, blocksize=512):
'''
Uses heuristics to guess whether the given file is text or binary,
by reading a single block of bytes from the file.
If more than 30% of the chars in the block are non-text, or there
are NUL ('\x00') bytes in the block, assume this is a binary file.
'''
... | IOError | dataset/ETHPy150Open saltstack/salt/salt/utils/__init__.py/istextfile |
4,299 | def str_to_num(text):
'''
Convert a string to a number.
Returns an integer if the string represents an integer, a floating
point number if the string is a real number, or the string unchanged
otherwise.
'''
try:
return int(text)
except __HOLE__:
try:
return fl... | ValueError | dataset/ETHPy150Open saltstack/salt/salt/utils/__init__.py/str_to_num |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.