Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
6,600 | def save_as(self, event):
filename = self.asksavefile()
if filename:
if self.writefile(filename):
self.set_filename(filename)
self.set_saved(1)
try:
self.editwin.store_file_breaks()
except __HOLE__:
... | AttributeError | dataset/ETHPy150Open francelabs/datafari/windows/python/Lib/idlelib/IOBinding.py/IOBinding.save_as |
6,601 | def writefile(self, filename):
self.fixlastline()
chars = self.encode(self.text.get("1.0", "end-1c"))
if self.eol_convention != "\n":
chars = chars.replace("\n", self.eol_convention)
try:
with open(filename, "wb") as f:
f.write(chars)
r... | IOError | dataset/ETHPy150Open francelabs/datafari/windows/python/Lib/idlelib/IOBinding.py/IOBinding.writefile |
6,602 | def try_unlink(fname):
try:
os.unlink(fname)
except __HOLE__ as e:
if "No such file" not in str(e):
raise | OSError | dataset/ETHPy150Open fp7-ofelia/ocf/expedient/src/python/expedient_geni/tests.py/try_unlink |
6,603 | def test_getprotocol():
try:
getprotocol('invalid')
assert False, "ValueError was not raised"
except __HOLE__:
pass | ValueError | dataset/ETHPy150Open openstack/wsme/wsme/tests/test_protocols.py/test_getprotocol |
6,604 | def test_main():
suite = unittest.TestSuite()
suite.addTest(DocTestSuite('_threading_local'))
if test_support.is_jython:
del ThreadingLocalTest.test_local_refs
suite.addTest(unittest.makeSuite(ThreadingLocalTest))
try:
from thread import _local
except __HOLE__:
pass
... | ImportError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_threading_local.py/test_main |
6,605 | def run(self, edit):
settings = self.view.settings()
history = settings.get("git_savvy.help.history") or []
try:
history.pop()
page, anchor = history[-1]
except __HOLE__:
print("sorry, no can do!")
return
settings.set("git_savvy.h... | IndexError | dataset/ETHPy150Open divmain/GitSavvy/common/commands/help.py/GsHelpGotoPrevious.run |
6,606 | def symlink (src, dst):
print "Creating symlink to %s from %s" % (src, dst)
try:
os.symlink(src, dst)
except __HOLE__, e:
"Already exists!" | OSError | dataset/ETHPy150Open fp7-ofelia/ocf/ofam/src/install.py/symlink |
6,607 | def addDir (path, owner):
try:
print "Making Directory: %s" % (path)
os.makedirs(path)
except __HOLE__, e:
pass
call('chown %s %s' % (owner, path)) | OSError | dataset/ETHPy150Open fp7-ofelia/ocf/ofam/src/install.py/addDir |
6,608 | def aliasSub(requestContext, seriesList, search, replace):
"""
Runs series names through a regex search/replace.
Example::
&target=aliasSub(ip.*TCP*,"^.*TCP(\d+)","\\1")
"""
try:
seriesList.name = re.sub(search, replace, seriesList.name)
except __HOLE__:
for series in se... | AttributeError | dataset/ETHPy150Open brutasse/graphite-api/graphite_api/functions.py/aliasSub |
6,609 | def alias(requestContext, seriesList, newName):
"""
Takes one metric or a wildcard seriesList and a string in quotes.
Prints the string instead of the metric name in the legend.
Example::
&target=alias(Sales.widgets.largeBlue,"Large Blue Widgets")
"""
try:
seriesList.name = ne... | AttributeError | dataset/ETHPy150Open brutasse/graphite-api/graphite_api/functions.py/alias |
6,610 | def removeAbovePercentile(requestContext, seriesList, n):
"""
Removes data above the nth percentile from the series or list of series
provided. Values above this percentile are assigned a value of None.
"""
for s in seriesList:
s.name = 'removeAbovePercentile(%s, %d)' % (s.name, n)
s... | IndexError | dataset/ETHPy150Open brutasse/graphite-api/graphite_api/functions.py/removeAbovePercentile |
6,611 | def removeBelowPercentile(requestContext, seriesList, n):
"""
Removes data below the nth percentile from the series or list of series
provided. Values below this percentile are assigned a value of None.
"""
for s in seriesList:
s.name = 'removeBelowPercentile(%s, %d)' % (s.name, n)
s... | IndexError | dataset/ETHPy150Open brutasse/graphite-api/graphite_api/functions.py/removeBelowPercentile |
6,612 | def branch_stats(self):
"""Get stats about branches.
Returns a dict mapping line numbers to a tuple:
(total_exits, taken_exits).
"""
exit_counts = self.parser.exit_counts()
missing_arcs = self.missing_branch_arcs()
stats = {}
for lnum in self.branch_line... | KeyError | dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/coverage/results.py/Analysis.branch_stats |
6,613 | def DownloadActivityList(self, serviceRecord, exhaustive=False):
oauthSession = self._oauthSession(serviceRecord)
activities = []
exclusions = []
page_url = "https://api.endomondo.com/api/1/workouts"
while True:
resp = oauthSession.get(page_url)
try:
... | ValueError | dataset/ETHPy150Open cpfair/tapiriik/tapiriik/services/Endomondo/endomondo.py/EndomondoService.DownloadActivityList |
6,614 | def DownloadActivity(self, serviceRecord, activity):
resp = self._oauthSession(serviceRecord).get("https://api.endomondo.com/api/1/workouts/%d" % activity.ServiceData["WorkoutID"], params={"fields": "points"})
try:
resp = resp.json()
except __HOLE__:
self._rateLimitBailou... | ValueError | dataset/ETHPy150Open cpfair/tapiriik/tapiriik/services/Endomondo/endomondo.py/EndomondoService.DownloadActivity |
6,615 | def _run_exitfuncs():
"""run any registered exit functions
_exithandlers is traversed in reverse order so functions are executed
last in, first out.
"""
exc_info = None
while _exithandlers:
func, targs, kargs = _exithandlers.pop()
try:
func(*targs, **kargs)
... | SystemExit | dataset/ETHPy150Open python-zk/kazoo/kazoo/python2atexit.py/_run_exitfuncs |
6,616 | def get_page_size(request, default=20):
session = request.session
cookies = request.COOKIES
try:
page_size = int(session.get('horizon_pagesize',
cookies.get('horizon_pagesize',
getattr(settings,
... | ValueError | dataset/ETHPy150Open CiscoSystems/avos/horizon/utils/functions.py/get_page_size |
6,617 | def next_key(tuple_of_tuples, key):
"""Processes a tuple of 2-element tuples and returns the key which comes
after the given key.
"""
for i, t in enumerate(tuple_of_tuples):
if t[0] == key:
try:
return tuple_of_tuples[i + 1][0]
except __HOLE__:
... | IndexError | dataset/ETHPy150Open CiscoSystems/avos/horizon/utils/functions.py/next_key |
6,618 | def previous_key(tuple_of_tuples, key):
"""Processes a tuple of 2-element tuples and returns the key which comes
before the given key.
"""
for i, t in enumerate(tuple_of_tuples):
if t[0] == key:
try:
return tuple_of_tuples[i - 1][0]
except __HOLE__:
... | IndexError | dataset/ETHPy150Open CiscoSystems/avos/horizon/utils/functions.py/previous_key |
6,619 | def __new__(cls, start=None, stop=None, step=None, name=None, dtype=None,
fastpath=False, copy=False, **kwargs):
if fastpath:
return cls._simple_new(start, stop, step, name=name)
cls._validate_dtype(dtype)
# RangeIndex
if isinstance(start, RangeIndex):
... | ValueError | dataset/ETHPy150Open pydata/pandas/pandas/indexes/range.py/RangeIndex.__new__ |
6,620 | @classmethod
def _simple_new(cls, start, stop=None, step=None, name=None,
dtype=None, **kwargs):
result = object.__new__(cls)
# handle passed None, non-integers
if start is None or not com.is_integer(start):
try:
return RangeIndex(start, stop,... | TypeError | dataset/ETHPy150Open pydata/pandas/pandas/indexes/range.py/RangeIndex._simple_new |
6,621 | @classmethod
def _add_numeric_methods_binary(cls):
""" add in numeric methods, specialized to RangeIndex """
def _make_evaluate_binop(op, opstr, reversed=False, step=False):
"""
Parameters
----------
op : callable that accepts 2 parms
... | ValueError | dataset/ETHPy150Open pydata/pandas/pandas/indexes/range.py/RangeIndex._add_numeric_methods_binary |
6,622 | def run_subprocess(cmd, data=None):
"""
Execute the command C{cmd} in a subprocess.
@param cmd: The command to execute, specified as a list
of string.
@param data: A string containing data to send to the
subprocess.
@return: A tuple C{(out, err)}.
@raise OSError: If there is... | IOError | dataset/ETHPy150Open ardekantur/pyglet/tools/epydoc/epydoc/util.py/run_subprocess |
6,623 | def services(b):
logging.info('searching for service dependencies')
# Command fragments for listing the files in a package.
commands = {'apt': ['dpkg-query', '-L'],
'yum': ['rpm', '-ql']}
# Build a map of the directory that contains each file in the
# blueprint to the pathname of t... | KeyError | dataset/ETHPy150Open devstructure/blueprint/blueprint/services.py/services |
6,624 | def getByReference(self, ref):
"""
Returns an object based on the supplied reference. The C{ref} should
be an C{int}.
If the reference is not found, C{None} will be returned.
"""
try:
return self.list[ref]
except __HOLE__:
return None | IndexError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/PyAMF-0.6.1/pyamf/codec.py/IndexedCollection.getByReference |
6,625 | def getClassAlias(self, klass):
"""
Gets a class alias based on the supplied C{klass}. If one is not found
in the global context, one is created locally.
If you supply a string alias and the class is not registered,
L{pyamf.UnknownClassAlias} will be raised.
@param klas... | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/PyAMF-0.6.1/pyamf/codec.py/Context.getClassAlias |
6,626 | def readElement(self):
"""
Reads an AMF3 element from the data stream.
@raise DecodeError: The ActionScript type is unsupported.
@raise EOStream: No more data left to decode.
"""
pos = self.stream.tell()
try:
t = self.stream.read(1)
except IO... | IOError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/PyAMF-0.6.1/pyamf/codec.py/Decoder.readElement |
6,627 | def writeSequence(self, iterable):
"""
Encodes an iterable. The default is to write If the iterable has an al
"""
try:
alias = self.context.getClassAlias(iterable.__class__)
except (__HOLE__, pyamf.UnknownClassAlias):
self.writeList(iterable)
... | AttributeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/PyAMF-0.6.1/pyamf/codec.py/Encoder.writeSequence |
6,628 | def writeGenerator(self, gen):
"""
Iterates over a generator object and encodes all that is returned.
"""
n = getattr(gen, 'next')
while True:
try:
self.writeElement(n())
except __HOLE__:
break | StopIteration | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/PyAMF-0.6.1/pyamf/codec.py/Encoder.writeGenerator |
6,629 | def getTypeFunc(self, data):
"""
Returns a callable that will encode C{data} to C{self.stream}. If
C{data} is unencodable, then C{None} is returned.
"""
if data is None:
return self.writeNull
t = type(data)
# try types that we know will work
... | TypeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/PyAMF-0.6.1/pyamf/codec.py/Encoder.getTypeFunc |
6,630 | def writeElement(self, data):
"""
Encodes C{data} to AMF. If the data is not able to be matched to an AMF
type, then L{pyamf.EncodeError} will be raised.
"""
key = type(data)
func = None
try:
func = self._func_cache[key]
except __HOLE__:
... | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/PyAMF-0.6.1/pyamf/codec.py/Encoder.writeElement |
6,631 | def next(self):
try:
element = self.bucket.pop(0)
except __HOLE__:
raise StopIteration
start_pos = self.stream.tell()
self.writeElement(element)
end_pos = self.stream.tell()
self.stream.seek(start_pos)
return self.stream.read(end_pos -... | IndexError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/PyAMF-0.6.1/pyamf/codec.py/Encoder.next |
6,632 | def assert_course(p0, p1, expected):
try:
len(expected)
array = True
except __HOLE__:
array = False
result = geog.course(p0, p1)
if not array:
with pytest.raises(TypeError):
len(result)
assert np.allclose(result, expected)
result = geog.course(p0, p... | TypeError | dataset/ETHPy150Open jwass/geog/tests/test_course.py/assert_course |
6,633 | def DownloadLogs(self):
"""Download the requested logs.
This will write the logs to the file designated by
self.output_file, or to stdout if the filename is '-'.
Multiple roundtrips to the server may be made.
"""
if self.server:
StatusUpdate('Downloading request logs for app %s server %s ... | IOError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/appcfg.py/LogsRequester.DownloadLogs |
6,634 | def DateOfLogLine(line):
"""Returns a date object representing the log line's timestamp.
Args:
line: a log line string.
Returns:
A date object representing the timestamp or None if parsing fails.
"""
m = re.compile(r'[^[]+\[(\d+/[A-Za-z]+/\d+):[^\d]*').match(line)
if not m:
return None
try:
... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/appcfg.py/DateOfLogLine |
6,635 | def FindSentinel(filename, blocksize=2**16):
"""Return the sentinel line from the output file.
Args:
filename: The filename of the output file. (We'll read this file.)
blocksize: Optional block size for buffering, for unit testing.
Returns:
The contents of the last line in the file that doesn't sta... | IOError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/appcfg.py/FindSentinel |
6,636 | def EnsureDir(path):
"""Makes sure that a directory exists at the given path.
If a directory already exists at that path, nothing is done.
Otherwise, try to create a directory at that path with os.makedirs.
If that fails, propagate the resulting OSError exception.
Args:
path: The path that you want to r... | OSError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/appcfg.py/EnsureDir |
6,637 | def DoDownloadApp(rpcserver, out_dir, app_id, server, app_version):
"""Downloads the files associated with a particular app version.
Args:
rpcserver: The RPC server to use to download.
out_dir: The directory the files should be downloaded to.
app_id: The app ID of the app whose files we want to downloa... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/appcfg.py/DoDownloadApp |
6,638 | def DoUpload(self, paths, openfunc):
"""Uploads a new appversion with the given config and files to the server.
Args:
paths: An iterator that yields the relative paths of the files to upload.
openfunc: A function that takes a path and returns a file-like object.
Returns:
An appinfo.AppIn... | KeyboardInterrupt | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/appcfg.py/AppVersionUpload.DoUpload |
6,639 | def RequestLogs(self):
"""Write request logs to a file."""
args_length = len(self.args)
server = ''
if args_length == 2:
appyaml = self._ParseAppInfoFromYaml(self.args.pop(0))
app_id = appyaml.application
server = appyaml.server or ''
version = appyaml.version
elif args_leng... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/appcfg.py/AppCfgApp.RequestLogs |
6,640 | def RunBulkloader(self, arg_dict):
"""Invokes the bulkloader with the given keyword arguments.
Args:
arg_dict: Dictionary of arguments to pass to bulkloader.Run().
"""
try:
import sqlite3
except __HOLE__:
logging.error('upload_data action requires SQLite3 and the python '
... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/appcfg.py/AppCfgApp.RunBulkloader |
6,641 | def main(argv):
logging.basicConfig(format=('%(asctime)s %(levelname)s %(filename)s:'
'%(lineno)s %(message)s '))
try:
result = AppCfgApp(argv).Run()
if result:
sys.exit(result)
except __HOLE__:
StatusUpdate('Interrupted.')
sys.exit(1) | KeyboardInterrupt | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/appcfg.py/main |
6,642 | def on_select_remote(self, remote_index):
"""
After the user selects a remote, display a panel of branches that are
present on that remote, then proceed to `on_select_branch`.
"""
# If the user pressed `esc` or otherwise cancelled.
if remote_index == -1:
retur... | ValueError | dataset/ETHPy150Open divmain/GitSavvy/core/commands/pull.py/GsPullCommand.on_select_remote |
6,643 | def __lt__(self, other):
# convenience
obj = self.obj
if isinstance(other, Comparable):
other = other.obj
# None < everything else
if other is None:
return False
if obj is None:
return True
# numbers < everything else (except... | TypeError | dataset/ETHPy150Open alimanfoo/petl/petl/comparison.py/Comparable.__lt__ |
6,644 | def __getitem__(self, key):
if self.is_remote: # pragma: no cover
getitem = partial(robust_getitem, catch=RuntimeError)
else:
getitem = operator.getitem
try:
data = getitem(self.array, key)
except __HOLE__:
# Catch IndexError in netCDF4 a... | IndexError | dataset/ETHPy150Open pydata/xarray/xarray/backends/netCDF4_.py/NetCDF4ArrayWrapper.__getitem__ |
6,645 | def _nc4_group(ds, group, mode):
if group in set([None, '', '/']):
# use the root group
return ds
else:
# make sure it's a string
if not isinstance(group, basestring):
raise ValueError('group must be a string or None')
# support path-like syntax
path =... | KeyError | dataset/ETHPy150Open pydata/xarray/xarray/backends/netCDF4_.py/_nc4_group |
6,646 | def get_process_list():
procs = dict()
for proc in psutil.process_iter():
try:
pinfo = proc.as_dict(attrs=['pid', 'cmdline'])
procs[pinfo['pid']] = pinfo['cmdline'][0]
except (psutil.NoSuchProcess, IndexError, __HOLE__):
pass
return procs | TypeError | dataset/ETHPy150Open gooddata/smoker/tests/server/test_plugins.py/get_process_list |
6,647 | def get_TestSuite_from_module(mod, config):
"""Get an existing suite from a module."""
for methname in ("get_suite", "GetSuite"):
try:
meth = getattr(mod, methname)
return meth(config)
except __HOLE__:
continue
raise module.ObjectImportError("Module %r doe... | AttributeError | dataset/ETHPy150Open kdart/pycopia/QA/pycopia/QA/testloader.py/get_TestSuite_from_module |
6,648 | @staticmethod
def _get_mode(mode_arg, i_var_count, d_var_count):
"""
Tries to return an appropriate mode class.
Intended to be called only by __new__.
mode_arg
Can be a string or a class. If it is a
PlotMode subclass, it is simply returned.
If it ... | TypeError | dataset/ETHPy150Open sympy/sympy/sympy/plotting/pygletplot/plot_mode.py/PlotMode._get_mode |
6,649 | @staticmethod
def _get_default_mode(i, d, i_vars=-1):
if i_vars == -1:
i_vars = i
try:
return PlotMode._mode_default_map[d][i]
except __HOLE__:
# Keep looking for modes in higher i var counts
# which support the given d var count until we
... | TypeError | dataset/ETHPy150Open sympy/sympy/sympy/plotting/pygletplot/plot_mode.py/PlotMode._get_default_mode |
6,650 | @staticmethod
def _get_aliased_mode(alias, i, d, i_vars=-1):
if i_vars == -1:
i_vars = i
if alias not in PlotMode._mode_alias_list:
raise ValueError(("Couldn't find a mode called"
" %s. Known modes: %s.")
% (alias, ",... | TypeError | dataset/ETHPy150Open sympy/sympy/sympy/plotting/pygletplot/plot_mode.py/PlotMode._get_aliased_mode |
6,651 | @staticmethod
def _interpret_args(args):
interval_wrong_order = "PlotInterval %s was given before any function(s)."
interpret_error = "Could not interpret %s as a function or interval."
functions, intervals = [], []
if isinstance(args[0], GeometryEntity):
for coords in l... | TypeError | dataset/ETHPy150Open sympy/sympy/sympy/plotting/pygletplot/plot_mode.py/PlotMode._interpret_args |
6,652 | def deftgt(self, forme=None):
if forme is None:
forme = self
try:
tgtview = self.tgtview
except __HOLE__:
self.env.deftgt(forme)
else:
if forme.tgtfullname in tgtview:
self.error('Duplicate definition of %r'%forme.tgtfullname, forme.src.node)
tgtview[forme.tgtfullname] = forme | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/gsl/Main.py/Description.deftgt |
6,653 | def get_descr_by_name(self, name, context=None):
if name.startswith(self.mod.tgt_prefix):
return self.get_descr_by_tgt_name(name, context)
e = self
parts = name.split('.')
for part in parts:
try:
e = e.localview[part]
except __HOLE__:
assert context
self.env.error(
'Undefined: %r in %r.'... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/gsl/Main.py/Package.get_descr_by_name |
6,654 | def __repr__(self):
try:
return self.cond_expr
except __HOLE__:
return Description.__repr__(self) | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/gsl/Main.py/ConditionRef.__repr__ |
6,655 | def get_name(self):
try:
return self.get_arg_name()
except __HOLE__:
return '?' | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/gsl/Main.py/Arg.get_name |
6,656 | def _open(fullpath):
try:
size = os.stat(fullpath).st_size
except OSError, err: # Permission denied - ignore the file
print_debug("%s: permission denied: %s" % (fullpath, err))
return None
if size > 1024*1024: # too big
print_debug("%s: the file is too big: %d bytes"... | IOError | dataset/ETHPy150Open Southpaw-TACTIC/TACTIC/src/context/client/tactic-api-python-4.0.api04/Tools/Scripts/pysource.py/_open |
6,657 | def test_cache_options():
try:
from chest import Chest
except __HOLE__:
return
cache = Chest()
def inc2(x):
assert 'y' in cache
return x + 1
with dask.set_options(cache=cache):
get_sync({'x': (inc2, 'y'), 'y': 1}, 'x') | ImportError | dataset/ETHPy150Open dask/dask/dask/tests/test_async.py/test_cache_options |
6,658 | def precedence(item):
"""
Returns the precedence of a given object.
"""
if hasattr(item, "precedence"):
return item.precedence
try:
mro = item.__class__.__mro__
except __HOLE__:
return PRECEDENCE["Atom"]
for i in mro:
n = i.__name__
if n in PRECEDENCE_... | AttributeError | dataset/ETHPy150Open sympy/sympy/sympy/printing/precedence.py/precedence |
6,659 | def adb_shell(device, command, timeout=None, check_exit_code=False, as_root=False): # NOQA
# pylint: disable=too-many-branches, too-many-locals, too-many-statements
_check_env()
if as_root:
command = 'echo \'{}\' | su'.format(escape_single_quotes(command))
device_string = '-s {}'.format(device)... | ValueError | dataset/ETHPy150Open ARM-software/workload-automation/wlauto/utils/android.py/adb_shell |
6,660 | def filer_staticmedia_prefix():
"""
Returns the string contained in the setting FILER_STATICMEDIA_PREFIX.
"""
try:
from .. import settings
except __HOLE__:
return ''
return settings.FILER_STATICMEDIA_PREFIX | ImportError | dataset/ETHPy150Open django-leonardo/django-leonardo/leonardo/module/media/templatetags/filermedia.py/filer_staticmedia_prefix |
6,661 | def biblio(self,
aliases,
provider_url_template=None,
cache_enabled=True):
aliases_dict = provider.alias_dict_from_tuples(aliases)
if "blog" in aliases_dict:
id = aliases_dict["blog"][0]
# Only lookup biblio for items with appropriate ids
... | AttributeError | dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/providers/wordpresscom.py/Wordpresscom.biblio |
6,662 | def wordpress_post_id_from_nid(self, nid):
try:
return json.loads(nid)["wordpress_post_id"]
except (KeyError, __HOLE__):
return None | ValueError | dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/providers/wordpresscom.py/Wordpresscom.wordpress_post_id_from_nid |
6,663 | def blog_url_from_nid(self, nid):
try:
return json.loads(nid)["blog_url"]
except (__HOLE__, ValueError):
return None
# default method; providers can override | KeyError | dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/providers/wordpresscom.py/Wordpresscom.blog_url_from_nid |
6,664 | def get_aliases(self, query):
query_url = "{api_url}/provider/{provider_name}/memberitems/{query}?method=sync".format(
api_url=api_url,
provider_name=self.provider_name,
query=query
)
start = time.time()
logger.info(u"getting aliases from the {provider... | ValueError | dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/fakes.py/Importer.get_aliases |
6,665 | def poll(self, max_time=60):
logger.info(u"polling collection '{collection_id}'".format(
collection_id=self.collection_id))
still_updating = True
tries = 0
start = time.time()
while still_updating:
url = api_url + "/collection/" + self.collectionId
... | ValueError | dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/fakes.py/ReportPage.poll |
6,666 | def get_dois(self, num=1):
start = time.time()
dois = []
url = "http://random.labs.crossref.org/dois?from=2000&count=" + str(num)
logger.info(u"getting {num} random dois with IdSampler, using {url}".format(
num=num, url=url))
try:
r = requests.get(url,... | ValueError | dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/fakes.py/IdSampler.get_dois |
6,667 | def parse_args():
description='Silly Server for mocking real http servers'
options = [
{
"dest": "root_dir",
"required": False,
"metavar": "/dir/somedir",
"help": """Directory where your fake responses are waiting for me.
If not provided - defa... | ImportError | dataset/ETHPy150Open bak1an/silly-server/ss.py/parse_args |
6,668 | def log(self):
""" """
for log in self.logs:
log()
try:
if (self.store.stamp - self.flushStamp) >= self.flushPeriod:
console.profuse("Logger {0} Flushed at {1}, previous flush at {2}\n".format(
self.name, self.store.stamp, self.flus... | TypeError | dataset/ETHPy150Open ioflo/ioflo/ioflo/base/logging.py/Logger.log |
6,669 | def createPath(self, prefix = './'):
"""creates log directory path
creates physical directories on disk
"""
try:
#if repened too quickly could be same so we make a do until kludge
path = self.path
i = 0
while path == self.path: #do unti... | OSError | dataset/ETHPy150Open ioflo/ioflo/ioflo/base/logging.py/Logger.createPath |
6,670 | def reopen(self):
"""closes if open then reopens
"""
self.close() #innocuous to call close() on unopened file
try:
self.file = open(self.path, 'a+')
except __HOLE__ as ex:
console.terse("Error: creating log file '{0}'\n".format(ex))
self.file... | IOError | dataset/ETHPy150Open ioflo/ioflo/ioflo/base/logging.py/Log.reopen |
6,671 | def log(self):
"""called by conditional actions
"""
self.stamp = self.store.stamp
#should be different if binary kind
cf = io.StringIO() #use string io faster than concatenation
try:
text = self.formats['_time'] % self.stamp
except __HOLE__:
... | TypeError | dataset/ETHPy150Open ioflo/ioflo/ioflo/base/logging.py/Log.log |
6,672 | def logSequence(self, fifo=False):
""" called by conditional actions
Log and remove all elements of sequence
Default is lifo order
If fifo Then log in fifo order
head is left tail is right
lifo is log tail to head
fifo is log head to tail
... | TypeError | dataset/ETHPy150Open ioflo/ioflo/ioflo/base/logging.py/Log.logSequence |
6,673 | def change(self):
"""log if changed
logs once and then only if changed
requires that self.prepare has been called otherwise fields in
self.lasts won't match fields in log
"""
if self.stamp is None: #Always log at least once even if not updated
self.lo... | AttributeError | dataset/ETHPy150Open ioflo/ioflo/ioflo/base/logging.py/Log.change |
6,674 | def _checkFilePath(self, path):
try:
if not os.path.exists(path):
os.makedirs(path)
except __HOLE__:
log = "Could not create "+ path
self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log))) | OSError | dataset/ETHPy150Open lmco/laikaboss/laikamilter.py/LaikaMilter._checkFilePath |
6,675 | def _checkOKToContinueWithOpenFiles(self):
okToContinue = True
try:
pid = os.getpid()
try:
fd_dir=os.path.join('/proc/', str(pid), 'fd/')
except:
self.logger.writeLog(syslog.LOG_DEBUG, "Open Files: Problem With PID: "+str(pid)... | ValueError | dataset/ETHPy150Open lmco/laikaboss/laikamilter.py/LaikaMilter._checkOKToContinueWithOpenFiles |
6,676 | def _writeFileToDisk(self):
if self.archiveFileName:
try:
fp = open(self.archiveFileName, "wb")
fp.write(self.fileBuffer)
fp.flush()
fp.close()
except __HOLE__:
log = self.uuid+" Could not open "+ self.archiv... | IOError | dataset/ETHPy150Open lmco/laikaboss/laikamilter.py/LaikaMilter._writeFileToDisk |
6,677 | def deserialize(data):
try:
if not isinstance(data, str):
data = data.decode('utf-8')
data = json.loads(data)
if 'key' not in data or 'uri' not in data:
raise ValueError("Missing 'key' or 'uri' fields.")
return Account(key=load_private_key(data['key'].encode('... | TypeError | dataset/ETHPy150Open veeti/manuale/manuale/account.py/deserialize |
6,678 | def update_hash_dict(filehash, filename):
"""
Opens the pickled hash dictionary, adds an entry, and dumps it back.
"""
try:
with open(file_path + '/hash_dict.pickle', 'rb') as f:
hash_dict = cPickle.load(f)
except __HOLE__:
hash_dict = {}
hash_dict.update({filename: f... | IOError | dataset/ETHPy150Open statsmodels/statsmodels/tools/hash_funcs.py/update_hash_dict |
6,679 | def check_hash(rawfile, filename):
"""
Returns True if hash does not match the previous one.
"""
try:
with open(file_path + '/hash_dict.pickle', 'rb') as f:
hash_dict = cPickle.load(f)
except __HOLE__:
hash_dict = {}
try:
checkhash = hash_dict[filename]
ex... | IOError | dataset/ETHPy150Open statsmodels/statsmodels/tools/hash_funcs.py/check_hash |
6,680 | def parse_content(self, text):
"""parse section to formal format
raw_content: {title: section(with title)}. For `help` access.
formal_content: {title: section} but the section has been dedented
without title. For parse instance"""
raw_content = self.raw_content
... | ValueError | dataset/ETHPy150Open TylerTemp/docpie/docpie/parser.py/OptionParser.parse_content |
6,681 | def parse_line_to_lis(self, line, name=None):
if name is not None:
_, find_name, line = line.partition(name)
if not find_name:
raise DocpieError(
'%s is not in usage pattern %s' % (name, _))
# wrapped_space = self.wrap_symbol_re.sub(r' ... | ValueError | dataset/ETHPy150Open TylerTemp/docpie/docpie/parser.py/UsageParser.parse_line_to_lis |
6,682 | def __init__(self,methodName='runTest'):
unittest.TestCase.__init__(self,methodName)
self.host = "localhost:%d" % self.SERVER_PORT
self.connected = False
self.handle = -1
logdir = os.environ.get("ZKPY_LOG_DIR")
logfile = os.path.join(logdir, self.__class__.__name__ + ".lo... | IOError | dataset/ETHPy150Open francelabs/datafari/debian7/zookeeper/contrib/zkpython/src/test/zktestbase.py/TestBase.__init__ |
6,683 | def unregister(self, model=None):
'''Unregister a ``model`` if provided, otherwise it unregister all
registered models. Return a list of unregistered model managers or ``None``
if no managers were removed.'''
if model is not None:
try:
manager = self._registered_models.pop(mo... | KeyError | dataset/ETHPy150Open lsbardel/python-stdnet/stdnet/odm/mapper.py/Router.unregister |
6,684 | def model_iterator(application, include_related=True, exclude=None):
'''A generator of :class:`StdModel` classes found in *application*.
:parameter application: A python dotted path or an iterable over python
dotted-paths where models are defined.
Only models defined in these paths are considered.
For exampl... | ImportError | dataset/ETHPy150Open lsbardel/python-stdnet/stdnet/odm/mapper.py/model_iterator |
6,685 | @property
def isAbstract(self):
if self.subtreeRollUp:
return self.subtreeRollUp == CHILDREN_BUT_NO_ROLLUP
try:
try:
return self.abstract # ordinate may have an abstract attribute
except __HOLE__: # if none use axis object
return se... | AttributeError | dataset/ETHPy150Open Arelle/Arelle/arelle/ModelRenderingObject.py/StructuralNode.isAbstract |
6,686 | @property
def tagSelectors(self):
try:
return self._tagSelectors
except __HOLE__:
if self.parentStructuralNode is None:
self._tagSelectors = set()
else:
self._tagSelectors = self.parentStructuralNode.tagSelectors
if self... | AttributeError | dataset/ETHPy150Open Arelle/Arelle/arelle/ModelRenderingObject.py/StructuralNode.tagSelectors |
6,687 | @property
def parentDefinitionNode(self):
try:
return self._parentDefinitionNode
except __HOLE__:
parentDefinitionNode = None
for rel in self.modelXbrl.relationshipSet(XbrlConst.euAxisMember).toModelObject(self):
parentDefinitionNode = rel.fromMode... | AttributeError | dataset/ETHPy150Open Arelle/Arelle/arelle/ModelRenderingObject.py/ModelEuAxisCoord.parentDefinitionNode |
6,688 | @property
def filterRelationships(self):
try:
return self._filterRelationships
except __HOLE__:
rels = [] # order so conceptName filter is first (if any) (may want more sorting in future)
for rel in self.modelXbrl.relationshipSet((XbrlConst.tableFilter, XbrlConst.... | AttributeError | dataset/ETHPy150Open Arelle/Arelle/arelle/ModelRenderingObject.py/ModelTable.filterRelationships |
6,689 | @property
def renderingXPathContext(self):
try:
return self._rendrCntx
except __HOLE__:
xpCtx = getattr(self.modelXbrl, "rendrCntx", None) # none for EU 2010 tables
if xpCtx is not None:
self._rendrCntx = xpCtx.copy()
for tblParamRe... | AttributeError | dataset/ETHPy150Open Arelle/Arelle/arelle/ModelRenderingObject.py/ModelTable.renderingXPathContext |
6,690 | def aspectValue(self, xpCtx, aspect, inherit=None):
try:
# if xpCtx is None: xpCtx = self.modelXbrl.rendrCntx (must have xpCtx of callint table)
if aspect == Aspect.LOCATION and self._locationSourceVar in xpCtx.inScopeVars:
return xpCtx.inScopeVars[self._locationSourceVar... | AttributeError | dataset/ETHPy150Open Arelle/Arelle/arelle/ModelRenderingObject.py/ModelConstraintSet.aspectValue |
6,691 | @property
def constraintSets(self):
try:
return self._constraintSets
except __HOLE__:
self._constraintSets = dict((ruleSet.tagName, ruleSet)
for ruleSet in XmlUtil.children(self, self.namespaceURI, "ruleSet"))
if self.aspect... | AttributeError | dataset/ETHPy150Open Arelle/Arelle/arelle/ModelRenderingObject.py/ModelRuleDefinitionNode.constraintSets |
6,692 | @property
def aspectsInTaggedConstraintSet(self):
try:
return self._aspectsInTaggedConstraintSet
except __HOLE__:
self._aspectsInTaggedConstraintSet = set()
for tag, constraintSet in self.constraitSets().items():
if tag is not None:
... | AttributeError | dataset/ETHPy150Open Arelle/Arelle/arelle/ModelRenderingObject.py/ModelRuleDefinitionNode.aspectsInTaggedConstraintSet |
6,693 | @property
def generations(self):
try:
return _INT( XmlUtil.childText(self, (XbrlConst.table, XbrlConst.tableMMDD, XbrlConst.table201305, XbrlConst.table201301, XbrlConst.table2011), "generations") )
except (__HOLE__, ValueError):
if self.axis in ('sibling', 'child', 'parent')... | TypeError | dataset/ETHPy150Open Arelle/Arelle/arelle/ModelRenderingObject.py/ModelRelationshipDefinitionNode.generations |
6,694 | def coveredAspect(self, structuralNode=None):
try:
return self._coveredAspect
except __HOLE__:
self._coveredAspect = self.dimRelationships(structuralNode, getDimQname=True)
return self._coveredAspect | AttributeError | dataset/ETHPy150Open Arelle/Arelle/arelle/ModelRenderingObject.py/ModelDimensionRelationshipDefinitionNode.coveredAspect |
6,695 | def coveredAspect(self, structuralNode=None):
try:
return self._coveredAspect
except __HOLE__:
coveredAspect = self.get("coveredAspect")
if coveredAspect in coveredAspectToken:
self._coveredAspect = coveredAspectToken[coveredAspect]
else: ... | AttributeError | dataset/ETHPy150Open Arelle/Arelle/arelle/ModelRenderingObject.py/ModelSelectionDefinitionNode.coveredAspect |
6,696 | @property
def filterRelationships(self):
try:
return self._filterRelationships
except __HOLE__:
rels = [] # order so conceptName filter is first (if any) (may want more sorting in future)
for rel in self.modelXbrl.relationshipSet((XbrlConst.tableAspectNodeFilter, ... | AttributeError | dataset/ETHPy150Open Arelle/Arelle/arelle/ModelRenderingObject.py/ModelFilterDefinitionNode.filterRelationships |
6,697 | def aspectsCovered(self, varBinding=None):
try:
return self._aspectsCovered
except __HOLE__:
self._aspectsCovered = set()
self._dimensionsCovered = set()
self.includeUnreportedValue = False
if self.localName == "aspectNode": # after 2-13-05-17
... | AttributeError | dataset/ETHPy150Open Arelle/Arelle/arelle/ModelRenderingObject.py/ModelFilterDefinitionNode.aspectsCovered |
6,698 | def _kill_app(self, method, process_count):
""" Confirms that a number of test apps are terminated after the
provided method is executed.
`method`
Callable to execute when testing app terminate functionality.
This method will be passed the filename for th... | OSError | dataset/ETHPy150Open xtrementl/focus/tests/unit/plugin/modules/test_apps.py/CloseAppCase._kill_app |
6,699 | @defer.inlineCallbacks
def register(
self,
localpart=None,
password=None,
generate_token=True,
guest_access_token=None,
make_guest=False
):
"""Registers a new client on the server.
Args:
localpart : The local part of the user ID to reg... | ValueError | dataset/ETHPy150Open matrix-org/synapse/synapse/handlers/register.py/RegistrationHandler.register |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.