Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
9,800 | def get_latest_results(self):
"""
Gets latest results for the ladder
"""
results = {}
for result in self.result_set.filter(ladder=self).order_by('-date_added')[:10]: # [:10] to limit to 5
try:
opponent = self.result_set.filter(ladder=self, player=res... | IndexError | dataset/ETHPy150Open jzahedieh/django-tennis-ladder/ladder/models.py/Ladder.get_latest_results |
9,801 | def sanitize_css(self, text):
"""Remove potentially dangerous property declarations from CSS code.
In particular, properties using the CSS ``url()`` function with a scheme
that is not considered safe are removed:
>>> sanitizer = HTMLSanitizer()
>>> sanitizer.san... | ValueError | dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python3/genshi/filters/html.py/HTMLSanitizer.sanitize_css |
9,802 | def __init__(self, machine):
self.timers = set()
self.timers_to_remove = set()
self.timers_to_add = set()
self.log = logging.getLogger("Timing")
self.machine = machine
try:
Timing.HZ = self.machine.config['timing']['hz']
except __HOLE__:
... | KeyError | dataset/ETHPy150Open missionpinball/mpf/mpf/system/timing.py/Timing.__init__ |
9,803 | def get_filename(self, fileno):
try:
return self._filemap[fileno]
except __HOLE__:
raise ValueError, "unknown fileno" | KeyError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/hotshot/log.py/LogReader.get_filename |
9,804 | def get_funcname(self, fileno, lineno):
try:
return self._funcmap[(fileno, lineno)]
except __HOLE__:
raise ValueError, "unknown function location"
# Iteration support:
# This adds an optional (& ignored) parameter to next() so that the
# same bound method can... | KeyError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/hotshot/log.py/LogReader.get_funcname |
9,805 | def _decode_location(self, fileno, lineno):
try:
return self._funcmap[(fileno, lineno)]
except __HOLE__:
#
# This should only be needed when the log file does not
# contain all the DEFINE_FUNC records needed to allow the
# function name ... | KeyError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/hotshot/log.py/LogReader._decode_location |
9,806 | def _loadfile(self, fileno):
try:
filename = self._filemap[fileno]
except KeyError:
print "Could not identify fileId", fileno
return 1
if filename is None:
return 1
absname = os.path.normcase(os.path.join(self.cwd, filename))
... | TypeError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/hotshot/log.py/LogReader._loadfile |
9,807 | @internationalizeDocstring
def add(self, irc, msg, args, channel, user, at, expires, news):
"""[<channel>] <expires> <subject>: <text>
Adds a given news item of <text> to a channel with the given <subject>.
If <expires> isn't 0, that news item will expire <expires> seconds from
now.... | ValueError | dataset/ETHPy150Open ProgVal/Limnoria/plugins/News/plugin.py/News.add |
9,808 | def loadEntityInformation(dts, rssItem):
entityInformation = {}
# identify tables
disclosureSystem = dts.modelManager.disclosureSystem
if disclosureSystem.validationType == "EFM":
reloadCache = False
if rssItem is not None:
accession = rssItem.url.split('/')[-2]
f... | IndexError | dataset/ETHPy150Open Arelle/Arelle/arelle/plugin/xbrlDB/entityInformation.py/loadEntityInformation |
9,809 | def __eq__(self, other):
try:
return self.source == other.source and \
self.rosdep_data == other.rosdep_data
except __HOLE__:
return False | AttributeError | dataset/ETHPy150Open ros-infrastructure/rosdep/src/rosdep2/sources_list.py/CachedDataSource.__eq__ |
9,810 | def parse_sources_data(data, origin='<string>', model=None):
"""
Parse sources file format (tags optional)::
# comments and empty lines allowed
<type> <uri> [tags]
e.g.::
yaml http://foo/rosdep.yaml fuerte lucid ubuntu
If tags are specified, *all* tags must match the current
co... | ValueError | dataset/ETHPy150Open ros-infrastructure/rosdep/src/rosdep2/sources_list.py/parse_sources_data |
9,811 | def parse_sources_file(filepath):
"""
Parse file on disk
:returns: List of data sources, [:class:`DataSource`]
:raises: :exc:`InvalidData` If any error occurs reading
file, so an I/O error, non-existent file, or invalid format.
"""
try:
with open(filepath, 'r') as f:
... | IOError | dataset/ETHPy150Open ros-infrastructure/rosdep/src/rosdep2/sources_list.py/parse_sources_file |
9,812 | def _generate_key_from_urls(urls):
# urls may be a list of urls or a single string
try:
assert isinstance(urls, (list, basestring))
except __HOLE__:
assert isinstance(urls, (list, str))
# We join the urls by the '^' character because it is not allowed in urls
return '^'.join(urls if ... | NameError | dataset/ETHPy150Open ros-infrastructure/rosdep/src/rosdep2/sources_list.py/_generate_key_from_urls |
9,813 | def write_cache_file(source_cache_d, key_filenames, rosdep_data):
"""
:param source_cache_d: directory to write cache file to
:param key_filenames: filename (or list of filenames) to be used in hashing
:param rosdep_data: dictionary of data to serialize as YAML
:returns: name of file where cache is ... | OSError | dataset/ETHPy150Open ros-infrastructure/rosdep/src/rosdep2/sources_list.py/write_cache_file |
9,814 | def write_atomic(filepath, data, binary=False):
# write data to new file
fd, filepath_tmp = tempfile.mkstemp(prefix=os.path.basename(filepath) + '.tmp.', dir=os.path.dirname(filepath))
if (binary):
fmode = 'wb'
else:
fmode = 'w'
with os.fdopen(fd, fmode) as f:
f.write(data)... | OSError | dataset/ETHPy150Open ros-infrastructure/rosdep/src/rosdep2/sources_list.py/write_atomic |
9,815 | def rmtree(path):
try:
remove_tree(convert_path(path))
except __HOLE__, err:
if err.errno != errno.ENOENT:
raise | OSError | dataset/ETHPy150Open abusesa/abusehelper/setup.py/rmtree |
9,816 | def install_other(subdir):
cwd = os.getcwd()
path = os.path.join(cwd, subdir)
try:
os.chdir(path)
except __HOLE__, error:
if error.errno not in (errno.ENOENT, errno.ENOTDIR):
raise
print >> sys.stderr, "Could not find directory %r" % path
return
try:
... | OSError | dataset/ETHPy150Open abusesa/abusehelper/setup.py/install_other |
9,817 | def is_package(path):
try:
imp.find_module(".", [path])
except __HOLE__:
return False
return True | ImportError | dataset/ETHPy150Open abusesa/abusehelper/setup.py/is_package |
9,818 | def tryint(s):
try:
return int(s)
except __HOLE__:
return s | ValueError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/lxml-3.3.6/buildlibxml.py/tryint |
9,819 | def download_library(dest_dir, location, name, version_re, filename,
version=None):
if version is None:
try:
fns = ftp_listdir(location)
versions = []
for fn in fns:
match = version_re.search(fn)
if match:
... | IOError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/lxml-3.3.6/buildlibxml.py/download_library |
9,820 | def call_subprocess(cmd, **kw):
try:
from subprocess import proc_call
except __HOLE__:
# no subprocess for Python 2.3
def proc_call(cmd, **kwargs):
cwd = kwargs.get('cwd', '.')
old_cwd = os.getcwd()
try:
os.chdir(cwd)
re... | ImportError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/lxml-3.3.6/buildlibxml.py/call_subprocess |
9,821 | def see_if_file_has_new_data(self, path):
"""
Given a file path, determine whether we should read/send it.
:rtype: bool
:returns: ``True`` if the file should be read, ``False`` if not.
"""
# Catching file removal by eve before we can read the mtime from the file
... | IOError | dataset/ETHPy150Open gtaylor/EVE-Market-Data-Uploader/emdu/cache_watcher/crude_watcher.py/CrudeCacheWatcher.see_if_file_has_new_data |
9,822 | def safeConvert(self, chunk):
# Exceptionally gross, but the safest way
# I've found to ensure I get a legit unicode object
if not chunk:
return u''
if isinstance(chunk, unicode):
return chunk
try:
return chunk.decode('utf-8', 'strict')
... | AttributeError | dataset/ETHPy150Open binhex/moviegrabber/lib/site-packages/Cheetah/DummyTransaction.py/DummyResponse.safeConvert |
9,823 | def getvalue(self, outputChunks=None):
chunks = outputChunks or self._outputChunks
try:
return u''.join(chunks)
except __HOLE__, ex:
logging.debug('Trying to work around a UnicodeDecodeError in getvalue()')
logging.debug('...perhaps you could fix "%s" while yo... | UnicodeDecodeError | dataset/ETHPy150Open binhex/moviegrabber/lib/site-packages/Cheetah/DummyTransaction.py/DummyResponse.getvalue |
9,824 | @classdef.method("initialize", path="path")
def method_initialize(self, space, path):
self.path = path
try:
self.dirp = opendir(path)
except __HOLE__ as e:
raise error_for_oserror(space, e)
self.open = True | OSError | dataset/ETHPy150Open topazproject/topaz/topaz/objects/dirobject.py/W_DirObject.method_initialize |
9,825 | @classdef.singleton_method("chdir", path="path")
def method_chdir(self, space, path=None, block=None):
if path is None:
path = os.environ["HOME"]
current_dir = os.getcwd()
try:
os.chdir(path)
except __HOLE__ as e:
raise error_for_oserror(space, e)
... | OSError | dataset/ETHPy150Open topazproject/topaz/topaz/objects/dirobject.py/W_DirObject.method_chdir |
9,826 | @classdef.singleton_method("delete", path="path")
@classdef.singleton_method("rmdir", path="path")
@classdef.singleton_method("unlink", path="path")
def method_delete(self, space, path):
try:
os.rmdir(path if path else "")
except __HOLE__ as e:
raise error_for_oserror... | OSError | dataset/ETHPy150Open topazproject/topaz/topaz/objects/dirobject.py/W_DirObject.method_delete |
9,827 | @classdef.method("read")
def method_read(self, space, args_w):
self.ensure_open(space)
try:
filename = readdir(self.dirp)
except __HOLE__ as e:
raise error_for_oserror(space, e)
if filename is None:
return space.w_nil
else:
retu... | OSError | dataset/ETHPy150Open topazproject/topaz/topaz/objects/dirobject.py/W_DirObject.method_read |
9,828 | @classdef.singleton_method("mkdir", path="path", mode="int")
def method_mkdir(self, space, path, mode=0777):
try:
os.mkdir(path, mode)
except __HOLE__ as e:
raise error_for_oserror(space, e)
return space.newint(0) | OSError | dataset/ETHPy150Open topazproject/topaz/topaz/objects/dirobject.py/W_DirObject.method_mkdir |
9,829 | @classdef.singleton_method("entries", dirname="path")
def method_entries(self, space, dirname):
try:
return space.newarray([space.newstr_fromstr(d) for d in os.listdir(dirname)])
except __HOLE__ as e:
raise error_for_oserror(space, e) | OSError | dataset/ETHPy150Open topazproject/topaz/topaz/objects/dirobject.py/W_DirObject.method_entries |
9,830 | def collect(self):
if json is None:
self.log.error('Unable to import json')
return {}
url = 'http://%s:%i/metrics' % (
self.config['host'], int(self.config['port']))
try:
response = urllib2.urlopen(url)
except urllib2.HTTPError, err:
... | ValueError | dataset/ETHPy150Open BrightcoveOS/Diamond/src/collectors/dropwizard/dropwizard.py/DropwizardCollector.collect |
9,831 | def pick_disk_driver_name(hypervisor_version, is_block_dev=False):
"""Pick the libvirt primary backend driver name
If the hypervisor supports multiple backend drivers we have to tell libvirt
which one should be used.
Xen supports the following drivers: "tap", "tap2", "phy", "file", or
"qemu", bein... | OSError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/libvirt/utils.py/pick_disk_driver_name |
9,832 | def is_mounted(mount_path, source=None):
"""Check if the given source is mounted at given destination point."""
try:
check_cmd = ['findmnt', '--target', mount_path]
if source:
check_cmd.extend(['--source', source])
utils.execute(*check_cmd)
return True
except pro... | OSError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/libvirt/utils.py/is_mounted |
9,833 | @classmethod
def from_html(cls, col_str, a=1.0):
"""Creates a color object from an html style color string.
col_str -- The color string (eg. "#FF0000")
"""
if len(col_str) != 7 or col_str[0] != '#':
raise ValueError("Requires a color encoded in a html style string")
... | ValueError | dataset/ETHPy150Open PythonProgramming/Beginning-Game-Development-with-Python-and-Pygame/gameobjects/color.py/ColorRGBA.from_html |
9,834 | @classmethod
def from_palette(cls, color_name):
try:
c = cls.__new__(cls, object)
r, g, b = _palette[color_name]
c._c = [r, g, b, 1.0]
return c
except __HOLE__:
raise ValueError( "Unknown color name (%s)" % color_name ) | KeyError | dataset/ETHPy150Open PythonProgramming/Beginning-Game-Development-with-Python-and-Pygame/gameobjects/color.py/ColorRGBA.from_palette |
9,835 | def _set_r(self, r):
try:
self._c[0] = 1.0 * r
except __HOLE__:
raise TypeError( "Must be a number" ) | TypeError | dataset/ETHPy150Open PythonProgramming/Beginning-Game-Development-with-Python-and-Pygame/gameobjects/color.py/ColorRGBA._set_r |
9,836 | def _set_g(self, g):
try:
self._c[1] = 1.0 * g
except __HOLE__:
raise TypeError( "Must be a number" ) | TypeError | dataset/ETHPy150Open PythonProgramming/Beginning-Game-Development-with-Python-and-Pygame/gameobjects/color.py/ColorRGBA._set_g |
9,837 | def _set_b(self, b):
try:
self._c[2] = b
except __HOLE__:
raise TypeError( "Must be a number" ) | TypeError | dataset/ETHPy150Open PythonProgramming/Beginning-Game-Development-with-Python-and-Pygame/gameobjects/color.py/ColorRGBA._set_b |
9,838 | def _set_a(self, a):
try:
self._c[3] = a
except __HOLE__:
raise TypeError( "Must be a number" ) | TypeError | dataset/ETHPy150Open PythonProgramming/Beginning-Game-Development-with-Python-and-Pygame/gameobjects/color.py/ColorRGBA._set_a |
9,839 | def __getitem__(self, index):
try:
return self._c[index]
except __HOLE__:
raise IndexError( "Index must be 0, 1, 2, or 3" ) | IndexError | dataset/ETHPy150Open PythonProgramming/Beginning-Game-Development-with-Python-and-Pygame/gameobjects/color.py/ColorRGBA.__getitem__ |
9,840 | def __setitem__(self, index, value):
assert isinstance(value, float), "Must be a float"
try:
self._c[index] = 1.0 * value
except IndexError:
raise IndexError( "Index must be 0, 1, 2, or 3" )
except __HOLE__:
raise ValueError( "Must be a number" ) | ValueError | dataset/ETHPy150Open PythonProgramming/Beginning-Game-Development-with-Python-and-Pygame/gameobjects/color.py/ColorRGBA.__setitem__ |
9,841 | def __call__(self, keys):
c = self._c
try:
return tuple(c["rgba".index(k)] for k in keys)
except __HOLE__:
raise IndexError("Keys must be one of r, g, b, a") | ValueError | dataset/ETHPy150Open PythonProgramming/Beginning-Game-Development-with-Python-and-Pygame/gameobjects/color.py/ColorRGBA.__call__ |
9,842 | def paginate(request, queryset, per_page=20, count=None):
"""
Get a Paginator, abstracting some common paging actions.
If you pass ``count``, that value will be used instead of calling
``.count()`` on the queryset. This can be good if the queryset would
produce an expensive count query.
"""
... | ValueError | dataset/ETHPy150Open mozilla/addons-server/src/olympia/amo/utils.py/paginate |
9,843 | def cache_ns_key(namespace, increment=False):
"""
Returns a key with namespace value appended. If increment is True, the
namespace will be incremented effectively invalidating the cache.
Memcache doesn't have namespaces, but we can simulate them by storing a
"%(key)s_namespace" value. Invalidating ... | ValueError | dataset/ETHPy150Open mozilla/addons-server/src/olympia/amo/utils.py/cache_ns_key |
9,844 | def _open(self, name, mode='rb'):
if mode.startswith('w'):
parent = os.path.dirname(self.path(name))
try:
# Try/except to prevent race condition raising "File exists".
os.makedirs(parent)
except __HOLE__ as e:
if e.errno == errn... | OSError | dataset/ETHPy150Open mozilla/addons-server/src/olympia/amo/utils.py/LocalFileStorage._open |
9,845 | def smart_decode(s):
"""Guess the encoding of a string and decode it."""
if isinstance(s, unicode):
return s
enc_guess = chardet.detect(s)
try:
return s.decode(enc_guess['encoding'])
except (__HOLE__, TypeError), exc:
msg = 'Error decoding string (encoding: %r %.2f%% sure): %... | UnicodeDecodeError | dataset/ETHPy150Open mozilla/addons-server/src/olympia/amo/utils.py/smart_decode |
9,846 | def assertFileExists(self, path):
"""
Check that a file at path exists.
"""
try:
open(path)
except __HOLE__:
path_dir = os.path.dirname(path)
msg = [
"File does not exist: {0}".format(path),
"The following files ... | IOError | dataset/ETHPy150Open koenbok/Cactus/cactus/tests/__init__.py/BaseTestCase.assertFileExists |
9,847 | def assertFileDoesNotExist(self, path):
"""
Check that the file at path does not exist.
"""
try:
open(path)
except __HOLE__:
pass
else:
self.fail("File exists: {0}".format(path)) | IOError | dataset/ETHPy150Open koenbok/Cactus/cactus/tests/__init__.py/BaseTestCase.assertFileDoesNotExist |
9,848 | @classmethod
def delete_if_unreferenced(cls, model_object, publish=True, dispatch_trigger=True):
# Found in the innards of mongoengine.
# e.g. {'pk': ObjectId('5609e91832ed356d04a93cc0')}
delete_query = model_object._object_key
delete_query['ref_count__lte'] = 0
cls._get_impl... | ValueError | dataset/ETHPy150Open StackStorm/st2/st2common/st2common/persistence/trigger.py/Trigger.delete_if_unreferenced |
9,849 | @property
def host(self):
"""
Rackspace uses a separate host for API calls which is only provided
after an initial authentication request. If we haven't made that
request yet, do it here. Otherwise, just return the management host.
TODO: Fixup for when our token expires (!!!... | KeyError | dataset/ETHPy150Open infincia/AEServmon/libcloud/drivers/rackspace.py/RackspaceConnection.host |
9,850 | def load(self):
# TODO: Providers register with the provider registry when
# loaded. Here, we build the URLs for all registered providers. So, we
# really need to be sure all providers did register, which is why we're
# forcefully importing the `provider` modules here. The overall
... | ImportError | dataset/ETHPy150Open pennersr/django-allauth/allauth/socialaccount/providers/__init__.py/ProviderRegistry.load |
9,851 | @signalcommand
def handle_label(self, label, **options):
project_dir = os.getcwd()
project_name = os.path.split(project_dir)[-1]
app_name = label
app_template = options.get('app_template') or os.path.join(django_extensions.__path__[0], 'conf', 'app_template')
app_dir = os.pat... | OSError | dataset/ETHPy150Open django-extensions/django-extensions/django_extensions/management/commands/create_app.py/Command.handle_label |
9,852 | def copy_template(app_template, copy_to, project_name, app_name):
"""copies the specified template directory to the copy_to location"""
import shutil
copy_migrations = True if VERSION[:2] >= (1, 7) else False
app_template = os.path.normpath(app_template)
# walks the template structure and copies it... | OSError | dataset/ETHPy150Open django-extensions/django-extensions/django_extensions/management/commands/create_app.py/copy_template |
9,853 | def loop(self):
sockets = [self.server]
try:
while self.active():
try:
ready, _, _ = select.select(sockets, [], [], 0.1)
except __HOLE__:
raise socket.error
if not self.client:
if self... | ValueError | dataset/ETHPy150Open lunixbochs/actualvim/vim.py/VimSocket.loop |
9,854 | def _update(self, v, dirty, moved):
data = v.dump()
self.status, self.cmdline = [
s.strip() for s in data.rsplit('\n')[-3:-1]
]
try:
if self.status.count('+') >= 2:
pos, rest = self.status.split(',', 1)
row, col = pos.split('+', 1)
... | ValueError | dataset/ETHPy150Open lunixbochs/actualvim/vim.py/Vim._update |
9,855 | def _initialize_logging(self, name):
formatter = logging.Formatter("%(levelname)-7s %(module)s.%(funcName)s: %(message)s")
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(formatter)
root_logger = logging.getLogger()
log_level = os.getenv("RWB_LOG_LEVEL"... | ValueError | dataset/ETHPy150Open boakley/robotframework-workbench/rwb/lib/rwbapp.py/AbstractRwbApp._initialize_logging |
9,856 | @staticmethod
def from_string(s):
"""Deserializes a token from a string like one returned by
`to_string()`."""
if not len(s):
raise ValueError("Invalid parameter string.")
params = parse_qs(s, keep_blank_values=False)
if not len(params):
raise Valu... | KeyError | dataset/ETHPy150Open mrgaaron/LinkedIn-Client-Library/liclient/oauth2/__init__.py/Token.from_string |
9,857 | def setter(attr):
name = attr.__name__
def getter(self):
try:
return self.__dict__[name]
except __HOLE__:
raise AttributeError(name)
def deleter(self):
del self.__dict__[name]
return property(getter, attr, deleter) | KeyError | dataset/ETHPy150Open mrgaaron/LinkedIn-Client-Library/liclient/oauth2/__init__.py/setter |
9,858 | def sign(self, request, consumer, token):
"""Builds the base signature string."""
key, raw = self.signing_base(request, consumer, token)
# HMAC object.
try:
from hashlib import sha1 as sha
except __HOLE__:
import sha # Deprecated
hashed... | ImportError | dataset/ETHPy150Open mrgaaron/LinkedIn-Client-Library/liclient/oauth2/__init__.py/SignatureMethod_HMAC_SHA1.sign |
9,859 | def sorted_list_difference(expected, actual):
"""Finds elements in only one or the other of two, sorted input lists.
Returns a two-element tuple of lists. The first list contains those
elements in the "expected" list but not in the "actual" list, and the
second contains those elements in the "actual... | IndexError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/util.py/sorted_list_difference |
9,860 | def unorderable_list_difference(expected, actual):
"""Same behavior as sorted_list_difference but
for lists of unorderable items (like dicts).
As it does a linear search per item (remove) it
has O(n*n) performance."""
missing = []
while expected:
item = expected.pop()
try:
... | ValueError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/unittest/util.py/unorderable_list_difference |
9,861 | def _split(self, data):
try:
last_break = data.rindex(b'\n') + 1
return data[0:last_break], data[last_break:]
except __HOLE__:
return b'', data | ValueError | dataset/ETHPy150Open catkin/catkin_tools/catkin_tools/execution/io.py/IOBufferProtocol._split |
9,862 | def setproctitle(x):
try:
from setproctitle import setproctitle as _setproctitle
_setproctitle(x)
except __HOLE__:
pass | ImportError | dataset/ETHPy150Open douban/dpark/dpark/executor.py/setproctitle |
9,863 | def startWebServer(path):
# check the default web server
if not os.path.exists(path):
os.makedirs(path)
testpath = os.path.join(path, 'test')
with open(testpath, 'w') as f:
f.write(path)
default_uri = 'http://%s:%d/%s' % (socket.gethostname(), DEFAULT_WEB_PORT,
os.path.ba... | IOError | dataset/ETHPy150Open douban/dpark/dpark/executor.py/startWebServer |
9,864 | def forward(fd, addr, prefix=''):
f = os.fdopen(fd, 'r')
ctx = zmq.Context()
out = [None]
buf = []
def send(buf):
if not out[0]:
out[0] = ctx.socket(zmq.PUSH)
out[0].connect(addr)
out[0].send(prefix+''.join(buf))
while True:
try:
line ... | IOError | dataset/ETHPy150Open douban/dpark/dpark/executor.py/forward |
9,865 | def setup_cleaner_process(workdir):
ppid = os.getpid()
pid = os.fork()
if pid == 0:
os.setsid()
pid = os.fork()
if pid == 0:
try:
import psutil
except __HOLE__:
os._exit(1)
try:
psutil.Process(ppid).w... | ImportError | dataset/ETHPy150Open douban/dpark/dpark/executor.py/setup_cleaner_process |
9,866 | def check_memory(self, driver):
try:
import psutil
except __HOLE__:
logger.error("no psutil module")
return
mem_limit = {}
idle_since = time.time()
while True:
self.lock.acquire()
for tid, (task, pool) in self.busy_wo... | ImportError | dataset/ETHPy150Open douban/dpark/dpark/executor.py/MyExecutor.check_memory |
9,867 | def get_idle_worker(self):
try:
return self.idle_workers.pop()[1]
except __HOLE__:
p = multiprocessing.Pool(1, init_env, [self.init_args])
p.done = 0
return p | IndexError | dataset/ETHPy150Open douban/dpark/dpark/executor.py/MyExecutor.get_idle_worker |
9,868 | @staff_member_required
@csrf_exempt
def report(request):
outerkeyfunc = itemgetter('content_type_id')
content_types_list = []
if request.method == 'POST':
ignore_link_id = request.GET.get('ignore', None)
if ignore_link_id != None:
link = Link.objects.get(id=ignore_... | AttributeError | dataset/ETHPy150Open DjangoAdminHackers/django-linkcheck/linkcheck/views.py/report |
9,869 | def update_versions(self):
"""updates the versions if it is checked in the UI
"""
reference_resolution = self.generate_reference_resolution()
# send them back to environment
try:
self.environment.update_versions(reference_resolution)
except __HOLE__ as e:
... | RuntimeError | dataset/ETHPy150Open eoyilmaz/anima/anima/ui/version_updater.py/MainDialog.update_versions |
9,870 | def _reduce_ex(self, proto):
assert proto < 2
for base in self.__class__.__mro__:
if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE:
break
else:
base = object # not really reachable
if base is object:
state = None
else:
if base is self.__cla... | AttributeError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/copyreg.py/_reduce_ex |
9,871 | def get_info(dynamic=True):
## Date information
date_info = datetime.datetime.now()
date = time.asctime(date_info.timetuple())
revision, version, version_info, vcs_info = None, None, None, None
import_failed = False
dynamic_failed = False
if dynamic:
revision, vcs_info = get_revis... | ImportError | dataset/ETHPy150Open networkx/networkx/networkx/release.py/get_info |
9,872 | def parse_font(font):
""" Parse a CSS3 shorthand font string into an Enaml Font object.
Returns
-------
result : Font or None
A font object representing the parsed font. If the string is
invalid, None will be returned.
"""
token = []
tokens = []
quotechar = None
for... | ValueError | dataset/ETHPy150Open ContinuumIO/ashiba/enaml/enaml/fonts.py/parse_font |
9,873 | def pusher(task_queue, event, broker=None):
"""
Pulls tasks of the broker and puts them in the task queue
:type task_queue: multiprocessing.Queue
:type event: multiprocessing.Event
"""
if not broker:
broker = get_broker()
logger.info(_('{} pushing tasks at {}').format(current_process... | TypeError | dataset/ETHPy150Open Koed00/django-q/django_q/cluster.py/pusher |
9,874 | def worker(task_queue, result_queue, timer, timeout=Conf.TIMEOUT):
"""
Takes a task from the task queue, tries to execute it and puts the result back in the result queue
:type task_queue: multiprocessing.Queue
:type result_queue: multiprocessing.Queue
:type timer: multiprocessing.Value
"""
n... | ValueError | dataset/ETHPy150Open Koed00/django-q/django_q/cluster.py/worker |
9,875 | def build_node_data_bag():
"""Tells LittleChef to build the node data bag"""
current_dir = os.getcwd()
os.chdir(KITCHEN_DIR)
try:
lib.get_recipes() # This builds metadata.json for all recipes
chef.build_node_data_bag()
except __HOLE__ as e:
log.error(e)
finally:
... | SystemExit | dataset/ETHPy150Open edelight/kitchen/kitchen/backends/lchef.py/build_node_data_bag |
9,876 | def _data_loader(data_type, name=None):
"""Loads data from LittleChef's kitchen"""
current_dir = os.getcwd()
os.chdir(KITCHEN_DIR)
try:
func = getattr(lib, "get_" + data_type)
if name:
data = func(name)
else:
data = func()
except __HOLE__ as e:
... | SystemExit | dataset/ETHPy150Open edelight/kitchen/kitchen/backends/lchef.py/_data_loader |
9,877 | def calc(self, input):
try:
lmp_date = datetime.strptime(input["lmp"], "%d-%m-%Y")
edd_date = lmp_date + timedelta(days=280)
return [_("Estimated Date of Delivery: %s") % edd_date.strftime("%d-%m-%Y")]
except __HOLE__:
self._headers = [" ", " "]
... | ValueError | dataset/ETHPy150Open dimagi/commcare-hq/custom/bihar/reports/supervisor.py/EDDCalcReport.calc |
9,878 | def calc(self, input):
try:
weight = float(input["weight"])
height = float(input["height"])
except __HOLE__:
self._headers = [" ", " "]
return [_("Error: We can't parse your input, please try again"), self.form_html]
bmi = weight / (height * heigh... | ValueError | dataset/ETHPy150Open dimagi/commcare-hq/custom/bihar/reports/supervisor.py/BMICalcReport.calc |
9,879 | def exec_command(task, cmd, **kw):
'''
helper function to:
- run a command
- log stderr and stdout into worch_<taskname>.log.txt
- printout the content of that file when the command fails
'''
bld = task.generator.bld
cwd = getattr(task, 'cwd', bld.out_dir)
msg.debug('orch: exec co... | KeyError | dataset/ETHPy150Open hwaf/hwaf/py-hwaftools/orch/wafutil.py/exec_command |
9,880 | def implement(self, m, clock, reset, seq_name='seq', aswire=False):
""" implemente actual registers and operations in Verilog """
mul.reset()
seq = Seq(m, seq_name, clock, reset)
# for mult and div
m._clock = clock
m._reset = reset
try:
dat... | RuntimeError | dataset/ETHPy150Open PyHDI/veriloggen/veriloggen/dataflow/dataflow.py/Dataflow.implement |
9,881 | def getResponse(self, challenge):
directives = self._parse(challenge)
# Compat for implementations that do not send this along with
# a succesful authentication.
if 'rspauth' in directives:
return ''
try:
realm = directives['realm']
except __HOLE... | KeyError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/words/protocols/jabber/sasl_mechanisms.py/DigestMD5.getResponse |
9,882 | def get_requirements():
try:
requirements_file = os.path.join(CURRENT_DIR, 'requirements/main.txt')
with open(requirements_file) as f:
return f.read().splitlines()
except __HOLE__:
# Simple hack for `tox` test.
return [] | IOError | dataset/ETHPy150Open itdxer/neupy/setup.py/get_requirements |
9,883 | def mergeKLists_TLE1(self, lists):
"""
k lists; each list has N items
Algorithm 1:
Merge the lists 1 by 1, just add a loop outside the merge.
Complexity: 2N+3N+4N+..kN = O(k^2 * N)
Algorithm 2:
Group the lists in pairs with every pair having 2 lists, merg... | IndexError | dataset/ETHPy150Open algorhythms/LeetCode/022 Merge k Sorted Lists.py/Solution.mergeKLists_TLE1 |
9,884 | def __init__(self, conf, logger, rcache, devices, zero_byte_only_at_fps=0):
self.conf = conf
self.logger = logger
self.devices = devices
self.diskfile_router = diskfile.DiskFileRouter(conf, self.logger)
self.max_files_per_second = float(conf.get('files_per_second', 20))
s... | SystemExit | dataset/ETHPy150Open openstack/swift/swift/obj/auditor.py/AuditorWorker.__init__ |
9,885 | def _aggregate_multiple_funcs(self, arg, _level):
from pandas.tools.merge import concat
if self.axis != 0:
raise NotImplementedError("axis other than 0 is not supported")
if self._selected_obj.ndim == 1:
obj = self._selected_obj
else:
obj = self._obj... | TypeError | dataset/ETHPy150Open pydata/pandas/pandas/core/base.py/SelectionMixin._aggregate_multiple_funcs |
9,886 | def item(self):
""" return the first element of the underlying data as a python
scalar
"""
try:
return self.values.item()
except __HOLE__:
# copy numpy's message here because Py26 raises an IndexError
raise ValueError('can only convert an array... | IndexError | dataset/ETHPy150Open pydata/pandas/pandas/core/base.py/IndexOpsMixin.item |
9,887 | @deprecate_kwarg('take_last', 'keep', mapping={True: 'last',
False: 'first'})
@Appender(_shared_docs['duplicated'] % _indexops_doc_kwargs)
def duplicated(self, keep='first'):
keys = com._values_from_object(com._ensure_object(self.values))
duplic... | AttributeError | dataset/ETHPy150Open pydata/pandas/pandas/core/base.py/IndexOpsMixin.duplicated |
9,888 | @classmethod
def set_policy_from_env(cls):
envmap = {
"IGNORE": False,
"FALSE": False,
"SAVE": True,
"TRUE": True,
"VERBOSE": "VERBOSE",
"DEFAULT": "VERBOSE",
}
oldvalue = cls.DEFAULT_H5_BACKTRACE_POLICY
envvalue... | KeyError | dataset/ETHPy150Open PyTables/PyTables/tables/exceptions.py/HDF5ExtError.set_policy_from_env |
9,889 | def handle(self, *app_labels, **options):
include_deployment_checks = options['deploy']
if options['list_tags']:
self.stdout.write('\n'.join(sorted(registry.tags_available(include_deployment_checks))))
return
if app_labels:
app_configs = [apps.get_app_config(... | StopIteration | dataset/ETHPy150Open django/django/django/core/management/commands/check.py/Command.handle |
9,890 | def wait_on_children(self):
while self.running:
try:
pid, status = os.wait()
if os.WIFEXITED(status) or os.WIFSIGNALED(status):
self.logger.error(_('Removing dead child %s') % pid)
self.children.remove(pid)
s... | OSError | dataset/ETHPy150Open rcbops/glance-buildpackage/glance/common/wsgi.py/Server.wait_on_children |
9,891 | def wait(self):
"""Wait until all servers have completed running."""
try:
if self.children:
self.wait_on_children()
else:
self.pool.waitall()
except __HOLE__:
pass | KeyboardInterrupt | dataset/ETHPy150Open rcbops/glance-buildpackage/glance/common/wsgi.py/Server.wait |
9,892 | def dispatch(self, obj, action, *args, **kwargs):
"""Find action-specific method on self and call it."""
try:
method = getattr(obj, action)
except __HOLE__:
method = getattr(obj, 'default')
return method(*args, **kwargs) | AttributeError | dataset/ETHPy150Open rcbops/glance-buildpackage/glance/common/wsgi.py/Resource.dispatch |
9,893 | def get_action_args(self, request_environment):
"""Parse dictionary created by routes library."""
try:
args = request_environment['wsgiorg.routing_args'][1].copy()
except Exception:
return {}
try:
del args['controller']
except __HOLE__:
... | KeyError | dataset/ETHPy150Open rcbops/glance-buildpackage/glance/common/wsgi.py/Resource.get_action_args |
9,894 | def _find_incorrect_case(self, included_files):
for (filename, node_and_module) in included_files.items():
base_name = os.path.basename(filename)
try:
candidates = os.listdir(os.path.dirname(filename))
except __HOLE__:
continue
cor... | OSError | dataset/ETHPy150Open myint/cppclean/cpp/find_warnings.py/WarningHunter._find_incorrect_case |
9,895 | def _is_ipv4(self, subnet):
try:
return (netaddr.IPNetwork(subnet.get_cidr()).version == 4)
except __HOLE__:
return False | TypeError | dataset/ETHPy150Open openstack/dragonflow/dragonflow/controller/dhcp_app.py/DHCPApp._is_ipv4 |
9,896 | def get_def_username(request, auth):
# Try to determine the current system user's username to use as a default.
try:
def_username = getpass.getuser().replace(' ', '').lower()
except (__HOLE__, KeyError):
# KeyError will be raised by os.getpwuid() (called by getuser())
# if there is n... | ImportError | dataset/ETHPy150Open quantmind/lux/lux/extensions/odm/commands/create_superuser.py/get_def_username |
9,897 | def run(self, options, interactive=False):
username = options.username
password = options.password
email = options.email
if not username or not password or not email:
interactive = True
request = self.app.wsgi_request()
auth_backend = self.app.auth_backend
... | KeyboardInterrupt | dataset/ETHPy150Open quantmind/lux/lux/extensions/odm/commands/create_superuser.py/Command.run |
9,898 | def ensure_dir(dirname):
"""
Ensure that a named directory exists; if it does not, attempt to create it.
"""
try:
os.makedirs(dirname)
except __HOLE__, e:
if e.errno != errno.EEXIST:
raise | OSError | dataset/ETHPy150Open VisTrails/VisTrails/scripts/dist/windows/update_alps.py/ensure_dir |
9,899 | @patch('sys.stdout', new_callable=StringIO)
@patch('sys.stderr', new_callable=StringIO)
def test_print_help(stderr, stdout):
tool = get_tool('groups')
server = Server('localhost')
try:
status = tool.execute(server, ['groups', '--help'])
except __HOLE__ as e:
status = e.code
eq_(0, st... | SystemExit | dataset/ETHPy150Open bjorns/aem-cmd/tests/tools/test_groups.py/test_print_help |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.