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=result.opponent, opponent=result.player)[0]
except __HOLE__:
continue # this exception happens if result does not have opponent
player_opponent_index = ''.join(unicode(e) for e in sorted([result.player.id, opponent.player.id]))
try:
if results[player_opponent_index]:
continue
except KeyError:
results[player_opponent_index] = {'player': result.player, 'player_result': result.result,
'opponent_result': opponent.result, 'opponent': opponent.player,
'date_added': result.date_added}
ordered_results = {}
i = 0
for key in sorted(results, key=lambda x: (results[x]['date_added']), reverse=True):
ordered_results[i] = results[key]
i += 1
return list(ordered_results.items())
|
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.sanitize_css('''
... background: url(javascript:alert("foo"));
... color: #000;
... ''')
['color: #000']
Also, the proprietary Internet Explorer function ``expression()`` is
always stripped:
>>> sanitizer.sanitize_css('''
... background: #fff;
... color: #000;
... width: e/**/xpression(alert("foo"));
... ''')
['background: #fff', 'color: #000']
:param text: the CSS text; this is expected to be `unicode` and to not
contain any character or numeric references
:return: a list of declarations that are considered safe
:rtype: `list`
:since: version 0.4.3
"""
decls = []
text = self._strip_css_comments(self._replace_unicode_escapes(text))
for decl in text.split(';'):
decl = decl.strip()
if not decl:
continue
try:
propname, value = decl.split(':', 1)
except __HOLE__:
continue
if not self.is_safe_css(propname.strip().lower(), value.strip()):
continue
is_evil = False
if self._EXPRESSION_SEARCH(value):
is_evil = True
for match in self._URL_FINDITER(value):
if not self.is_safe_uri(match.group(1)):
is_evil = True
break
if not is_evil:
decls.append(decl.strip())
return decls
|
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__:
Timing.HZ = 30
self.log.debug("Configuring system Timing for %sHz", Timing.HZ)
Timing.secs_per_tick = 1 / float(Timing.HZ)
Timing.ms_per_tick = 1000 * Timing.secs_per_tick
|
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 be used as the __getitem__() method -- this
# avoids using an additional method call which kills the performance.
|
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 to be retrieved from the log file.
#
if self._loadfile(fileno):
filename = funcname = None
try:
filename, funcname = self._funcmap[(fileno, lineno)]
except KeyError:
filename = self._filemap.get(fileno)
funcname = None
self._funcmap[(fileno, lineno)] = (filename, funcname)
return filename, funcname
|
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))
try:
fp = open(absname)
except IOError:
return
st = parser.suite(fp.read())
fp.close()
# Scan the tree looking for def and lambda nodes, filling in
# self._funcmap with all the available information.
funcdef = symbol.funcdef
lambdef = symbol.lambdef
stack = [st.totuple(1)]
while stack:
tree = stack.pop()
try:
sym = tree[0]
except (IndexError, __HOLE__):
continue
if sym == funcdef:
self._funcmap[(fileno, tree[2][2])] = filename, tree[2][1]
elif sym == lambdef:
self._funcmap[(fileno, tree[1][2])] = filename, "<lambda>"
stack.extend(list(tree[1:]))
|
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. <channel> is only necessary if the message isn't sent in the
channel itself.
"""
try:
(subject, text) = news.split(': ', 1)
except __HOLE__:
raise callbacks.ArgumentError
id = self.db.add(channel, subject, text, at, expires, user.id)
irc.replySuccess(format(_('(News item #%i added)'), id))
|
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]
fileUrl = os.path.dirname(rssItem.url) + '/' + accession[0:10] + '-' + accession[10:12] + '-' + accession[12:] + ".hdr.sgml"
reloadCache = getattr(rssItem.modelXbrl, "reloadCache", False)
elif dts.uri.startswith("http://www.sec.gov/Archives/edgar/data") and dts.uri.endswith(".xml"):
accession = dts.uri.split('/')[-2]
dirPart = os.path.dirname(dts.uri)
if accession.endswith("-xbrl.zip"): # might be an instance document inside a xbrl.zip file
accession = dts.uri.split('/')[-3]
dirPart = os.path.dirname(dirPart)
fileUrl = dirPart + '/' + accession[0:10] + '-' + accession[10:12] + '-' + accession[12:] + ".hdr.sgml"
else:
fileUrl = ''
if fileUrl:
# try to load and use it
normalizedUrl = dts.modelManager.cntlr.webCache.normalizeUrl(fileUrl)
hdrSgml = ''
try:
filePath = dts.modelManager.cntlr.webCache.getfilename(normalizedUrl, reload=reloadCache)
if filePath:
with open(filePath) as fh:
hdrSgml = fh.read()
except (IOError, EnvironmentError) as err:
dts.info("xpDB:headerSgmlDocumentLoadingError",
_("Loading XBRL DB: header SGML document %(file)s loading error: %(error)s"),
modelObject=dts, file=normalizedUrl, error=err)
hdrSgml = ''
record = ''
formerCompanyNumber = 0
for match in re.finditer(r"[<]([^>]+)[>]([^<\n\r]*)", hdrSgml, re.MULTILINE):
tag = match.group(1).lower()
v = match.group(2).replace("<","<").replace(">",">").replace("&","&")
if tag in ('business-address','mail-address'):
record = tag + '.'
elif tag == 'former-company':
formerCompanyNumber += 1
record = "{}-{}.".format(tag, formerCompanyNumber)
elif tag.startswith('/'):
record = ''
elif v:
if tag.endswith("-datetime"):
try:
v = datetime.datetime(_INT(v[0:4]),_INT(v[4:6]),_INT(v[6:8]),_INT(v[8:10]),_INT(v[10:12]),_INT(v[12:14]))
except ValueError:
pass
elif tag.endswith("-date") or tag.startswith("date-of-"):
try:
v = datetime.date(_INT(v[0:4]),_INT(v[4:6]),_INT(v[6:8]))
except ValueError:
pass
elif tag.endswith("-year-end") and len(v) == 4:
v = "{0}-{1}".format(v[0:2],v[2:4])
elif tag in ('assigned-sic',):
try:
v = _INT(v)
except ValueError:
v = None
entityInformation[record + tag] = v
# primary document if no rssItem
if rssItem is None:
# try to sgml txt file
normalizedUrl = normalizedUrl.replace(".hdr.sgml", ".txt")
httpDir = normalizedUrl.rpartition('/')[0]
txtSgml = ''
try:
filePath = dts.modelManager.cntlr.webCache.getfilename(normalizedUrl, reload=reloadCache)
if filePath:
with open(filePath, encoding='utf-8') as fh:
txtSgml = fh.read()
# remove from cache, very large file
os.remove(filePath)
except (IOError, EnvironmentError) as err:
dts.info("xpDB:txtSgmlDocumentLoadingError",
_("Loading XBRL DB: txt SGML document %(file)s loading error: %(error)s"),
modelObject=dts, file=normalizedUrl, error=err)
txtSgml = ''
documentType = documentSequence = None
itemsFound = 0
for match in re.finditer(r"[<]([^>]+)[>]([^<\n\r]*)", txtSgml, re.MULTILINE):
tag = match.group(1).lower()
v = match.group(2).replace("<","<").replace(">",">").replace("&","&")
if tag == 'sequence':
documentSequence = v
elif tag == 'type':
documentType = v
elif tag == 'filename':
if documentType.endswith('.INS') and 'instance-url' not in entityInformation:
entityInformation['instance-url'] = httpDir + '/' + v
documentType = documentSequence = None
itemsFound += 1
if documentSequence == '1':
entityInformation['primary-document-url'] = httpDir + '/' + v
documentType = documentSequence = None
itemsFound += 1
if itemsFound >= 2:
break
del txtSgml # dereference big string
# instance information
for factName, entityField in (("EntityFilerCategory", "filer-category"),
("EntityPublicFloat", "public-float"),
("TradingSymbol", "trading-symbol"),
("DocumentFisalYearFocus", "fiscal-year-focus"),
("DocumentFisalPeriodFocus", "fiscal-period-focus")):
try:
concept = dts.nameConcepts[factName][0] # get qname irrespective of taxonomy year
facts = dts.factsByQname[concept.qname]
for fact in facts:
if not fact.context.qnameDims: #default context
if factName in ("EntityPublicFloat",):
entityInformation[entityField] = roundValue(fact.value, fact.precision, fact.decimals) if fact.isNumeric and not fact.isNil else None
else:
entityInformation[entityField] = fact.value.strip() # may have white space
break
except __HOLE__:
pass
return entityInformation
|
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
configuration for the sources data to be used.
:param data: data in sources file format
:param model: model to load data into. Defaults to :class:`DataSource`
:returns: List of data sources, [:class:`DataSource`]
:raises: :exc:`InvalidData`
"""
if model is None:
model = DataSource
sources = []
for line in data.split('\n'):
line = line.strip()
# ignore empty lines or comments
if not line or line.startswith('#'):
continue
splits = line.split(' ')
if len(splits) < 2:
raise InvalidData("invalid line:\n%s"%(line), origin=origin)
type_ = splits[0]
url = splits[1]
tags = splits[2:]
try:
sources.append(model(type_, url, tags, origin=origin))
except __HOLE__ as e:
raise InvalidData("line:\n\t%s\n%s"%(line, e), origin=origin)
return sources
|
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:
return parse_sources_data(f.read(), origin=filepath)
except __HOLE__ as e:
raise InvalidData("I/O error reading sources file: %s"%(str(e)), origin=filepath)
|
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 isinstance(urls, list) else [urls])
|
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 stored
:raises: :exc:`OSError` if cannot write to cache file/directory
:raises: :exc:`IOError` if cannot write to cache file/directory
"""
if not os.path.exists(source_cache_d):
os.makedirs(source_cache_d)
key_hash = compute_filename_hash(key_filenames)
filepath = os.path.join(source_cache_d, key_hash)
try:
write_atomic(filepath + PICKLE_CACHE_EXT, pickle.dumps(rosdep_data, -1), True)
except __HOLE__ as e:
raise CachePermissionError("Failed to write cache file: " + str(e))
try:
os.unlink(filepath)
except OSError:
pass
return filepath
|
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)
f.close()
try:
# switch file atomically (if supported)
os.rename(filepath_tmp, filepath)
except OSError:
# fall back to non-atomic operation
try:
os.unlink(filepath)
except __HOLE__:
pass
try:
os.rename(filepath_tmp, filepath)
except OSError:
os.unlink(filepath_tmp)
|
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:
module_info = imp.find_module("setup", ["."])
imp.load_module("setup", *module_info)
finally:
os.chdir(cwd)
|
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:
version_string = match.group(1)
versions.append((tuple(map(tryint, version_string.split('.'))),
version_string))
if versions:
versions.sort()
version = versions[-1][-1]
print('Latest version of %s is %s' % (name, version))
else:
raise Exception(
"Could not find the most current version of the %s from the files: %s"
% (name, fns))
except __HOLE__:
# network failure - maybe we have the files already?
latest = (0,0,0)
fns = os.listdir(dest_dir)
for fn in fns:
if fn.startswith(name+'-'):
match = match_libfile_version(fn)
if match:
version_tuple = tuple(map(tryint, match.group(1).split('.')))
if version_tuple > latest:
latest = version_tuple
filename = fn
version = None
if latest == (0,0,0):
raise
if version:
filename = filename % version
full_url = urljoin(location, filename)
dest_filename = os.path.join(dest_dir, filename)
if os.path.exists(dest_filename):
print('Using existing %s downloaded into %s (delete this file if you want to re-download the package)'
% (name, dest_filename))
else:
print('Downloading %s into %s' % (name, dest_filename))
urlretrieve(full_url, dest_filename)
return dest_filename
## Backported method of tarfile.TarFile.extractall (doesn't exist in 2.4):
|
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)
return os.system(' '.join(cmd))
finally:
os.chdir(old_cwd)
cwd = kw.get('cwd', '.')
cmd_desc = ' '.join(cmd)
log.info('Running "%s" in %s' % (cmd_desc, cwd))
returncode = proc_call(cmd, **kw)
if returncode:
raise Exception('Command "%s" returned code %s' % (cmd_desc, returncode))
|
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
try:
stat_result = os.stat(path)
except (__HOLE__, OSError):
logger.error("Caught error from missing cache file")
return False
# File's last modified time.
cache_mtime = stat_result.st_mtime
if cache_mtime < self.start_time:
# This file was modified before the uploader was started.
return False
# Not interested in files past five minutes staleness.
cutoff = time.time() - (60 * 5)
if cache_mtime < cutoff:
# File is too stale to even consider.
return False
last_read = self.cache_file_tracker.get(path)
if not last_read:
# No key found, we need to read this file.
return True
# We've got a key, let's see if the mtimes match.
if cache_mtime > last_read:
# Modified time is greater than the time of our last recorded
# reading of this file.
return True
return False
|
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')
except UnicodeDecodeError:
try:
return chunk.decode('latin-1', 'strict')
except UnicodeDecodeError:
return chunk.decode('ascii', 'ignore')
except __HOLE__:
return unicode(chunk, errors='ignore')
return chunk
|
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 you\'re debugging')
return ''.join((self.safeConvert(c) for c in chunks))
|
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)
if block is not None:
try:
return space.invoke_block(block, [space.newstr_fromstr(path)])
finally:
try:
os.chdir(current_dir)
except OSError as e:
raise error_for_oserror(space, e)
else:
return space.newint(0)
|
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(space, e)
return space.newint(0)
|
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:
return space.newstr_fromstr(filename)
|
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:
self.log.error("%s: %s", url, err)
return
try:
result = json.load(response)
except (TypeError, __HOLE__):
self.log.error("Unable to parse response from elasticsearch as a"
+ " json object")
return
metrics = {}
memory = result['jvm']['memory']
mempool = memory['memory_pool_usages']
jvm = result['jvm']
thread_st = jvm['thread-states']
metrics['jvm.memory.totalInit'] = memory['totalInit']
metrics['jvm.memory.totalUsed'] = memory['totalUsed']
metrics['jvm.memory.totalMax'] = memory['totalMax']
metrics['jvm.memory.totalCommitted'] = memory['totalCommitted']
metrics['jvm.memory.heapInit'] = memory['heapInit']
metrics['jvm.memory.heapUsed'] = memory['heapUsed']
metrics['jvm.memory.heapMax'] = memory['heapMax']
metrics['jvm.memory.heapCommitted'] = memory['heapCommitted']
metrics['jvm.memory.heap_usage'] = memory['heap_usage']
metrics['jvm.memory.non_heap_usage'] = memory['non_heap_usage']
metrics['jvm.memory.code_cache'] = mempool['Code Cache']
metrics['jvm.memory.eden_space'] = mempool['PS Eden Space']
metrics['jvm.memory.old_gen'] = mempool['PS Old Gen']
metrics['jvm.memory.perm_gen'] = mempool['PS Perm Gen']
metrics['jvm.memory.survivor_space'] = mempool['PS Survivor Space']
metrics['jvm.daemon_thread_count'] = jvm['daemon_thread_count']
metrics['jvm.thread_count'] = jvm['thread_count']
metrics['jvm.fd_usage'] = jvm['fd_usage']
metrics['jvm.thread_states.timed_waiting'] = thread_st['timed_waiting']
metrics['jvm.thread_states.runnable'] = thread_st['runnable']
metrics['jvm.thread_states.blocked'] = thread_st['blocked']
metrics['jvm.thread_states.waiting'] = thread_st['waiting']
metrics['jvm.thread_states.new'] = thread_st['new']
metrics['jvm.thread_states.terminated'] = thread_st['terminated']
for key in metrics:
self.publish(key, metrics[key])
|
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", being "qemu" the preferred one. Qemu only supports "qemu".
:param is_block_dev:
:returns: driver_name or None
"""
if CONF.libvirt.virt_type == "xen":
if is_block_dev:
return "phy"
else:
# 4002000 == 4.2.0
if hypervisor_version >= 4002000:
try:
execute('xend', 'status',
run_as_root=True, check_exit_code=True)
except __HOLE__ as exc:
if exc.errno == errno.ENOENT:
LOG.debug("xend is not found")
# libvirt will try to use libxl toolstack
return 'qemu'
else:
raise
except processutils.ProcessExecutionError:
LOG.debug("xend is not started")
# libvirt will try to use libxl toolstack
return 'qemu'
# libvirt will use xend/xm toolstack
try:
out, err = execute('tap-ctl', 'check', check_exit_code=False)
if out == 'ok\n':
# 4000000 == 4.0.0
if hypervisor_version > 4000000:
return "tap2"
else:
return "tap"
else:
LOG.info(_LI("tap-ctl check: %s"), out)
except OSError as exc:
if exc.errno == errno.ENOENT:
LOG.debug("tap-ctl tool is not installed")
else:
raise
return "file"
elif CONF.libvirt.virt_type in ('kvm', 'qemu'):
return "qemu"
else:
# UML doesn't want a driver_name set
return None
|
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 processutils.ProcessExecutionError:
return False
except __HOLE__ as exc:
# info since it's not required to have this tool.
if exc.errno == errno.ENOENT:
LOG.info(_LI("findmnt tool is not installed"))
return False
|
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")
c = cls.__new__(cls, object)
components = col_str[1:3], col_str[3:5], col_str[5:6]
try:
c._c = [ int(s, 16) / 255.0 for s in components ] + [ a ]
except __HOLE__:
raise ValueError \
("Components should be encoded as two hex characters")
|
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.
"""
p = (ESPaginator if isinstance(queryset, search.ES)
else paginator.Paginator)(queryset, per_page)
if count is not None:
p._count = count
# Get the page from the request, make sure it's an int.
try:
page = int(request.GET.get('page', 1))
except __HOLE__:
page = 1
# Get a page of results, or the first page if there's a problem.
try:
paginated = p.page(page)
except (paginator.EmptyPage, paginator.InvalidPage):
paginated = p.page(1)
paginated.url = u'%s?%s' % (request.path, request.GET.urlencode())
return paginated
|
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 the namespace simply requires
editing that key. Your application will no longer request the old keys,
and they will eventually fall off the end of the LRU and be reclaimed.
"""
ns_key = 'ns:%s' % namespace
if increment:
try:
ns_val = cache.incr(ns_key)
except __HOLE__:
log.info('Cache increment failed for key: %s. Resetting.' % ns_key)
ns_val = epoch(datetime.datetime.now())
cache.set(ns_key, ns_val, None)
else:
ns_val = cache.get(ns_key)
if ns_val is None:
ns_val = epoch(datetime.datetime.now())
cache.set(ns_key, ns_val, None)
return '%s:%s' % (ns_val, ns_key)
|
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 == errno.EEXIST and os.path.isdir(parent):
pass
else:
raise
return super(LocalFileStorage, self)._open(name, mode=mode)
|
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): %s: %s'
log.error(msg % (enc_guess['encoding'],
enc_guess['confidence'] * 100.0,
exc.__class__.__name__, exc))
return unicode(s, errors='replace')
|
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 *did* exist in {0}: {1}".format(path_dir, os.listdir(path_dir))
]
self.fail("\n".join(msg))
|
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().delete_by_query(**delete_query)
# Since delete_by_query cannot tell if teh delete actually happened check with a get call
# if the trigger was deleted. Unfortuantely, this opens up to races on delete.
confirmed_delete = False
try:
cls.get_by_id(model_object.id)
except __HOLE__:
confirmed_delete = True
# Publish internal event on the message bus
if confirmed_delete and publish:
try:
cls.publish_delete(model_object)
except Exception:
LOG.exception('Publish failed.')
# Dispatch trigger
if confirmed_delete and dispatch_trigger:
try:
cls.dispatch_delete_trigger(model_object)
except Exception:
LOG.exception('Trigger dispatch failed.')
return model_object
|
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 (!!!)
"""
if not self.__host:
# Initial connection used for authentication
conn = self.conn_classes[self.secure](self.auth_host, self.port[self.secure])
conn.request(method='GET', url='/%s' % self.api_version,
headers={'X-Auth-User': self.user_id,
'X-Auth-Key': self.key})
resp = conn.getresponse()
headers = dict(resp.getheaders())
try:
self.token = headers['x-auth-token']
endpoint = headers['x-server-management-url']
except __HOLE__:
raise InvalidCredsException()
scheme, server, self.path, param, query, fragment = (
urlparse.urlparse(endpoint)
)
if scheme is "https" and self.secure is not 1:
# TODO: Custom exception (?)
raise InvalidCredsException()
# Set host to where we want to make further requests to; close auth conn
self.__host = server
conn.close()
return self.__host
|
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
# mechanism is way to magical and depends on the import order et al, so
# all of this really needs to be revisited.
if not self.loaded:
for app in settings.INSTALLED_APPS:
provider_module = app + '.provider'
try:
importlib.import_module(provider_module)
except __HOLE__:
pass
self.loaded = True
|
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.path.join(options.get('parent_path') or project_dir, app_name)
dia_path = options.get('dia_path') or os.path.join(project_dir, '%s.dia' % app_name)
if not os.path.exists(app_template):
raise CommandError("The template path, %r, does not exist." % app_template)
if not re.search(r'^\w+$', label):
raise CommandError("%r is not a valid application name. Please use only numbers, letters and underscores." % label)
dia_parse = options.get('dia_path') or options.get('dia_parse')
if dia_parse:
if not os.path.exists(dia_path):
raise CommandError("The diagram path, %r, does not exist." % dia_path)
if app_name in settings.INSTALLED_APPS:
raise CommandError("The application %s should not be defined in the settings file. Please remove %s now, and add it after using this command." % (app_name, app_name))
tables = [name for name in connection.introspection.table_names() if name.startswith('%s_' % app_name)]
if tables:
raise CommandError("%r application has tables in the database. Please delete them." % app_name)
try:
os.makedirs(app_dir)
except __HOLE__ as e:
raise CommandError(e)
copy_template(app_template, app_dir, project_name, app_name)
if dia_parse:
generate_models_and_admin(dia_path, app_dir, project_name, app_name)
print("Application %r created." % app_name)
print("Please add now %r and any other dependent application in settings.INSTALLED_APPS, and run 'manage syncdb'" % app_name)
|
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
for d, subdirs, files in os.walk(app_template):
relative_dir = d[len(app_template) + 1:]
d_new = os.path.join(copy_to, relative_dir).replace('app_name', app_name)
if relative_dir and not os.path.exists(d_new):
os.mkdir(d_new)
for i, subdir in enumerate(subdirs):
if subdir.startswith('.'):
del subdirs[i]
elif subdir.startswith('migrations') and not copy_migrations:
del subdirs[i]
replacements = {'app_name': app_name, 'project_name': project_name}
replacements.update(REPLACEMENTS)
for f in files:
if f.endswith('.pyc') or f.startswith('.DS_Store'):
continue
path_old = os.path.join(d, f)
path_new = os.path.join(d_new, f.replace('app_name', app_name))
if os.path.exists(path_new):
path_new = os.path.join(d_new, f)
if os.path.exists(path_new):
continue
if path_new.endswith('.tmpl'):
path_new = path_new[:-5]
fp_old = open(path_old, 'r')
fp_new = open(path_new, 'w')
fp_new.write(Template(fp_old.read()).render(Context(replacements)))
fp_old.close()
fp_new.close()
try:
shutil.copymode(path_old, path_new)
_make_writeable(path_new)
except __HOLE__:
sys.stderr.write("Notice: Couldn't set permission bits on %s. You're probably using an uncommon filesystem setup. No problem.\n" % path_new)
|
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.server in ready:
print('client connection')
self.client, addr = self.server.accept()
sockets = [self.client]
self.cmd('1', 'create')
for line in self.preload:
self.send(line)
else:
continue
elif self.client in ready:
# we're willing to wait up to 1/120 of a second
# for a delete following an erase
# this and a big buffer prevent flickering.
data = self.client.recv(102400).decode('utf8')
if 'remove' in data and not 'insert' in data:
more, _, _ = select.select([self.client], [], [], 1.0 / 120)
if more:
data += self.client.recv(102400).decode('utf8')
# print('data:', data)
if data:
self.handle(data)
else:
break
except socket.error:
pass
finally:
self.close(disconnect=True)
|
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)
self.row, self.col = int(row), int(col)
self.mode, vs, rest = rest.split(',', 2)
a, b = vs.split('+', 1)
self.modified = (rest == '+')
self.visual = (int(a), int(b))
# print(self.status)
except __HOLE__:
pass
if self.monitor:
with Edit(self.monitor) as edit:
if dirty:
edit.erase(sublime.Region(0, self.monitor.size()))
edit.insert(0, data)
edit.reselect(
lambda view: view.text_point(v.row - 1, v.col - 1))
def update_cursor(view, edit):
row, col = (self.row - 1, self.col + 1)
# see if it's prompting for input
if v.row == self.rows and v.col > 0:
char = v.buf[v.row - 1][0]
if char in ':/':
row, col = (v.row - 1, v.col - 1)
pos = view.text_point(row, col)
sel = sublime.Region(pos, pos)
view.add_regions(
'cursor', [sel], 'comment',
'', sublime.DRAW_EMPTY,
)
if moved:
edit.callback(update_cursor)
if self.update_callback:
self.update_callback(self, dirty, moved)
|
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", logging.WARN)
try:
root_logger.setLevel(log_level)
except __HOLE__:
root_logger.setLevel(logging.DEBUG)
root_logger.debug("unknown log level '%s'; DEBUG will be used instead" % log_level)
log_level = logging.DEBUG
self.log = logging.getLogger(type(self).__name__)
self.log.setLevel(log_level)
self.log.addHandler(handler)
self.log.propagate = False
|
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 ValueError("Invalid parameter string.")
try:
key = params['oauth_token'][0]
except Exception:
raise ValueError("'oauth_token' not found in OAuth request.")
try:
secret = params['oauth_token_secret'][0]
except Exception:
raise ValueError("'oauth_token_secret' not found in "
"OAuth request.")
token = Token(key, secret)
try:
token.callback_confirmed = params['oauth_callback_confirmed'][0]
except __HOLE__:
pass # 1.0, no callback confirmed.
return token
|
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 = hmac.new(key, raw, sha)
# Calculate the digest base 64.
return binascii.b2a_base64(hashed.digest())[:-1]
|
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" list but not in the
"expected" list. Duplicate elements in either input list are ignored.
"""
i = j = 0
missing = []
unexpected = []
while True:
try:
e = expected[i]
a = actual[j]
if e < a:
missing.append(e)
i += 1
while expected[i] == e:
i += 1
elif e > a:
unexpected.append(a)
j += 1
while actual[j] == a:
j += 1
else:
i += 1
try:
while expected[i] == e:
i += 1
finally:
j += 1
while actual[j] == a:
j += 1
except __HOLE__:
missing.extend(expected[i:])
unexpected.extend(actual[j:])
break
return missing, unexpected
|
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:
actual.remove(item)
except __HOLE__:
missing.append(item)
# anything left in actual is unexpected
return missing, actual
|
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.basename(path))
try:
data = urllib2.urlopen(default_uri + '/' + 'test').read()
if data == path:
return default_uri
except __HOLE__, e:
pass
logger.warning("default webserver at %s not available", DEFAULT_WEB_PORT)
LocalizedHTTP.basedir = os.path.dirname(path)
ss = SocketServer.TCPServer(('0.0.0.0', 0), LocalizedHTTP)
spawn(ss.serve_forever)
uri = "http://%s:%d/%s" % (socket.gethostname(), ss.server_address[1],
os.path.basename(path))
return uri
|
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 = f.readline()
if not line: break
buf.append(line)
if line.endswith('\n'):
send(buf)
buf = []
except __HOLE__:
break
if buf:
send(buf)
if out[0]:
out[0].close()
f.close()
ctx.shutdown()
|
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).wait()
os.killpg(ppid, signal.SIGKILL) # kill workers
except Exception, e:
pass # make sure to exit
finally:
for d in workdir:
while os.path.exists(d):
try: shutil.rmtree(d, True)
except: pass
os._exit(0)
os.wait()
|
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_workers.items():
task_id = task.task_id
try:
pid = pool._pool[0].pid
p = psutil.Process(pid)
rss = p.memory_info().rss >> 20
except Exception, e:
logger.error("worker process %d of task %s is dead: %s", pid, tid, e)
reply_status(driver, task_id, mesos_pb2.TASK_LOST)
self.busy_workers.pop(tid)
continue
if p.status == psutil.STATUS_ZOMBIE or not p.is_running():
logger.error("worker process %d of task %s is zombie", pid, tid)
reply_status(driver, task_id, mesos_pb2.TASK_LOST)
self.busy_workers.pop(tid)
continue
offered = get_task_memory(task)
if not offered:
continue
if rss > offered * 1.5:
logger.warning("task %s used too much memory: %dMB > %dMB * 1.5, kill it. "
+ "use -M argument or taskMemory to request more memory.", tid, rss, offered)
reply_status(driver, task_id, mesos_pb2.TASK_KILLED)
self.busy_workers.pop(tid)
pool.terminate()
elif rss > offered * mem_limit.get(tid, 1.0):
logger.debug("task %s used too much memory: %dMB > %dMB, "
+ "use -M to request or taskMemory for more memory", tid, rss, offered)
mem_limit[tid] = rss / offered + 0.1
now = time.time()
n = len([1 for t, p in self.idle_workers if t + MAX_WORKER_IDLE_TIME < now])
if n:
for _, p in self.idle_workers[:n]:
p.terminate()
self.idle_workers = self.idle_workers[n:]
if self.busy_workers or self.idle_workers:
idle_since = now
elif idle_since + MAX_EXECUTOR_IDLE_TIME < now:
os._exit(0)
self.lock.release()
time.sleep(1)
|
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_link_id)
link.ignore = True
link.save()
if request.is_ajax():
json_data = json.dumps({'link': ignore_link_id})
return HttpResponse(json_data, content_type='application/javascript')
unignore_link_id = request.GET.get('unignore', None)
if unignore_link_id != None:
link = Link.objects.get(id=unignore_link_id)
link.ignore = False
link.save()
if request.is_ajax():
json_data = json.dumps({'link': unignore_link_id})
return HttpResponse(json_data, content_type='application/javascript')
recheck_link_id = request.GET.get('recheck', None)
if recheck_link_id is not None:
link = Link.objects.get(id=recheck_link_id)
url = link.url
url.check_url(external_recheck_interval=0)
links = [x[0] for x in url.links.values_list('id')]
if request.is_ajax():
json_data = json.dumps({
'links': links,
'message': url.message,
'colour': url.colour,
})
return HttpResponse(json_data, content_type='application/javascript')
link_filter = request.GET.get('filters', 'show_invalid')
if link_filter == 'show_valid':
qset = Link.objects.filter(ignore=False, url__status__exact=True)
report_type = 'Good Links'
elif link_filter == 'show_unchecked':
qset = Link.objects.filter(ignore=False, url__last_checked__exact=None)
report_type = 'Untested Links'
elif link_filter == 'ignored':
qset = Link.objects.filter(ignore=True)
report_type = 'Ignored Links'
else:
qset = Link.objects.filter(ignore=False, url__status__exact=False)
report_type = 'Broken Links'
paginated_links = Paginator(qset, RESULTS_PER_PAGE, 0, True)
try:
page = int(request.GET.get('page', '1'))
except:
page = 0
# offset = (page - 1) * RESULTS_PER_PAGE
links = paginated_links.page(page)
# This code groups links into nested lists by content type and object id
# It's a bit nasty but we can't use groupby unless be get values()
# instead of a queryset because of the 'Object is not subscriptable' error
t = sorted(links.object_list.values(), key=outerkeyfunc)
for tk, tg in groupby(t, outerkeyfunc):
innerkeyfunc = itemgetter('object_id')
objects = []
tg = sorted(tg, key=innerkeyfunc)
for ok, og in groupby(tg, innerkeyfunc):
content_type = ContentType.objects.get(pk=tk)
og = list(og)
try:
object = None
if content_type.model_class():
object = content_type.model_class().objects.get(pk=ok)
except ObjectDoesNotExist:
pass
try:
admin_url = object.get_admin_url()
except __HOLE__:
try:
admin_url = reverse('admin:%s_%s_change' % (content_type.app_label, content_type.model), args=[ok])
except NoReverseMatch:
admin_url = None
objects.append({
'object': object,
'link_list': Link.objects.in_bulk([x['id'] for x in og]).values(), # Convert values_list back to queryset. Do we need to get values() or do we just need a list of ids?
'admin_url': admin_url,
})
content_types_list.append({
'content_type': content_type,
'object_list': objects
})
# Pass any querystring data back to the form minus page
rqst = request.GET.copy()
if 'page' in rqst:
del rqst['page']
return render(request, 'linkcheck/report.html', {
'content_types_list': content_types_list,
'pages': links,
'filter': link_filter,
'media': forms.Media(js=[static('admin/js/jquery.min.js')]),
'qry_data': rqst.urlencode(),
'report_type': report_type,
'ignored_count': Link.objects.filter(ignore=True).count(),
},
)
|
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:
# display as a Error message and return without doing anything
message_box = QtGui.QMessageBox(self)
message_box.critical(
self,
"Error",
str(e),
QtGui.QMessageBox.Ok
)
return
# close the interface
self.close()
|
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.__class__:
raise TypeError("can't pickle %s objects" % base.__name__)
state = base(self)
args = (self.__class__, base, state)
try:
getstate = self.__getstate__
except AttributeError:
if getattr(self, "__slots__", None):
raise TypeError("a class that defines __slots__ without "
"defining __getstate__ cannot be pickled")
try:
dict = self.__dict__
except __HOLE__:
dict = None
else:
dict = getstate()
if dict:
return _reconstructor, args, dict
else:
return _reconstructor, args
# Helper for __reduce_ex__ protocol 2
|
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_revision()
if revision is None:
dynamic_failed = True
if dynamic_failed or not dynamic:
# This is where most final releases of NetworkX will be.
# All info should come from version.py. If it does not exist, then
# no vcs information will be provided.
sys.path.insert(0, basedir)
try:
from version import date, date_info, version, version_info, vcs_info
except __HOLE__:
import_failed = True
vcs_info = (None, (None, None))
else:
revision = vcs_info[1][0]
del sys.path[0]
if import_failed or (dynamic and not dynamic_failed):
# We are here if:
# we failed to determine static versioning info, or
# we successfully obtained dynamic revision info
version = ''.join([str(major), '.', str(minor)])
if dev:
version += '.dev_' + date_info.strftime("%Y%m%d%H%M%S")
version_info = (name, major, minor, revision)
return date, date_info, version, version_info, vcs_info
## Version information
|
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 char in font:
if quotechar is not None:
if char == quotechar:
tokens.append(''.join(token))
token = []
quotechar = None
else:
token.append(char)
elif char == '"' or char == "'":
quotechar = char
elif char in ' \t':
if token:
tokens.append(''.join(token))
token = []
else:
token.append(char)
# Failed to close quoted string.
if quotechar is not None:
return
if token:
tokens.append(''.join(token))
sizes = []
families = []
optionals = []
for token in tokens:
if token in _STYLES or token in _VARIANTS or token in _WEIGHTS:
if len(sizes) > 0 or len(families) > 0:
return None
optionals.append(token)
elif token in _SIZES or token[-2:] in _UNITS:
if len(families) > 0:
return None
sizes.append(token)
else:
families.append(token)
if len(optionals) > 3:
return None
if len(sizes) != 1:
return None
if len(families) != 1:
return None
style = None
variant = None
weight = None
for opt in optionals:
if opt == 'normal':
continue
elif opt in _STYLES:
if style is not None:
return None
style = opt
elif opt in _VARIANTS:
if variant is not None:
return None
variant = opt
elif opt in _WEIGHTS:
if weight is not None:
return None
weight = opt
else:
return None
size = sizes[0]
if size in _SIZES:
size = _SIZES[size]
else:
sizenum, units = size[:-2], size[-2:]
try:
sizenum = float(sizenum)
except __HOLE__:
return None
size = _UNITS[units](sizenum)
family = str(families[0])
weight = _WEIGHTS[weight] if weight else _WEIGHTS['normal']
style = _STYLES[style] if style else _STYLES['normal']
variant = _VARIANTS[variant] if variant else _VARIANTS['normal']
return Font(family, size, weight, style, variant)
|
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().name, current_process().pid))
while True:
try:
task_set = broker.dequeue()
except Exception as e:
logger.error(e)
# broker probably crashed. Let the sentinel handle it.
sleep(10)
break
if task_set:
for task in task_set:
ack_id = task[0]
# unpack the task
try:
task = signing.SignedPackage.loads(task[1])
except (__HOLE__, signing.BadSignature) as e:
logger.error(e)
broker.fail(ack_id)
continue
task['ack_id'] = ack_id
task_queue.put(task)
logger.debug(_('queueing from {}').format(broker.list_key))
if event.is_set():
break
logger.info(_("{} stopped pushing tasks").format(current_process().name))
|
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
"""
name = current_process().name
logger.info(_('{} ready for work at {}').format(name, current_process().pid))
task_count = 0
# Start reading the task queue
for task in iter(task_queue.get, 'STOP'):
result = None
timer.value = -1 # Idle
task_count += 1
# Get the function from the task
logger.info(_('{} processing [{}]').format(name, task['name']))
f = task['func']
# if it's not an instance try to get it from the string
if not callable(task['func']):
try:
module, func = f.rsplit('.', 1)
m = importlib.import_module(module)
f = getattr(m, func)
except (__HOLE__, ImportError, AttributeError) as e:
result = (e, False)
if rollbar:
rollbar.report_exc_info()
# We're still going
if not result:
db.close_old_connections()
# execute the payload
timer.value = task['kwargs'].pop('timeout', timeout or 0) # Busy
try:
res = f(*task['args'], **task['kwargs'])
result = (res, True)
except Exception as e:
result = ('{}'.format(e), False)
if rollbar:
rollbar.report_exc_info()
# Process result
task['result'] = result[0]
task['success'] = result[1]
task['stopped'] = timezone.now()
result_queue.put(task)
timer.value = -1 # Idle
# Recycle
if task_count == Conf.RECYCLE:
timer.value = -2 # Recycled
break
logger.info(_('{} stopped doing work').format(name))
|
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:
os.chdir(current_dir)
return True
|
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:
log.error(e)
raise RepoError('Error while loading {0} files. Possibly a JSON '
'syntax error'.format(data_type))
else:
return data
finally:
os.chdir(current_dir)
|
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 = [" ", " "]
return [_("Error: We can't parse your input, please try again"), self.form_html]
|
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 * height)
if bmi >= 30:
return [_("You are obese")]
elif bmi >= 25:
return [_("You are overweight")]
elif bmi >= 18.5:
return [_("You are normal weight")]
else:
return [_("You are underweight")]
|
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 command: %s: "%s" in %s' % (task.name, cmd, cwd))
if not osp.exists(cwd):
os.makedirs(cwd)
log_dir = bld.root.make_node(osp.join(bld.out_dir, 'logs'))
log_dir.mkdir()
fnode = log_dir.make_node('worch_%s.log.txt' % task.name)
flog = open(fnode.abspath(), 'w')
cmd_dict = dict(kw)
env = kw.get('env', task.env.env)
cmd_dict.update({
'cwd': cwd,
'env': env,
'stdout': flog,
'stderr': flog,
})
try:
pdict = bld.env['orch_package_dict'][task.name.split('_',1)[0]]
except __HOLE__:
pdict = dict()
flog.write('WORCH CMD: %s\n' % cmd)
flog.write('WORCH CWD: %s\n' % cwd)
flog.write('WORCH TSK: %s\n' % str(task))
flog.write(pprint.pformat(task.__dict__, indent=2, depth=2))
flog.write('\n')
if pdict:
flog.write('WORCH PKG:\n')
flog.write(pprint.pformat(pdict, indent=2, depth=2))
flog.write('\nWORCH ENV:\n\t%s' % \
'\n\t'.join(['%s = %s' % kv for kv in sorted(env.items())]))
flog.write('\nWORCH command output:\n')
flog.flush()
try:
ret = task.exec_command(cmd, **cmd_dict)
except KeyboardInterrupt:
raise
except WafError:
msg.error('Command failed with WafError: %s in %s' % (cmd, cwd))
raise
finally:
flog.close()
if msg.verbose and ret == 0 and 'orchstep' in msg.zones:
with open(flog.abspath()) as f:
msg.pprint('NORMAL','orchstep: %s (%s)\n%s' % \
(task.name, flog.name, ''.join(f.readlines())))
pass
pass
if ret == 0:
return 0
msg.error('command failed with code %s, log in %s' % (ret, flog.name))
repo = osp.join(cwd, "worch_%s.repo.sh" % task.name)
with open(repo, 'w') as fp:
fp.write('#!/bin/bash\n')
fp.write('cd %s\n' % cwd)
for var, val in sorted(env.items()):
if val.startswith('()'):
fp.write('%s %s\n' % (var, val))
else:
fp.write('export %s="%s"\n' % (var,val))
fp.write('\n\n%s\n' % cmd)
msg.error('reproduce with: %s' % repo)
return ret
|
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:
dataflow_nodes = copy.deepcopy(self.nodes)
except __HOLE__:
dataflow_nodes = self.nodes
limit = sys.getrecursionlimit()
print("Warning: Current dataflow definitions are not copied.", file=sys.stderr)
print(" If object backup is required, enlarge maximum recursion depth"
" by 'sys.setrecursionlimit(v)'.")
print(" Current maximum depth is %d." % limit, file=sys.stderr)
input_visitor = visitor.InputVisitor()
input_vars = set()
for node in sorted(dataflow_nodes, key=lambda x:x.object_id):
input_vars.update( input_visitor.visit(node) )
output_visitor = visitor.OutputVisitor()
output_vars = set()
for node in sorted(dataflow_nodes, key=lambda x:x.object_id):
output_vars.update( output_visitor.visit(node) )
# add input ports
for input_var in sorted(input_vars, key=lambda x:x.object_id):
input_var._implement_input(m, seq)
# schedule
sched = scheduler.ASAPScheduler()
sched.schedule(output_vars)
# balance output stage depth
max_stage = None
for output_var in sorted(output_vars, key=lambda x:x.object_id):
max_stage = dtypes._max(max_stage, output_var.end_stage)
self.max_stage = max_stage
output_vars = sched.balance_output(output_vars, max_stage)
# get all vars
all_visitor = visitor.AllVisitor()
all_vars = set()
for output_var in sorted(output_vars, key=lambda x:x.object_id):
all_vars.update( all_visitor.visit(output_var) )
# allocate (implement signals)
alloc = allocator.Allocator()
alloc.allocate(m, seq, all_vars)
# add output ports
for output_var in sorted(output_vars, key=lambda x:x.object_id):
output_var._implement_output(m, seq)
# add always statement
seq.make_always()
# save schedule result
self.last_result = output_vars
return m
#---------------------------------------------------------------------------
|
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__:
realm = self.defaultRealm
return self._gen_response(directives['charset'],
realm,
directives['nonce'])
|
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, merge two, then repeat again
Complexity:
T(N) = (k/2)*2N+(k/4)*4N..+(k/2^r)*2^r*N
T(N) = O(lg k * k * N)
:param lists: a list of ListNode
:return: ListNode
"""
lists = filter(lambda x: x is not None, lists)
if not lists:
return
length = len(lists)
factor = 2
while length>0:
i = 0
while True:
try:
lists[i] = self.mergeTwoLists(lists[i], lists[i+factor/2])
except __HOLE__:
break
i += factor
length /= 2
factor *= 2
return lists[0]
|
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))
self.max_bytes_per_second = float(conf.get('bytes_per_second',
10000000))
try:
# ideally unless ops overrides the rsync_tempfile_timeout in the
# auditor section we can base our behavior on whatever they
# configure for their replicator
replicator_config = readconf(self.conf['__file__'],
'object-replicator')
except (KeyError, __HOLE__):
# if we can't parse the real config (generally a KeyError on
# __file__, or SystemExit on no object-replicator section) we use
# a very conservative default
default = 86400
else:
replicator_rsync_timeout = int(replicator_config.get(
'rsync_timeout', replicator.DEFAULT_RSYNC_TIMEOUT))
# Here we can do some light math for ops and use the *replicator's*
# rsync_timeout (plus 15 mins to avoid deleting local tempfiles
# before the remote replicator kills it's rsync)
default = replicator_rsync_timeout + 900
self.rsync_tempfile_timeout = config_auto_int_value(
self.conf.get('rsync_tempfile_timeout'), default)
self.auditor_type = 'ALL'
self.zero_byte_only_at_fps = zero_byte_only_at_fps
if self.zero_byte_only_at_fps:
self.max_files_per_second = float(self.zero_byte_only_at_fps)
self.auditor_type = 'ZBF'
self.log_time = int(conf.get('log_time', 3600))
self.last_logged = 0
self.files_running_time = 0
self.bytes_running_time = 0
self.bytes_processed = 0
self.total_bytes_processed = 0
self.total_files_processed = 0
self.passes = 0
self.quarantines = 0
self.errors = 0
self.rcache = rcache
self.stats_sizes = sorted(
[int(s) for s in list_from_csv(conf.get('object_size_stats'))])
self.stats_buckets = dict(
[(s, 0) for s in self.stats_sizes + ['OVER']])
|
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_with_exclusions
results = []
keys = []
# degenerate case
if obj.ndim == 1:
for a in arg:
try:
colg = self._gotitem(obj.name, ndim=1, subset=obj)
results.append(colg.aggregate(a))
# make sure we find a good name
name = com._get_callable_name(a) or a
keys.append(name)
except (__HOLE__, DataError):
pass
except SpecificationError:
raise
# multiples
else:
for col in obj:
try:
colg = self._gotitem(col, ndim=1, subset=obj[col])
results.append(colg.aggregate(arg))
keys.append(col)
except (TypeError, DataError):
pass
except SpecificationError:
raise
return concat(results, keys=keys, axis=1)
|
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 of size 1 to a '
'Python scalar')
|
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))
duplicated = lib.duplicated(keys, keep=keep)
try:
return self._constructor(duplicated,
index=self.index).__finalize__(self)
except __HOLE__:
return np.array(duplicated, dtype=bool)
# ----------------------------------------------------------------------
# abstracts
|
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 = os.environ.get("PT_DEFAULT_H5_BACKTRACE_POLICY", "DEFAULT")
try:
newvalue = envmap[envvalue.upper()]
except __HOLE__:
warnings.warn("Invalid value for the environment variable "
"'PT_DEFAULT_H5_BACKTRACE_POLICY'. The default "
"policy for HDF5 back trace management in PyTables "
"will be: '%s'" % oldvalue)
else:
cls.DEFAULT_H5_BACKTRACE_POLICY = newvalue
return oldvalue
|
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(app_label) for app_label in app_labels]
else:
app_configs = None
tags = options['tags']
if tags:
try:
invalid_tag = next(
tag for tag in tags if not checks.tag_exists(tag, include_deployment_checks)
)
except __HOLE__:
# no invalid tags
pass
else:
raise CommandError('There is no system check with the "%s" tag.' % invalid_tag)
self.check(
app_configs=app_configs,
tags=tags,
display_num_errors=True,
include_deployment_checks=include_deployment_checks,
fail_level=getattr(checks, options['fail_level']),
)
|
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)
self.run_child()
except __HOLE__, err:
if err.errno not in (errno.EINTR, errno.ECHILD):
raise
except KeyboardInterrupt:
sys.exit(1)
self.logger.info(_('Caught keyboard interrupt. Exiting.'))
break
eventlet.greenio.shutdown_safe(self.sock)
self.sock.close()
self.logger.debug(_('Exited'))
|
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__:
pass
try:
del args['format']
except KeyError:
pass
return args
|
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
correct_filename = get_correct_include_filename(base_name,
candidates)
if correct_filename:
self._add_warning(
"'{}' should be '{}'".format(base_name, correct_filename),
node_and_module[0])
|
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 no corresponding entry in the /etc/passwd file
# (a very restricted chroot environment, for example).
def_username = ''
# Determine whether the default username is taken, so we don't display
# it as an option.
if def_username:
user = auth.get_user(request, username=def_username)
if user:
def_username = ''
return def_username
|
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
if interactive: # pragma nocover
def_username = get_def_username(request, auth_backend)
input_msg = 'Username'
if def_username:
input_msg += ' (Leave blank to use %s)' % def_username
username = None
email = None
password = None
try:
# Get a username
while not username:
username = input(input_msg + ': ')
if def_username and username == '':
username = def_username
if not RE_VALID_USERNAME.match(username):
self.write_err('Error: That username is invalid. Use '
'only letters, digits and underscores.')
username = None
else:
user = auth_backend.get_user(request,
username=username)
if user is not None:
self.write_err(
"Error: That username is already taken.\n")
username = None
while not email:
email = input('Email: ')
try:
email = normalise_email(email)
except Exception:
self.write_err('Error: That email is invalid.')
email = None
else:
user = auth_backend.get_user(request, email=email)
if user is not None:
self.write_err(
"Error: That email is already taken.")
email = None
# Get a password
while 1:
if not password:
password = getpass.getpass()
password2 = getpass.getpass('Password (again): ')
if password != password2:
self.write_err(
"Error: Your passwords didn't match.")
password = None
continue
if password.strip() == '':
self.write_err(
"Error: Blank passwords aren't allowed.")
password = None
continue
break
except __HOLE__:
self.write_err('\nOperation cancelled.')
return
user = auth_backend.create_superuser(request,
username=username,
email=normalise_email(email),
password=password)
if user:
self.write("Superuser %s created successfully.\n" % user.username)
else:
self.write_err("ERROR: could not create superuser")
return user
|
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, status)
ok_(len(stdout.getvalue()) > 0)
eq_('', stderr.getvalue())
|
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.