id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
100 |
0compute/xtraceback
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/0compute_xtraceback/xtraceback/test/test_nosextraceback.py
|
xtraceback.test.test_nosextraceback.TestNoseXTraceback.makeSuite.TC
|
class TC(unittest.TestCase):
def runTest(self):
raise ValueError("xxx")
|
class TC(unittest.TestCase):
def runTest(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 73 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
101 |
0compute/xtraceback
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/0compute_xtraceback/xtraceback/test/test_nosextraceback.py
|
xtraceback.test.test_nosextraceback.TestNoseXTracebackColor
|
class TestNoseXTracebackColor(TestNoseXTraceback):
args = ('--xtraceback-color=on',)
exc_str = EXCEPTION_COLOR
|
class TestNoseXTracebackColor(TestNoseXTraceback):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 80 | 4 | 1 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 4 | 0 | 0 |
102 |
0compute/xtraceback
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/0compute_xtraceback/xtraceback/tracebackcompat.py
|
xtraceback.tracebackcompat.TracebackCompat
|
class TracebackCompat(Stacked):
"""
A context manager that patches the stdlib traceback module
Functions in the traceback module that exist as a method of this class are
replaced with equivalents that use XTraceback.
:cvar NOPRINT: Exception types that we don't print for (includes None)
:type NOPRINT: tuple
:ivar defaults: Default options to apply to XTracebacks created by this
instance
:type defaults: dict
"""
NOPRINT = (None, KeyboardInterrupt)
def __init__(self, **defaults):
super(TracebackCompat, self).__init__()
self.defaults = defaults
# register patches for methods that wrap traceback functions
for key in dir(traceback):
if hasattr(self, key):
self._register_patch(traceback, key, getattr(self, key))
def __exit__(self, etype, evalue, tb):
if etype not in self.NOPRINT:
self.print_exception(etype, evalue, tb)
super(TracebackCompat, self).__exit__(etype, evalue, tb)
def _factory(self, etype, value, tb, limit=None, **options):
options["limit"] = \
getattr(sys, "tracebacklimit", None) if limit is None else limit
_options = self.defaults.copy()
_options.update(options)
return XTraceback(etype, value, tb, **_options)
def _print_factory(self, etype, value, tb, limit=None, file=None,
**options):
# late binding here may cause problems where there is no sys i.e. on
# google app engine but it is required for cases where sys.stderr is
# rebound i.e. under nose
if file is None and hasattr(sys, "stderr"):
file = sys.stderr
options["stream"] = file
return self._factory(etype, value, tb, limit, **options)
@functools.wraps(traceback.format_tb)
def format_tb(self, tb, limit=None, **options):
xtb = self._factory(None, None, tb, limit, **options)
return xtb.format_tb()
@functools.wraps(traceback.format_exception_only)
def format_exception_only(self, etype, value, **options):
xtb = self._factory(etype, value, None, **options)
return xtb.format_exception_only()
@functools.wraps(traceback.format_exception)
def format_exception(self, etype, value, tb, limit=None, **options):
xtb = self._factory(etype, value, tb, limit, **options)
return xtb.format_exception()
@functools.wraps(traceback.format_exc)
def format_exc(self, limit=None, **options):
options["limit"] = limit
return "".join(self.format_exception(*sys.exc_info(), **options))
@functools.wraps(traceback.print_tb)
def print_tb(self, tb, limit=None, file=None, **options):
xtb = self._print_factory(None, None, tb, limit, file, **options)
xtb.print_tb()
@functools.wraps(traceback.print_exception)
def print_exception(self, etype, value, tb, limit=None, file=None,
**options):
xtb = self._print_factory(etype, value, tb, limit, file, **options)
xtb.print_exception()
@functools.wraps(traceback.print_exc)
def print_exc(self, limit=None, file=None, **options):
options["limit"] = limit
options["file"] = file
self.print_exception(*sys.exc_info(), **options)
|
class TracebackCompat(Stacked):
'''
A context manager that patches the stdlib traceback module
Functions in the traceback module that exist as a method of this class are
replaced with equivalents that use XTraceback.
:cvar NOPRINT: Exception types that we don't print for (includes None)
:type NOPRINT: tuple
:ivar defaults: Default options to apply to XTracebacks created by this
instance
:type defaults: dict
'''
def __init__(self, **defaults):
pass
def __exit__(self, etype, evalue, tb):
pass
def _factory(self, etype, value, tb, limit=None, **options):
pass
def _print_factory(self, etype, value, tb, limit=None, file=None,
**options):
pass
@functools.wraps(traceback.format_tb)
def format_tb(self, tb, limit=None, **options):
pass
@functools.wraps(traceback.format_exception_only)
def format_exception_only(self, etype, value, **options):
pass
@functools.wraps(traceback.format_exception)
def format_exception_only(self, etype, value, **options):
pass
@functools.wraps(traceback.format_exc)
def format_exception_only(self, etype, value, **options):
pass
@functools.wraps(traceback.print_tb)
def print_tb(self, tb, limit=None, file=None, **options):
pass
@functools.wraps(traceback.print_exception)
def print_exception(self, etype, value, tb, limit=None, file=None,
**options):
pass
@functools.wraps(traceback.print_exc)
def print_exception(self, etype, value, tb, limit=None, file=None,
**options):
pass
| 19 | 1 | 4 | 0 | 4 | 0 | 1 | 0.26 | 1 | 2 | 1 | 0 | 11 | 1 | 11 | 11 | 83 | 15 | 54 | 30 | 33 | 14 | 44 | 21 | 32 | 3 | 1 | 2 | 16 |
103 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.3.0/test/support.py
|
test.support._MemoryWatchdog
|
class _MemoryWatchdog:
"""An object which periodically watches the process' memory consumption
and prints it out.
"""
def __init__(self):
self.procfile = '/proc/{pid}/statm'.format(pid=os.getpid())
self.started = False
def start(self):
try:
f = open(self.procfile, 'r')
except OSError as e:
warnings.warn('/proc not available for stats: {}'.format(e),
RuntimeWarning)
sys.stderr.flush()
return
watchdog_script = findfile("memory_watchdog.py")
self.mem_watchdog = subprocess.Popen([sys.executable, watchdog_script],
stdin=f, stderr=subprocess.DEVNULL)
f.close()
self.started = True
def stop(self):
if self.started:
self.mem_watchdog.terminate()
self.mem_watchdog.wait()
|
class _MemoryWatchdog:
'''An object which periodically watches the process' memory consumption
and prints it out.
'''
def __init__(self):
pass
def start(self):
pass
def stop(self):
pass
| 4 | 1 | 7 | 0 | 7 | 0 | 2 | 0.14 | 0 | 3 | 0 | 0 | 3 | 3 | 3 | 3 | 28 | 4 | 21 | 10 | 17 | 3 | 19 | 9 | 15 | 2 | 0 | 1 | 5 |
104 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.2.3/test/support.py
|
test.support.EnvironmentVarGuard
|
class EnvironmentVarGuard(collections.MutableMapping):
"""Class to help protect the environment variable properly. Can be used as
a context manager."""
def __init__(self):
self._environ = os.environ
self._changed = {}
def __getitem__(self, envvar):
return self._environ[envvar]
def __setitem__(self, envvar, value):
# Remember the initial value on the first access
if envvar not in self._changed:
self._changed[envvar] = self._environ.get(envvar)
self._environ[envvar] = value
def __delitem__(self, envvar):
# Remember the initial value on the first access
if envvar not in self._changed:
self._changed[envvar] = self._environ.get(envvar)
if envvar in self._environ:
del self._environ[envvar]
def keys(self):
return self._environ.keys()
def __iter__(self):
return iter(self._environ)
def __len__(self):
return len(self._environ)
def set(self, envvar, value):
self[envvar] = value
def unset(self, envvar):
del self[envvar]
def __enter__(self):
return self
def __exit__(self, *ignore_exc):
for (k, v) in self._changed.items():
if v is None:
if k in self._environ:
del self._environ[k]
else:
self._environ[k] = v
os.environ = self._environ
|
class EnvironmentVarGuard(collections.MutableMapping):
'''Class to help protect the environment variable properly. Can be used as
a context manager.'''
def __init__(self):
pass
def __getitem__(self, envvar):
pass
def __setitem__(self, envvar, value):
pass
def __delitem__(self, envvar):
pass
def keys(self):
pass
def __iter__(self):
pass
def __len__(self):
pass
def set(self, envvar, value):
pass
def unset(self, envvar):
pass
def __enter__(self):
pass
def __exit__(self, *ignore_exc):
pass
| 12 | 1 | 3 | 0 | 3 | 0 | 2 | 0.11 | 1 | 0 | 0 | 0 | 11 | 2 | 11 | 11 | 51 | 12 | 35 | 15 | 23 | 4 | 34 | 15 | 22 | 4 | 1 | 3 | 17 |
105 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.2.3/test/support.py
|
test.support.EnvironmentVarGuard
|
class EnvironmentVarGuard(collections.MutableMapping):
"""Class to help protect the environment variable properly. Can be used as
a context manager."""
def __init__(self):
self._environ = os.environ
self._changed = {}
def __getitem__(self, envvar):
return self._environ[envvar]
def __setitem__(self, envvar, value):
# Remember the initial value on the first access
if envvar not in self._changed:
self._changed[envvar] = self._environ.get(envvar)
self._environ[envvar] = value
def __delitem__(self, envvar):
# Remember the initial value on the first access
if envvar not in self._changed:
self._changed[envvar] = self._environ.get(envvar)
if envvar in self._environ:
del self._environ[envvar]
def keys(self):
return self._environ.keys()
def __iter__(self):
return iter(self._environ)
def __len__(self):
return len(self._environ)
def set(self, envvar, value):
self[envvar] = value
def unset(self, envvar):
del self[envvar]
def __enter__(self):
return self
def __exit__(self, *ignore_exc):
for (k, v) in self._changed.items():
if v is None:
if k in self._environ:
del self._environ[k]
else:
self._environ[k] = v
os.environ = self._environ
|
class EnvironmentVarGuard(collections.MutableMapping):
'''Class to help protect the environment variable properly. Can be used as
a context manager.'''
def __init__(self):
pass
def __getitem__(self, envvar):
pass
def __setitem__(self, envvar, value):
pass
def __delitem__(self, envvar):
pass
def keys(self):
pass
def __iter__(self):
pass
def __len__(self):
pass
def set(self, envvar, value):
pass
def unset(self, envvar):
pass
def __enter__(self):
pass
def __exit__(self, *ignore_exc):
pass
| 12 | 1 | 3 | 0 | 3 | 0 | 2 | 0.11 | 1 | 0 | 0 | 0 | 11 | 2 | 11 | 52 | 51 | 12 | 35 | 15 | 23 | 4 | 34 | 15 | 22 | 4 | 7 | 3 | 17 |
106 |
0compute/xtraceback
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/0compute_xtraceback/test_support/python/3.3.0/test/test_traceback.py
|
test.test_traceback.SyntaxTracebackCases.test_format_exception_only_bad__str__.X
|
class X(Exception):
def __str__(self):
1/0
|
class X(Exception):
def __str__(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 11 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 3 | 0 | 1 |
107 |
0compute/xtraceback
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/0compute_xtraceback/test_support/python/3.3.0/test/test_traceback.py
|
test.test_traceback.SyntaxTracebackCases.test_format_exception_only_bad__str__.X
|
class X(Exception):
def __str__(self):
1/0
|
class X(Exception):
def __str__(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 11 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 3 | 0 | 1 |
108 |
0compute/xtraceback
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/0compute_xtraceback/test_support/python/3.3.0/test/test_traceback.py
|
test.test_traceback.SyntaxTracebackCases.test_format_exception_only_bad__str__.X
|
class X(Exception):
def __str__(self):
1/0
|
class X(Exception):
def __str__(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 11 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 3 | 0 | 1 |
109 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.3.0/test/support.py
|
test.support.Matcher
|
class Matcher(object):
_partial_matches = ('msg', 'message')
def matches(self, d, **kwargs):
"""
Try to match a single dict with the supplied arguments.
Keys whose values are strings and which are in self._partial_matches
will be checked for partial (i.e. substring) matches. You can extend
this scheme to (for example) do regular expression matching, etc.
"""
result = True
for k in kwargs:
v = kwargs[k]
dv = d.get(k)
if not self.match_value(k, dv, v):
result = False
break
return result
def match_value(self, k, dv, v):
"""
Try to match a single stored value (dv) with a supplied value (v).
"""
if type(v) != type(dv):
result = False
elif type(dv) is not str or k not in self._partial_matches:
result = (v == dv)
else:
result = dv.find(v) >= 0
return result
|
class Matcher(object):
def matches(self, d, **kwargs):
'''
Try to match a single dict with the supplied arguments.
Keys whose values are strings and which are in self._partial_matches
will be checked for partial (i.e. substring) matches. You can extend
this scheme to (for example) do regular expression matching, etc.
'''
pass
def match_value(self, k, dv, v):
'''
Try to match a single stored value (dv) with a supplied value (v).
'''
pass
| 3 | 2 | 14 | 1 | 9 | 5 | 3 | 0.47 | 1 | 2 | 0 | 0 | 2 | 0 | 2 | 2 | 32 | 4 | 19 | 9 | 16 | 9 | 17 | 9 | 14 | 3 | 1 | 2 | 6 |
110 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.3.0/test/support.py
|
test.support.Matcher
|
class Matcher(object):
_partial_matches = ('msg', 'message')
def matches(self, d, **kwargs):
"""
Try to match a single dict with the supplied arguments.
Keys whose values are strings and which are in self._partial_matches
will be checked for partial (i.e. substring) matches. You can extend
this scheme to (for example) do regular expression matching, etc.
"""
result = True
for k in kwargs:
v = kwargs[k]
dv = d.get(k)
if not self.match_value(k, dv, v):
result = False
break
return result
def match_value(self, k, dv, v):
"""
Try to match a single stored value (dv) with a supplied value (v).
"""
if type(v) != type(dv):
result = False
elif type(dv) is not str or k not in self._partial_matches:
result = (v == dv)
else:
result = dv.find(v) >= 0
return result
|
class Matcher(object):
def matches(self, d, **kwargs):
'''
Try to match a single dict with the supplied arguments.
Keys whose values are strings and which are in self._partial_matches
will be checked for partial (i.e. substring) matches. You can extend
this scheme to (for example) do regular expression matching, etc.
'''
pass
def match_value(self, k, dv, v):
'''
Try to match a single stored value (dv) with a supplied value (v).
'''
pass
| 3 | 2 | 14 | 1 | 9 | 5 | 3 | 0.47 | 1 | 2 | 0 | 0 | 2 | 0 | 2 | 2 | 32 | 4 | 19 | 9 | 16 | 9 | 17 | 9 | 14 | 3 | 1 | 2 | 6 |
111 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.3.0/test/support.py
|
test.support.TestHandler
|
class TestHandler(logging.handlers.BufferingHandler):
def __init__(self, matcher):
# BufferingHandler takes a "capacity" argument
# so as to know when to flush. As we're overriding
# shouldFlush anyway, we can set a capacity of zero.
# You can call flush() manually to clear out the
# buffer.
logging.handlers.BufferingHandler.__init__(self, 0)
self.matcher = matcher
def shouldFlush(self):
return False
def emit(self, record):
self.format(record)
self.buffer.append(record.__dict__)
def matches(self, **kwargs):
"""
Look for a saved dict whose keys/values match the supplied arguments.
"""
result = False
for d in self.buffer:
if self.matcher.matches(d, **kwargs):
result = True
break
return result
|
class TestHandler(logging.handlers.BufferingHandler):
def __init__(self, matcher):
pass
def shouldFlush(self):
pass
def emit(self, record):
pass
def matches(self, **kwargs):
'''
Look for a saved dict whose keys/values match the supplied arguments.
'''
pass
| 5 | 1 | 6 | 0 | 4 | 2 | 2 | 0.5 | 1 | 0 | 0 | 0 | 4 | 1 | 4 | 29 | 27 | 3 | 16 | 8 | 11 | 8 | 16 | 8 | 11 | 3 | 4 | 2 | 6 |
112 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.3.0/test/support.py
|
test.support.TestHandler
|
class TestHandler(logging.handlers.BufferingHandler):
def __init__(self, matcher):
# BufferingHandler takes a "capacity" argument
# so as to know when to flush. As we're overriding
# shouldFlush anyway, we can set a capacity of zero.
# You can call flush() manually to clear out the
# buffer.
logging.handlers.BufferingHandler.__init__(self, 0)
self.matcher = matcher
def shouldFlush(self):
return False
def emit(self, record):
self.format(record)
self.buffer.append(record.__dict__)
def matches(self, **kwargs):
"""
Look for a saved dict whose keys/values match the supplied arguments.
"""
result = False
for d in self.buffer:
if self.matcher.matches(d, **kwargs):
result = True
break
return result
|
class TestHandler(logging.handlers.BufferingHandler):
def __init__(self, matcher):
pass
def shouldFlush(self):
pass
def emit(self, record):
pass
def matches(self, **kwargs):
'''
Look for a saved dict whose keys/values match the supplied arguments.
'''
pass
| 5 | 1 | 6 | 0 | 4 | 2 | 2 | 0.5 | 1 | 0 | 0 | 0 | 4 | 1 | 4 | 29 | 27 | 3 | 16 | 8 | 11 | 8 | 16 | 8 | 11 | 3 | 4 | 2 | 6 |
113 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.1.5/test/support.py
|
test.support.WarningsRecorder
|
class WarningsRecorder(object):
"""Convenience wrapper for the warnings list returned on
entry to the warnings.catch_warnings() context manager.
"""
def __init__(self, warnings_list):
self.warnings = warnings_list
def __getattr__(self, attr):
if self.warnings:
return getattr(self.warnings[-1], attr)
elif attr in warnings.WarningMessage._WARNING_DETAILS:
return None
raise AttributeError("%r has no attribute %r" % (self, attr))
def reset(self):
del self.warnings[:]
|
class WarningsRecorder(object):
'''Convenience wrapper for the warnings list returned on
entry to the warnings.catch_warnings() context manager.
'''
def __init__(self, warnings_list):
pass
def __getattr__(self, attr):
pass
def reset(self):
pass
| 4 | 1 | 3 | 0 | 3 | 0 | 2 | 0.27 | 1 | 1 | 0 | 0 | 3 | 1 | 3 | 3 | 16 | 2 | 11 | 5 | 7 | 3 | 10 | 5 | 6 | 3 | 1 | 1 | 5 |
114 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.3.0/test/support.py
|
test.support.DirsOnSysPath
|
class DirsOnSysPath(object):
"""Context manager to temporarily add directories to sys.path.
This makes a copy of sys.path, appends any directories given
as positional arguments, then reverts sys.path to the copied
settings when the context ends.
Note that *all* sys.path modifications in the body of the
context manager, including replacement of the object,
will be reverted at the end of the block.
"""
def __init__(self, *paths):
self.original_value = sys.path[:]
self.original_object = sys.path
sys.path.extend(paths)
def __enter__(self):
return self
def __exit__(self, *ignore_exc):
sys.path = self.original_object
sys.path[:] = self.original_value
|
class DirsOnSysPath(object):
'''Context manager to temporarily add directories to sys.path.
This makes a copy of sys.path, appends any directories given
as positional arguments, then reverts sys.path to the copied
settings when the context ends.
Note that *all* sys.path modifications in the body of the
context manager, including replacement of the object,
will be reverted at the end of the block.
'''
def __init__(self, *paths):
pass
def __enter__(self):
pass
def __exit__(self, *ignore_exc):
pass
| 4 | 1 | 3 | 0 | 3 | 0 | 1 | 0.8 | 1 | 0 | 0 | 0 | 3 | 2 | 3 | 3 | 23 | 5 | 10 | 6 | 6 | 8 | 10 | 6 | 6 | 1 | 1 | 0 | 3 |
115 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.3.0/test/support.py
|
test.support.DirsOnSysPath
|
class DirsOnSysPath(object):
"""Context manager to temporarily add directories to sys.path.
This makes a copy of sys.path, appends any directories given
as positional arguments, then reverts sys.path to the copied
settings when the context ends.
Note that *all* sys.path modifications in the body of the
context manager, including replacement of the object,
will be reverted at the end of the block.
"""
def __init__(self, *paths):
self.original_value = sys.path[:]
self.original_object = sys.path
sys.path.extend(paths)
def __enter__(self):
return self
def __exit__(self, *ignore_exc):
sys.path = self.original_object
sys.path[:] = self.original_value
|
class DirsOnSysPath(object):
'''Context manager to temporarily add directories to sys.path.
This makes a copy of sys.path, appends any directories given
as positional arguments, then reverts sys.path to the copied
settings when the context ends.
Note that *all* sys.path modifications in the body of the
context manager, including replacement of the object,
will be reverted at the end of the block.
'''
def __init__(self, *paths):
pass
def __enter__(self):
pass
def __exit__(self, *ignore_exc):
pass
| 4 | 1 | 3 | 0 | 3 | 0 | 1 | 0.8 | 1 | 0 | 0 | 0 | 3 | 2 | 3 | 3 | 23 | 5 | 10 | 6 | 6 | 8 | 10 | 6 | 6 | 1 | 1 | 0 | 3 |
116 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.1.5/test/support.py
|
test.support.CleanImport
|
class CleanImport(object):
"""Context manager to force import to return a new module reference.
This is useful for testing module-level behaviours, such as
the emission of a DeprecationWarning on import.
Use like this:
with CleanImport("foo"):
__import__("foo") # new reference
"""
def __init__(self, *module_names):
self.original_modules = sys.modules.copy()
for module_name in module_names:
if module_name in sys.modules:
module = sys.modules[module_name]
# It is possible that module_name is just an alias for
# another module (e.g. stub for modules renamed in 3.x).
# In that case, we also need delete the real module to clear
# the import cache.
if module.__name__ != module_name:
del sys.modules[module.__name__]
del sys.modules[module_name]
def __enter__(self):
return self
def __exit__(self, *ignore_exc):
sys.modules.update(self.original_modules)
|
class CleanImport(object):
'''Context manager to force import to return a new module reference.
This is useful for testing module-level behaviours, such as
the emission of a DeprecationWarning on import.
Use like this:
with CleanImport("foo"):
__import__("foo") # new reference
'''
def __init__(self, *module_names):
pass
def __enter__(self):
pass
def __exit__(self, *ignore_exc):
pass
| 4 | 1 | 5 | 0 | 4 | 1 | 2 | 0.85 | 1 | 0 | 0 | 0 | 3 | 1 | 3 | 3 | 30 | 6 | 13 | 7 | 9 | 11 | 13 | 7 | 9 | 4 | 1 | 3 | 6 |
117 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.1.5/test/support.py
|
test.support.CleanImport
|
class CleanImport(object):
"""Context manager to force import to return a new module reference.
This is useful for testing module-level behaviours, such as
the emission of a DeprecationWarning on import.
Use like this:
with CleanImport("foo"):
__import__("foo") # new reference
"""
def __init__(self, *module_names):
self.original_modules = sys.modules.copy()
for module_name in module_names:
if module_name in sys.modules:
module = sys.modules[module_name]
# It is possible that module_name is just an alias for
# another module (e.g. stub for modules renamed in 3.x).
# In that case, we also need delete the real module to clear
# the import cache.
if module.__name__ != module_name:
del sys.modules[module.__name__]
del sys.modules[module_name]
def __enter__(self):
return self
def __exit__(self, *ignore_exc):
sys.modules.update(self.original_modules)
|
class CleanImport(object):
'''Context manager to force import to return a new module reference.
This is useful for testing module-level behaviours, such as
the emission of a DeprecationWarning on import.
Use like this:
with CleanImport("foo"):
__import__("foo") # new reference
'''
def __init__(self, *module_names):
pass
def __enter__(self):
pass
def __exit__(self, *ignore_exc):
pass
| 4 | 1 | 5 | 0 | 4 | 1 | 2 | 0.85 | 1 | 0 | 0 | 0 | 3 | 1 | 3 | 3 | 30 | 6 | 13 | 7 | 9 | 11 | 13 | 7 | 9 | 4 | 1 | 3 | 6 |
118 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.1.5/test/support.py
|
test.support.CleanImport
|
class CleanImport(object):
"""Context manager to force import to return a new module reference.
This is useful for testing module-level behaviours, such as
the emission of a DeprecationWarning on import.
Use like this:
with CleanImport("foo"):
__import__("foo") # new reference
"""
def __init__(self, *module_names):
self.original_modules = sys.modules.copy()
for module_name in module_names:
if module_name in sys.modules:
module = sys.modules[module_name]
# It is possible that module_name is just an alias for
# another module (e.g. stub for modules renamed in 3.x).
# In that case, we also need delete the real module to clear
# the import cache.
if module.__name__ != module_name:
del sys.modules[module.__name__]
del sys.modules[module_name]
def __enter__(self):
return self
def __exit__(self, *ignore_exc):
sys.modules.update(self.original_modules)
|
class CleanImport(object):
'''Context manager to force import to return a new module reference.
This is useful for testing module-level behaviours, such as
the emission of a DeprecationWarning on import.
Use like this:
with CleanImport("foo"):
__import__("foo") # new reference
'''
def __init__(self, *module_names):
pass
def __enter__(self):
pass
def __exit__(self, *ignore_exc):
pass
| 4 | 1 | 5 | 0 | 4 | 1 | 2 | 0.85 | 1 | 0 | 0 | 0 | 3 | 1 | 3 | 3 | 30 | 6 | 13 | 7 | 9 | 11 | 13 | 7 | 9 | 4 | 1 | 3 | 6 |
119 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.3.0/test/support.py
|
test.support.BasicTestRunner
|
class BasicTestRunner:
def run(self, test):
result = unittest.TestResult()
test(result)
return result
|
class BasicTestRunner:
def run(self, test):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 5 | 0 | 5 | 3 | 3 | 0 | 5 | 3 | 3 | 1 | 0 | 0 | 1 |
120 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.3.0/test/support.py
|
test.support.BasicTestRunner
|
class BasicTestRunner:
def run(self, test):
result = unittest.TestResult()
test(result)
return result
|
class BasicTestRunner:
def run(self, test):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 5 | 0 | 5 | 3 | 3 | 0 | 5 | 3 | 3 | 1 | 0 | 0 | 1 |
121 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.3.0/test/support.py
|
test.support.BasicTestRunner
|
class BasicTestRunner:
def run(self, test):
result = unittest.TestResult()
test(result)
return result
|
class BasicTestRunner:
def run(self, test):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 5 | 0 | 5 | 3 | 3 | 0 | 5 | 3 | 3 | 1 | 0 | 0 | 1 |
122 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.3.0/test/support.py
|
test.support.TransientResource
|
class TransientResource(object):
"""Raise ResourceDenied if an exception is raised while the context manager
is in effect that matches the specified exception and attributes."""
def __init__(self, exc, **kwargs):
self.exc = exc
self.attrs = kwargs
def __enter__(self):
return self
def __exit__(self, type_=None, value=None, traceback=None):
"""If type_ is a subclass of self.exc and value has attributes matching
self.attrs, raise ResourceDenied. Otherwise let the exception
propagate (if any)."""
if type_ is not None and issubclass(self.exc, type_):
for attr, attr_value in self.attrs.items():
if not hasattr(value, attr):
break
if getattr(value, attr) != attr_value:
break
else:
raise ResourceDenied("an optional resource is not available")
|
class TransientResource(object):
'''Raise ResourceDenied if an exception is raised while the context manager
is in effect that matches the specified exception and attributes.'''
def __init__(self, exc, **kwargs):
pass
def __enter__(self):
pass
def __exit__(self, type_=None, value=None, traceback=None):
'''If type_ is a subclass of self.exc and value has attributes matching
self.attrs, raise ResourceDenied. Otherwise let the exception
propagate (if any).'''
pass
| 4 | 2 | 6 | 0 | 5 | 1 | 2 | 0.33 | 1 | 1 | 1 | 0 | 3 | 2 | 3 | 3 | 24 | 4 | 15 | 7 | 11 | 5 | 15 | 7 | 11 | 4 | 1 | 3 | 6 |
123 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.3.0/test/support.py
|
test.support.TransientResource
|
class TransientResource(object):
"""Raise ResourceDenied if an exception is raised while the context manager
is in effect that matches the specified exception and attributes."""
def __init__(self, exc, **kwargs):
self.exc = exc
self.attrs = kwargs
def __enter__(self):
return self
def __exit__(self, type_=None, value=None, traceback=None):
"""If type_ is a subclass of self.exc and value has attributes matching
self.attrs, raise ResourceDenied. Otherwise let the exception
propagate (if any)."""
if type_ is not None and issubclass(self.exc, type_):
for attr, attr_value in self.attrs.items():
if not hasattr(value, attr):
break
if getattr(value, attr) != attr_value:
break
else:
raise ResourceDenied("an optional resource is not available")
|
class TransientResource(object):
'''Raise ResourceDenied if an exception is raised while the context manager
is in effect that matches the specified exception and attributes.'''
def __init__(self, exc, **kwargs):
pass
def __enter__(self):
pass
def __exit__(self, type_=None, value=None, traceback=None):
'''If type_ is a subclass of self.exc and value has attributes matching
self.attrs, raise ResourceDenied. Otherwise let the exception
propagate (if any).'''
pass
| 4 | 2 | 6 | 0 | 5 | 1 | 2 | 0.33 | 1 | 1 | 1 | 0 | 3 | 2 | 3 | 3 | 24 | 4 | 15 | 7 | 11 | 5 | 15 | 7 | 11 | 4 | 1 | 3 | 6 |
124 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.3.0/test/support.py
|
test.support.TransientResource
|
class TransientResource(object):
"""Raise ResourceDenied if an exception is raised while the context manager
is in effect that matches the specified exception and attributes."""
def __init__(self, exc, **kwargs):
self.exc = exc
self.attrs = kwargs
def __enter__(self):
return self
def __exit__(self, type_=None, value=None, traceback=None):
"""If type_ is a subclass of self.exc and value has attributes matching
self.attrs, raise ResourceDenied. Otherwise let the exception
propagate (if any)."""
if type_ is not None and issubclass(self.exc, type_):
for attr, attr_value in self.attrs.items():
if not hasattr(value, attr):
break
if getattr(value, attr) != attr_value:
break
else:
raise ResourceDenied("an optional resource is not available")
|
class TransientResource(object):
'''Raise ResourceDenied if an exception is raised while the context manager
is in effect that matches the specified exception and attributes.'''
def __init__(self, exc, **kwargs):
pass
def __enter__(self):
pass
def __exit__(self, type_=None, value=None, traceback=None):
'''If type_ is a subclass of self.exc and value has attributes matching
self.attrs, raise ResourceDenied. Otherwise let the exception
propagate (if any).'''
pass
| 4 | 2 | 6 | 0 | 5 | 1 | 2 | 0.33 | 1 | 1 | 1 | 0 | 3 | 2 | 3 | 3 | 24 | 4 | 15 | 7 | 11 | 5 | 15 | 7 | 11 | 4 | 1 | 3 | 6 |
125 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.3.0/test/support.py
|
test.support.ResourceDenied
|
class ResourceDenied(unittest.SkipTest):
"""Test skipped because it requested a disallowed resource.
This is raised when a test calls requires() for a resource that
has not be enabled. It is used to distinguish between expected
and unexpected skips.
"""
|
class ResourceDenied(unittest.SkipTest):
'''Test skipped because it requested a disallowed resource.
This is raised when a test calls requires() for a resource that
has not be enabled. It is used to distinguish between expected
and unexpected skips.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 7 | 1 | 1 | 1 | 0 | 5 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
126 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.3.0/test/support.py
|
test.support.ResourceDenied
|
class ResourceDenied(unittest.SkipTest):
"""Test skipped because it requested a disallowed resource.
This is raised when a test calls requires() for a resource that
has not be enabled. It is used to distinguish between expected
and unexpected skips.
"""
|
class ResourceDenied(unittest.SkipTest):
'''Test skipped because it requested a disallowed resource.
This is raised when a test calls requires() for a resource that
has not be enabled. It is used to distinguish between expected
and unexpected skips.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 7 | 1 | 1 | 1 | 0 | 5 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
127 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.3.0/test/support.py
|
test.support.ResourceDenied
|
class ResourceDenied(unittest.SkipTest):
"""Test skipped because it requested a disallowed resource.
This is raised when a test calls requires() for a resource that
has not be enabled. It is used to distinguish between expected
and unexpected skips.
"""
|
class ResourceDenied(unittest.SkipTest):
'''Test skipped because it requested a disallowed resource.
This is raised when a test calls requires() for a resource that
has not be enabled. It is used to distinguish between expected
and unexpected skips.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 7 | 1 | 1 | 1 | 0 | 5 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
128 |
0compute/xtraceback
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/0compute_xtraceback/xtraceback/lexer.py
|
xtraceback.lexer.PythonXTracebackLexer
|
class PythonXTracebackLexer(PythonTracebackLexer):
tokens = {
"root": [
include("entry"),
include("exception"),
(r"^.*\n", Generic.Error),
],
"entry": [
(r"^Traceback \(most recent call last\):\n",
Generic.Error,
"frame"),
# file - path is colored differently if under working directory
(r'^( File )((?:"[./<][^"]+")?)((?:"[^"]+")?)'
r'(, line )(\d+)((?:, in )?)(.*)(\n)',
bygroups(Generic.Error, Name.Builtin, Operator.Word,
Generic.Error, Number, Generic.Error, Name.Function,
Text),
"frame"),
],
"exception": [
(r"^(AssertionError: )(.+\n)", bygroups(Generic.Error,
using(XPythonLexer))),
(r"^(%s:?)(.+\n)" % BASE_NAME, bygroups(Generic.Error,
String)),
],
"frame": [
include("entry"),
include("exception"),
# line of python code
(r"^((?:-+>)?)( +)(\d+)(.+\n)",
bygroups(Generic.Error, Text, Number, using(XPythonLexer))),
# variable continuation
(r"^([ ]+)('[^']+')(: )(.*)([,}]?\n)",
bygroups(
Text, String, Name.Operator, using(XPythonLexer), Text
)),
# variable
(r"^([ ]+)((?:g:)?)(\**%s)( = )(.+\n)" % BASE_NAME,
bygroups(Text, Name.Builtin, Name.Variable, Name.Operator,
using(XPythonLexer))),
# plain python
(r"^( )(.+)(\n)",
bygroups(Text, using(XPythonLexer), Text)),
],
}
|
class PythonXTracebackLexer(PythonTracebackLexer):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0.13 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 29 | 47 | 2 | 40 | 2 | 39 | 5 | 2 | 2 | 1 | 0 | 6 | 0 | 0 |
129 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.1.5/test/support.py
|
test.support.EnvironmentVarGuard
|
class EnvironmentVarGuard(collections.MutableMapping):
"""Class to help protect the environment variable properly. Can be used as
a context manager."""
def __init__(self):
self._environ = os.environ
self._changed = {}
def __getitem__(self, envvar):
return self._environ[envvar]
def __setitem__(self, envvar, value):
# Remember the initial value on the first access
if envvar not in self._changed:
self._changed[envvar] = self._environ.get(envvar)
self._environ[envvar] = value
def __delitem__(self, envvar):
# Remember the initial value on the first access
if envvar not in self._changed:
self._changed[envvar] = self._environ.get(envvar)
if envvar in self._environ:
del self._environ[envvar]
def keys(self):
return self._environ.keys()
def __iter__(self):
return iter(self._environ)
def __len__(self):
return len(self._environ)
def set(self, envvar, value):
self[envvar] = value
def unset(self, envvar):
del self[envvar]
def __enter__(self):
return self
def __exit__(self, *ignore_exc):
for (k, v) in self._changed.items():
if v is None:
if k in self._environ:
del self._environ[k]
else:
self._environ[k] = v
|
class EnvironmentVarGuard(collections.MutableMapping):
'''Class to help protect the environment variable properly. Can be used as
a context manager.'''
def __init__(self):
pass
def __getitem__(self, envvar):
pass
def __setitem__(self, envvar, value):
pass
def __delitem__(self, envvar):
pass
def keys(self):
pass
def __iter__(self):
pass
def __len__(self):
pass
def set(self, envvar, value):
pass
def unset(self, envvar):
pass
def __enter__(self):
pass
def __exit__(self, *ignore_exc):
pass
| 12 | 1 | 3 | 0 | 3 | 0 | 2 | 0.12 | 1 | 0 | 0 | 0 | 11 | 2 | 11 | 11 | 50 | 12 | 34 | 15 | 22 | 4 | 33 | 15 | 21 | 4 | 1 | 3 | 17 |
130 |
0compute/xtraceback
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/0compute_xtraceback/xtraceback/nosextraceback.py
|
xtraceback.nosextraceback.NoseXTraceback
|
class NoseXTraceback(Plugin):
"""Extended traceback for error output."""
name = "xtraceback"
# must be before capture otherwise we don't see the real sys.stdout
score = 600
_options = (
("globals",
"Include globals in tracebacks [%s]",
"store_true"),
("globals_include",
"Include only globals in this namespace [%s]",
"store"),
("color",
"Show color tracebacks - one of on,off,auto (default=auto) [%s]",
"store"),
)
def options(self, parser, env):
super(NoseXTraceback, self).options(parser, env)
for name, doc, action in self._options:
env_opt = "NOSE_XTRACEBACK_%s" % name.upper()
parser.add_option("--xtraceback-%s" % name.replace("_", "-"),
action=action,
dest="xtraceback_%s" % name,
default=env.get(env_opt),
help=doc % env_opt)
def configure(self, options, conf):
super(NoseXTraceback, self).configure(options, conf)
for option in self._options:
name = "xtraceback_%s" % option[0]
setattr(self, name, getattr(options, name))
if self.xtraceback_color is not None:
if self.xtraceback_color == "on":
self.xtraceback_color = True
else:
self.xtraceback_color = False
def begin(self):
options = dict(
color=self.xtraceback_color,
stream=self.conf.stream,
show_globals=self.xtraceback_globals,
globals_module_include=self.xtraceback_globals_include
)
self.compat = TracebackCompat(**options)
self.compat.__enter__()
def finalize(self, result):
self.compat.__exit__(None, None, None)
|
class NoseXTraceback(Plugin):
'''Extended traceback for error output.'''
def options(self, parser, env):
pass
def configure(self, options, conf):
pass
def begin(self):
pass
def finalize(self, result):
pass
| 5 | 1 | 8 | 0 | 8 | 0 | 2 | 0.05 | 1 | 3 | 1 | 0 | 4 | 3 | 4 | 4 | 53 | 7 | 44 | 16 | 39 | 2 | 24 | 15 | 19 | 4 | 1 | 2 | 8 |
131 |
0compute/xtraceback
|
0compute_xtraceback/xtraceback/test/test_loggingcompat.py
|
xtraceback.test.test_loggingcompat.MockLogStreamHandler
|
class MockLogStreamHandler(MockLogHandler):
def __init__(self, level=logging.NOTSET, tty=False):
super(MockLogStreamHandler, self).__init__(level)
self.stream = self.StringIO()
self.stream.isatty = lambda: tty
|
class MockLogStreamHandler(MockLogHandler):
def __init__(self, level=logging.NOTSET, tty=False):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 23 | 6 | 1 | 5 | 3 | 3 | 0 | 5 | 3 | 3 | 1 | 4 | 0 | 1 |
132 |
0compute/xtraceback
|
0compute_xtraceback/xtraceback/test/test_loggingcompat.py
|
xtraceback.test.test_loggingcompat.TestLoggingCompat
|
class TestLoggingCompat(XTracebackTestCase):
def setUp(self):
super(TestLoggingCompat, self).setUp()
self.traceback_compat = TracebackCompat(**self.XTB_DEFAULTS)
def _make_logger(self, handler_cls, **handler_kwargs):
handler = handler_cls(**handler_kwargs)
handler.setFormatter(logging.Formatter())
logger = logging.Logger(name="test")
logger.addHandler(handler)
return logger, handler
def test_simple(self):
logger, handler = self._make_logger(MockLogHandler)
logging_compat = LoggingCompat(handler, self.traceback_compat)
with logging_compat:
try:
exec(BASIC_TEST, {})
except:
logger.exception("the exc")
else:
self.fail("Should have raised exception")
self.assertTrue(len(handler.log), 1)
self.assertTrue(len(handler.log["ERROR"]), 1)
exc_str = "\n".join(handler.log["ERROR"][0].split("\n")[1:])
self._assert_tb_str(exc_str, SIMPLE_EXCEPTION)
@skipIfNoPygments
def test_simple_color(self):
logger, handler = self._make_logger(MockLogHandler)
logging_compat = LoggingCompat(handler, self.traceback_compat,
color=True)
with logging_compat:
try:
exec(BASIC_TEST, {})
except:
logger.exception("the exc")
else:
self.fail("Should have raised exception")
self.assertTrue(len(handler.log), 1)
self.assertTrue(len(handler.log["ERROR"]), 1)
exc_str = "\n".join(handler.log["ERROR"][0].split("\n")[1:])
self._assert_tb_str(exc_str, SIMPLE_EXCEPTION_COLOR)
|
class TestLoggingCompat(XTracebackTestCase):
def setUp(self):
pass
def _make_logger(self, handler_cls, **handler_kwargs):
pass
def test_simple(self):
pass
@skipIfNoPygments
def test_simple_color(self):
pass
| 6 | 0 | 10 | 0 | 10 | 0 | 2 | 0 | 1 | 4 | 1 | 0 | 4 | 1 | 4 | 82 | 44 | 4 | 40 | 15 | 34 | 0 | 38 | 14 | 33 | 2 | 3 | 2 | 6 |
133 |
0compute/xtraceback
|
0compute_xtraceback/xtraceback/test/test_nosextraceback.py
|
xtraceback.test.test_nosextraceback.TestNoseXTraceback
|
class TestNoseXTraceback(PluginTester, XTracebackTestCase):
activate = '--with-xtraceback'
plugins = [NoseXTraceback()]
exc_str = EXCEPTION
def makeSuite(self):
class TC(unittest.TestCase):
def runTest(self):
raise ValueError("xxx")
return unittest.TestSuite([TC()])
def test_active(self):
exc_str = TIME_PATTEN.sub("0.001s", str(self.output))
self._assert_tb_str(exc_str, self.exc_str)
|
class TestNoseXTraceback(PluginTester, XTracebackTestCase):
def makeSuite(self):
pass
class TC(unittest.TestCase):
def runTest(self):
pass
def test_active(self):
pass
| 5 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 2 | 3 | 1 | 2 | 2 | 0 | 2 | 80 | 17 | 5 | 12 | 9 | 7 | 0 | 12 | 9 | 7 | 1 | 3 | 0 | 3 |
134 |
0compute/xtraceback
|
0compute_xtraceback/xtraceback/test/test_nosextraceback.py
|
xtraceback.test.test_nosextraceback.TestNoseXTracebackColorOff
|
class TestNoseXTracebackColorOff(TestNoseXTraceback):
args = ('--xtraceback-color=off',)
exc_str = EXCEPTION
|
class TestNoseXTracebackColorOff(TestNoseXTraceback):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 80 | 4 | 1 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 4 | 0 | 0 |
135 |
0compute/xtraceback
|
0compute_xtraceback/xtraceback/test/test_tracebackcompat.py
|
xtraceback.test.test_tracebackcompat.TestTracebackCompat
|
class TestTracebackCompat(XTracebackTestCase):
def setUp(self):
super(TestTracebackCompat, self).setUp()
self.compat = TracebackCompat(**self.XTB_DEFAULTS)
self.compat.__enter__()
def tearDown(self):
super(TestTracebackCompat, self).tearDown()
self.compat.__exit__(None, None, None)
def test_format_tb(self):
tb = self._get_exc_info(BASIC_TEST)[2]
lines = traceback.format_tb(tb)
self._assert_tb_lines(lines, SIMPLE_TRACEBACK)
def test_print_tb(self):
tb = self._get_exc_info(BASIC_TEST)[2]
stream = self.StringIO()
traceback.print_tb(tb, file=stream)
self._assert_tb_str(stream.getvalue(), SIMPLE_TRACEBACK)
def test_print_tb_no_file(self):
stream = self.StringIO()
stderr = sys.stderr
sys.stderr = stream
try:
tb = self._get_exc_info(BASIC_TEST)[2]
traceback.print_tb(tb)
self._assert_tb_str(stream.getvalue(), SIMPLE_TRACEBACK)
finally:
sys.stderr = stderr
def test_format_exception_only(self):
etype, value = self._get_exc_info(BASIC_TEST)[:-1]
lines = traceback.format_exception_only(etype, value)
self._assert_tb_lines(lines, SIMPLE_EXCEPTION_NO_TB)
def test_format_exception(self):
exc_info = self._get_exc_info(BASIC_TEST)
lines = traceback.format_exception(*exc_info)
self._assert_tb_lines(lines, SIMPLE_EXCEPTION)
def test_print_exception(self):
stream = self.StringIO()
exc_info = self._get_exc_info(BASIC_TEST)
traceback.print_exception(*exc_info, **dict(file=stream))
self._assert_tb_str(stream.getvalue(), SIMPLE_EXCEPTION)
def test_print_exception_limited(self):
stream = self.StringIO()
traceback.print_exception(*self._get_exc_info(BASIC_TEST),
**dict(limit=2, file=stream))
self._assert_tb_str(stream.getvalue(), SIMPLE_EXCEPTION_ONEFRAME)
def test_format_exc(self):
try:
exec(BASIC_TEST, {})
except:
exc_str = traceback.format_exc()
else:
self.fail("Should have raised exception")
self._assert_tb_str(exc_str, SIMPLE_EXCEPTION)
def test_print_exc(self):
stream = self.StringIO()
try:
exec(BASIC_TEST, {})
except:
traceback.print_exc(file=stream)
else:
self.fail("Should have raised exception")
self._assert_tb_str(stream.getvalue(), SIMPLE_EXCEPTION)
|
class TestTracebackCompat(XTracebackTestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_format_tb(self):
pass
def test_print_tb(self):
pass
def test_print_tb_no_file(self):
pass
def test_format_exception_only(self):
pass
def test_format_exception_only(self):
pass
def test_print_exception(self):
pass
def test_print_exception_limited(self):
pass
def test_format_exception_only(self):
pass
def test_print_exception(self):
pass
| 12 | 0 | 6 | 0 | 6 | 0 | 1 | 0 | 1 | 2 | 0 | 0 | 11 | 1 | 11 | 89 | 73 | 11 | 62 | 29 | 50 | 0 | 60 | 29 | 48 | 2 | 3 | 1 | 13 |
136 |
0compute/xtraceback
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/0compute_xtraceback/xtraceback/lexer.py
|
xtraceback.lexer.XPythonLexer
|
class XPythonLexer(PythonLexer):
tokens = PythonLexer.tokens.copy()
tokens["classname"] = [
("'?[a-zA-Z_][a-zA-Z0-9_.]*'?", Name.Class, "#pop")
]
# Marker __repr__
ref = r"(<ref offset)(=)(\-\d+)( ?)((?:name)?)(=?)((?:%s)?)(>?)" \
% BASE_NAME
tokens["root"].insert(0, (ref, bygroups(Name.Builtin, Name.Operator,
Number, Text, Name.Builtin,
Name.Operator, Name.Variable,
Name.Builtin)))
|
class XPythonLexer(PythonLexer):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0.18 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 32 | 15 | 3 | 11 | 3 | 10 | 2 | 5 | 3 | 4 | 0 | 6 | 0 | 0 |
137 |
0compute/xtraceback
|
0compute_xtraceback/xtraceback/test/test_tracebackinterface.py
|
xtraceback.test.test_tracebackinterface.TestTracebackInterface
|
class TestTracebackInterface(XTracebackStdlibTestCase):
def test_format_tb(self):
self.assertTrue(hasattr(self.compat, "format_tb"))
with self.compat:
tb = self._get_exc_info(EXTENDED_TEST)[2]
lines = traceback.format_tb(tb)
self.assertEqual(traceback.format_tb(tb), lines)
def test_print_tb(self):
self.assertTrue(hasattr(self.compat, "print_tb"))
with self.compat:
tb = self._get_exc_info(EXTENDED_TEST)[2]
stream = self.StringIO()
traceback.print_tb(tb, file=stream)
exc_str = stream.getvalue()
stream = self.StringIO()
traceback.print_tb(tb, file=stream)
stdlib_exc_str = stream.getvalue()
self.assertEqual(stdlib_exc_str, exc_str)
def test_print_tb_no_file(self):
stderr = sys.stderr
stream = self.StringIO()
sys.stderr = stream
try:
tb = self._get_exc_info(EXTENDED_TEST)[2]
with self.compat: # pragma: no cover - coverage does not see this
traceback.print_tb(tb)
exc_str = stream.getvalue()
stream = self.StringIO()
sys.stderr = stream
traceback.print_tb(tb)
stdlib_exc_str = stream.getvalue()
self.assertEqual(stdlib_exc_str, exc_str)
finally:
sys.stderr = stderr
def test_format_exception_only(self):
self.assertTrue(hasattr(self.compat, "format_exception_only"))
with self.compat:
etype, value = self._get_exc_info(EXTENDED_TEST)[:-1]
lines = traceback.format_exception_only(etype, value)
self.assertEqual(traceback.format_exception_only(etype, value), lines)
def test_format_exception(self):
self.assertTrue(hasattr(self.compat, "format_exception"))
with self.compat:
exc_info = self._get_exc_info(EXTENDED_TEST)
lines = traceback.format_exception(*exc_info)
self.assertEqual(traceback.format_exception(*exc_info), lines)
def test_print_exception(self):
self.assertTrue(hasattr(self.compat, "print_exception"))
exc_info = self._get_exc_info(EXTENDED_TEST)
with self.compat:
stream = self.StringIO()
traceback.print_exception(*exc_info, **dict(file=stream))
exc_str = stream.getvalue()
stream = self.StringIO()
traceback.print_exception(*exc_info, **dict(file=stream))
stdlib_exc_str = stream.getvalue()
self.assertEqual(stdlib_exc_str, exc_str)
def _get_format_exc_lines(self):
try:
exec(EXTENDED_TEST, {})
except:
return traceback.format_exc()
else:
self.fail("Should have raised exception")
def test_format_exc(self):
stdlib_lines = self._get_format_exc_lines()
with self.compat:
lines = self._get_format_exc_lines()
self.assertEqual(stdlib_lines, lines)
def _get_print_exc_str(self):
stream = self.StringIO()
try:
exec(EXTENDED_TEST, {})
except:
traceback.print_exc(file=stream)
else:
self.fail("Should have raised exception")
return stream.getvalue()
def test_print_exc(self):
self.assertTrue(hasattr(self.compat, "print_exc"))
stdlib_exc_str = self._get_print_exc_str()
with self.compat:
exc_str = self._get_print_exc_str()
self.assertEqual(stdlib_exc_str, exc_str)
|
class TestTracebackInterface(XTracebackStdlibTestCase):
def test_format_tb(self):
pass
def test_print_tb(self):
pass
def test_print_tb_no_file(self):
pass
def test_format_exception_only(self):
pass
def test_format_exception_only(self):
pass
def test_print_exception(self):
pass
def _get_format_exc_lines(self):
pass
def test_format_exception_only(self):
pass
def _get_print_exc_str(self):
pass
def test_print_exception(self):
pass
| 11 | 0 | 8 | 0 | 8 | 0 | 1 | 0.01 | 1 | 1 | 0 | 0 | 10 | 0 | 10 | 89 | 94 | 10 | 84 | 35 | 73 | 1 | 83 | 35 | 72 | 2 | 4 | 2 | 12 |
138 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.3.0/test/test_traceback.py
|
test.test_traceback.BaseExceptionReportingTests
|
class BaseExceptionReportingTests:
def get_exception(self, exception_or_callable):
if isinstance(exception_or_callable, Exception):
return exception_or_callable
try:
exception_or_callable()
except Exception as e:
return e
def zero_div(self):
1/0 # In zero_div
def check_zero_div(self, msg):
lines = msg.splitlines()
self.assertTrue(lines[-3].startswith(' File'))
self.assertIn('1/0 # In zero_div', lines[-2])
self.assertTrue(lines[-1].startswith('ZeroDivisionError'), lines[-1])
def test_simple(self):
try:
1/0 # Marker
except ZeroDivisionError as _:
e = _
lines = self.get_report(e).splitlines()
self.assertEqual(len(lines), 4)
self.assertTrue(lines[0].startswith('Traceback'))
self.assertTrue(lines[1].startswith(' File'))
self.assertIn('1/0 # Marker', lines[2])
self.assertTrue(lines[3].startswith('ZeroDivisionError'))
def test_cause(self):
def inner_raise():
try:
self.zero_div()
except ZeroDivisionError as e:
raise KeyError from e
def outer_raise():
inner_raise() # Marker
blocks = boundaries.split(self.get_report(outer_raise))
self.assertEqual(len(blocks), 3)
self.assertEqual(blocks[1], cause_message)
self.check_zero_div(blocks[0])
self.assertIn('inner_raise() # Marker', blocks[2])
def test_context(self):
def inner_raise():
try:
self.zero_div()
except ZeroDivisionError:
raise KeyError
def outer_raise():
inner_raise() # Marker
blocks = boundaries.split(self.get_report(outer_raise))
self.assertEqual(len(blocks), 3)
self.assertEqual(blocks[1], context_message)
self.check_zero_div(blocks[0])
self.assertIn('inner_raise() # Marker', blocks[2])
def test_context_suppression(self):
try:
try:
raise Exception
except:
raise ZeroDivisionError from None
except ZeroDivisionError as _:
e = _
lines = self.get_report(e).splitlines()
self.assertEqual(len(lines), 4)
self.assertTrue(lines[0].startswith('Traceback'))
self.assertTrue(lines[1].startswith(' File'))
self.assertIn('ZeroDivisionError from None', lines[2])
self.assertTrue(lines[3].startswith('ZeroDivisionError'))
def test_cause_and_context(self):
# When both a cause and a context are set, only the cause should be
# displayed and the context should be muted.
def inner_raise():
try:
self.zero_div()
except ZeroDivisionError as _e:
e = _e
try:
xyzzy
except NameError:
raise KeyError from e
def outer_raise():
inner_raise() # Marker
blocks = boundaries.split(self.get_report(outer_raise))
self.assertEqual(len(blocks), 3)
self.assertEqual(blocks[1], cause_message)
self.check_zero_div(blocks[0])
self.assertIn('inner_raise() # Marker', blocks[2])
def test_cause_recursive(self):
def inner_raise():
try:
try:
self.zero_div()
except ZeroDivisionError as e:
z = e
raise KeyError from e
except KeyError as e:
raise z from e
def outer_raise():
inner_raise() # Marker
blocks = boundaries.split(self.get_report(outer_raise))
self.assertEqual(len(blocks), 3)
self.assertEqual(blocks[1], cause_message)
# The first block is the KeyError raised from the ZeroDivisionError
self.assertIn('raise KeyError from e', blocks[0])
self.assertNotIn('1/0', blocks[0])
# The second block (apart from the boundary) is the ZeroDivisionError
# re-raised from the KeyError
self.assertIn('inner_raise() # Marker', blocks[2])
self.check_zero_div(blocks[2])
def test_syntax_error_offset_at_eol(self):
# See #10186.
def e():
raise SyntaxError('', ('', 0, 5, 'hello'))
msg = self.get_report(e).splitlines()
self.assertEqual(msg[-2], " ^")
def e():
exec("x = 5 | 4 |")
msg = self.get_report(e).splitlines()
self.assertEqual(msg[-2], ' ^')
|
class BaseExceptionReportingTests:
def get_exception(self, exception_or_callable):
pass
def zero_div(self):
pass
def check_zero_div(self, msg):
pass
def test_simple(self):
pass
def test_cause(self):
pass
def inner_raise():
pass
def outer_raise():
pass
def test_context(self):
pass
def inner_raise():
pass
def outer_raise():
pass
def test_context_suppression(self):
pass
def test_cause_and_context(self):
pass
def inner_raise():
pass
def outer_raise():
pass
def test_cause_recursive(self):
pass
def inner_raise():
pass
def outer_raise():
pass
def test_syntax_error_offset_at_eol(self):
pass
def e():
pass
def e():
pass
| 21 | 0 | 8 | 0 | 8 | 1 | 2 | 0.16 | 0 | 5 | 0 | 2 | 10 | 0 | 10 | 10 | 127 | 10 | 111 | 39 | 90 | 18 | 111 | 33 | 90 | 3 | 0 | 2 | 31 |
139 |
0compute/xtraceback
|
0compute_xtraceback/xtraceback/test/test_xtracebackoptions.py
|
xtraceback.test.test_xtracebackoptions.TestXTracebackOptions
|
class TestXTracebackOptions(XTracebackTestCase):
def test_unsupported_options(self):
self.assertRaises(TypeError, XTracebackOptions, bad_option=True)
|
class TestXTracebackOptions(XTracebackTestCase):
def test_unsupported_options(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 2 | 1 | 0 | 1 | 0 | 1 | 79 | 4 | 1 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 3 | 0 | 1 |
140 |
0compute/xtraceback
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/0compute_xtraceback/xtraceback/test/test_formatting.py
|
xtraceback.test.test_formatting.TestFormatting.test_format_long_repr.X
|
class X(object):
def __repr__(self):
return "<" + "x" * DEFAULT_WIDTH + ">"
|
class X(object):
def __repr__(self):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
141 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.3.0/test/test_traceback.py
|
test.test_traceback.CExcReportingTests
|
class CExcReportingTests(BaseExceptionReportingTests, unittest.TestCase):
#
# This checks built-in reporting by the interpreter.
#
def get_report(self, e):
e = self.get_exception(e)
with captured_output("stderr") as s:
exception_print(e)
return s.getvalue()
|
class CExcReportingTests(BaseExceptionReportingTests, unittest.TestCase):
def get_report(self, e):
pass
| 2 | 0 | 5 | 0 | 5 | 0 | 1 | 0.5 | 2 | 0 | 0 | 0 | 1 | 0 | 1 | 82 | 10 | 1 | 6 | 3 | 4 | 3 | 6 | 2 | 4 | 1 | 2 | 1 | 1 |
142 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.3.0/test/test_traceback.py
|
test.test_traceback.CExcReportingTests
|
class CExcReportingTests(BaseExceptionReportingTests, unittest.TestCase):
#
# This checks built-in reporting by the interpreter.
#
def get_report(self, e):
e = self.get_exception(e)
with captured_output("stderr") as s:
exception_print(e)
return s.getvalue()
|
class CExcReportingTests(BaseExceptionReportingTests, unittest.TestCase):
def get_report(self, e):
pass
| 2 | 0 | 5 | 0 | 5 | 0 | 1 | 0.5 | 2 | 0 | 0 | 0 | 1 | 0 | 1 | 82 | 10 | 1 | 6 | 3 | 4 | 3 | 6 | 2 | 4 | 1 | 2 | 1 | 1 |
143 |
0compute/xtraceback
|
0compute_xtraceback/test_support/python/3.3.0/test/test_traceback.py
|
test.test_traceback.CExcReportingTests
|
class CExcReportingTests(BaseExceptionReportingTests, unittest.TestCase):
#
# This checks built-in reporting by the interpreter.
#
def get_report(self, e):
e = self.get_exception(e)
with captured_output("stderr") as s:
exception_print(e)
return s.getvalue()
|
class CExcReportingTests(BaseExceptionReportingTests, unittest.TestCase):
def get_report(self, e):
pass
| 2 | 0 | 5 | 0 | 5 | 0 | 1 | 0.5 | 2 | 0 | 0 | 0 | 1 | 0 | 1 | 83 | 10 | 1 | 6 | 3 | 4 | 3 | 6 | 2 | 4 | 1 | 2 | 1 | 1 |
144 |
0compute/xtraceback
|
0compute_xtraceback/xtraceback/xtracebackframe.py
|
xtraceback.xtracebackframe.XTracebackFrame
|
class XTracebackFrame(object):
FILTER = ("__builtins__", "__all__", "__doc__", "__file__", "__name__",
"__package__", "__path__", "__loader__", "__cached__",
"__initializing__")
FUNCTION_EXCLUDE = ("GeneratorContextManager.__exit__",)
GLOBALS_PREFIX = "g:"
def __init__(self, exc, frame, frame_info, tb_index):
self.exc = exc
self.frame = frame
self.frame_info = frame_info
self.tb_index = tb_index
# shortcuts
self.xtb = exc.xtb
self.options = self.xtb.options
# filter variables
self.locals = self._filter(frame.f_locals)
self.globals = self._filter(frame.f_globals)
# filter out globals that are not under the namespace in
# globals_module_include if the option is not None
if self.options.globals_module_include is not None:
for key, value in self.globals.items():
if isinstance(value, types.ModuleType):
module = value.__name__
elif isinstance(value, types.InstanceType):
module = value.__class__.__module__
else:
module = getattr(value, "__module__", None)
if (module is not None
and not module.startswith(
self.options.globals_module_include)):
del self.globals[key]
# frame details
(self.filename, self.lineno, self.function,
self.code_context, self.index) = frame_info
self.args, self.varargs, self.varkw = inspect.getargs(frame.f_code)
# keep track of what we've formatted in this frame
self._formatted_vars = {}
# placeholder for formatted frame string
self._formatted = None
# if path is a real path then try to shorten it
if os.path.exists(self.filename):
self.filename = format_filename(self.options, self.filename)
# qualify method name with class name
if self.options.qualify_methods and self.args:
try:
cls = self.frame.f_locals[self.args[0]]
except KeyError: # pragma: no cover - defensive
# we're assuming that the first argument is in f_locals but
# it may not be in some cases so this is a defence, see
# https://github.com/0compute/xtraceback/issues/3 with further
# detail at http://www.sqlalchemy.org/trac/ticket/2317 and
# https://dev.entrouvert.org/issues/765
pass
except TypeError: # pragma: no cover - defensive
# if self.args[0] is a list it is not hashable -
# inspect.getargs may return nested lists for args
pass
else:
if not isinstance(cls, type):
cls = type(cls)
if hasattr(cls, self.function):
for base in inspect.getmro(cls):
if self.function in base.__dict__:
self.function = base.__name__ + "." + self.function
break
@property
def exclude(self):
return self.locals.get("__xtraceback_skip_frame__", False) \
or self.function in self.FUNCTION_EXCLUDE
def _filter(self, fdict):
try:
fdict = fdict.copy()
except NotImplementedError:
# user data types inheriting dict may not have implemented copy
pass
else:
to_remove = []
for key, value in fdict.items():
try:
if key in self.FILTER:
to_remove.append(key)
continue
except:
exc_info = sys.exc_info()
# the comparison failed for an unknown reason likely a
# custom __cmp__ that makes bad assumptions - swallow
try:
warnings.warn("Could not filter %r: %r"
% (key, exc_info[1]))
except:
warnings.warn("Could not filter and can't say why: %s"
% exc_info[1])
continue
else:
if isinstance(value, types.ModuleType):
value = ModuleShim(self.options, value)
elif isinstance(value, dict):
value = self._filter(value)
fdict[key] = value
for key in to_remove:
del fdict[key]
return fdict
def _format_variable(self, lines, key, value, indent=4, prefix=""):
if value is not self._formatted_vars.get(key):
self._formatted_vars[key] = value
if self.globals.get(key) is value:
prefix = self.GLOBALS_PREFIX + prefix
lines.append(format_variable(key, value, indent, prefix))
def _format_dict(self, odict, indent=4):
lines = []
for key in sorted(odict.keys()):
self._format_variable(lines, key, odict[key], indent)
return lines
def _format_frame(self):
lines = [' File "%s", line %d, in %s'
% (self.filename, self.lineno, self.function)]
# push frame args
if self.options.show_args:
for arg in self.args:
if isinstance(arg, list):
# TODO: inspect.getargs arg list may contain nested
# lists; skip it for now
continue
self._format_variable(lines, arg, self.locals.get(arg))
if self.varargs:
self._format_variable(
lines, self.varargs, self.locals.get(self.varargs),
prefix="*")
if self.varkw:
self._format_variable(lines, self.varkw,
self.locals.get(self.varkw), prefix="**")
# push globals
if self.options.show_globals:
lines.extend(self._format_dict(self.globals))
# push context lines
if self.code_context is not None:
lineno = self.lineno - self.index
dedented = textwrap.dedent("".join(self.code_context))
for line in dedented.splitlines():
numbered_line = " %s" % "%*s %s" \
% (self.xtb.number_padding, lineno, line)
if lineno == self.lineno:
if self.options.context > 1:
# push the numbered line with a marker
dedented_line = numbered_line.lstrip()
marker_padding = len(numbered_line) \
- len(dedented_line) - 2
lines.append("%s> %s" % ("-" * marker_padding,
dedented_line))
else:
# push the line only
lines.append(" " + line)
# push locals below lined up with the start of code
if self.options.show_locals:
indent = self.xtb.number_padding + len(line) \
- len(line.lstrip()) + 5
lines.extend(self._format_dict(self.locals, indent))
else:
# push the numbered line
lines.append(numbered_line)
lineno += 1
elif self.options.show_locals:
# no context so we are execing
lines.extend(self._format_dict(self.locals))
return "\n".join(lines)
def __str__(self):
if self._formatted is None:
self._formatted = self._format_frame()
return self._formatted
|
class XTracebackFrame(object):
def __init__(self, exc, frame, frame_info, tb_index):
pass
@property
def exclude(self):
pass
def _filter(self, fdict):
pass
def _format_variable(self, lines, key, value, indent=4, prefix=""):
pass
def _format_dict(self, odict, indent=4):
pass
def _format_frame(self):
pass
def __str__(self):
pass
| 9 | 0 | 27 | 3 | 19 | 4 | 6 | 0.22 | 1 | 7 | 1 | 0 | 7 | 18 | 7 | 7 | 203 | 34 | 140 | 43 | 131 | 31 | 117 | 41 | 109 | 14 | 1 | 5 | 44 |
145 |
0compute/xtraceback
|
0compute_xtraceback/xtraceback/xtracebackexc.py
|
xtraceback.xtracebackexc.XTracebackExc
|
class XTracebackExc(object):
def __init__(self, etype, value, tb, xtb):
"""
:param value: The exception instance
:type value: Exception
:param tb: The traceback instance
:type tb: traceback
:param xtb: the xtraceback instance
:type xtb: XTraceback
"""
self.etype = etype
#: The exception instance
self.value = value
#: The XTraceback instance
self.xtb = xtb
#: Used in XTracebackFrame to determine indent
self.number_padding = 0
#: List of XTracebackFrame
self.frames = []
i = 0
while tb is not None and (self.xtb.options.limit is None
or i < self.xtb.options.limit):
if i >= self.xtb.options.offset:
try:
frame_info = inspect.getframeinfo(tb,
self.xtb.options.context)
except KeyError: # pragma: no cover - defensive
# <stdlib>/inspect.py line 506 - there may be no __main__
# XXX: This can't be right - frame_info needs to be defined
# in order to construct the XTracebackFrame below.
pass
frame = XTracebackFrame(self, tb.tb_frame, frame_info, i)
if not frame.exclude:
self.frames.append(frame)
self.number_padding = max(len(str(frame.lineno)),
self.number_padding)
tb = tb.tb_next
i += 1
# { Traceback format - these return lines that should be joined with ""
def format_tb(self):
return ["%s\n" % frame for frame in self.frames]
def format_exception_only(self):
lines = []
if self.value is None:
value_str = ""
elif isinstance(self.value, SyntaxError):
# taken from traceback.format_exception_only
try:
msg, (filename, lineno, offset, badline) = self.value.args
except:
pass
else:
filename = filename and format_filename(self.xtb.options,
filename) or "<string>"
filename = filename or "<string>"
lines.append(' File "%s", line %d\n' % (filename, lineno))
if badline is not None:
lines.append(' %s\n' % badline.strip())
if offset is not None:
caretspace = badline.rstrip('\n')[:offset].lstrip()
# non-space whitespace (likes tabs) must be kept for
# alignment
caretspace = ((c.isspace() and c or ' ')
for c in caretspace)
# only three spaces to account for offset1 == pos 0
lines.append(' %s^\n' % ''.join(caretspace))
value_str = msg
else:
try:
value_str = str(self.value)
except Exception:
try:
value_str = unicode(self.value).encode("ascii",
"backslashreplace")
except Exception:
value_str = "<unprintable %s object>" \
% type(self.value).__name__
# format last line
if isinstance(self.etype, type):
stype = self.etype.__name__
# not using namedtuple to get major version as this is for >= py27
if sys.version_info[0] == 3:
# python 3 uses fully-qualified names
smod = self.etype.__module__
if smod not in ("__main__", "builtins"):
stype = smod + '.' + stype
else:
stype = str(self.etype)
lines.append("%s%s\n" % (stype,
value_str and ": %s" % value_str or ""))
return lines
def format_exception(self):
lines = list(self.format_tb())
if lines:
lines.insert(0, "Traceback (most recent call last):\n")
lines.extend(self.format_exception_only())
return lines
|
class XTracebackExc(object):
def __init__(self, etype, value, tb, xtb):
'''
:param value: The exception instance
:type value: Exception
:param tb: The traceback instance
:type tb: traceback
:param xtb: the xtraceback instance
:type xtb: XTraceback
'''
pass
def format_tb(self):
pass
def format_exception_only(self):
pass
def format_exception_only(self):
pass
| 5 | 1 | 26 | 3 | 18 | 6 | 5 | 0.32 | 1 | 7 | 1 | 0 | 4 | 5 | 4 | 4 | 112 | 15 | 74 | 20 | 69 | 24 | 63 | 20 | 58 | 11 | 1 | 4 | 19 |
146 |
0compute/xtraceback
|
0compute_xtraceback/xtraceback/test/test_xtraceback.py
|
xtraceback.test.test_xtraceback.TestXTraceback
|
class TestXTraceback(XTracebackTestCase):
def test_simple(self):
self._check_tb_str(config.BASIC_TEST, config.SIMPLE_EXCEPTION)
def test_simple_str(self):
exc_info = self._get_exc_info(config.BASIC_TEST)
xtb = self._factory(*exc_info)
self._assert_tb_str(str(xtb), config.SIMPLE_EXCEPTION)
@skipIfNoPygments
def test_simple_str_color(self):
exc_info = self._get_exc_info(config.BASIC_TEST)
xtb = self._factory(*exc_info, **dict(color=True))
self._assert_tb_str("".join(xtb.format_exception()),
config.SIMPLE_EXCEPTION_COLOR)
def test_simple_no_tb(self):
etype, value = self._get_exc_info(config.BASIC_TEST)[:-1]
xtb = self._factory(etype, value, None)
self._assert_tb_str(str(xtb), config.SIMPLE_EXCEPTION_NO_TB)
def test_with_globals(self):
self._check_tb_str(config.BASIC_TEST, config.WITH_GLOBALS_EXCEPTION,
one=1)
def test_with_show_globals(self):
exc_info = self._get_exc_info(config.BASIC_TEST, one=1)
xtb = self._factory(show_globals=True, *exc_info)
self._assert_tb_str(str(xtb), config.WITH_SHOW_GLOBALS_EXCEPTION)
def test_extended(self):
exc_info = self._get_exc_info(config.EXTENDED_TEST,
Thing=thing.Thing)
xtb = self._factory(show_globals=True, *exc_info)
self._assert_tb_str(str(xtb), config.EXTENDED_EXCEPTION)
def test_syntax(self):
self._check_tb_str(config.SYNTAX_TEST, config.SYNTAX_EXCEPTION)
def test_print_width_fixed(self):
print_width = 100
xtb = self._factory(None, None, None, print_width=print_width)
self.assertEqual(xtb.print_width, print_width)
|
class TestXTraceback(XTracebackTestCase):
def test_simple(self):
pass
def test_simple_str(self):
pass
@skipIfNoPygments
def test_simple_str_color(self):
pass
def test_simple_no_tb(self):
pass
def test_with_globals(self):
pass
def test_with_show_globals(self):
pass
def test_extended(self):
pass
def test_syntax(self):
pass
def test_print_width_fixed(self):
pass
| 11 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 3 | 1 | 0 | 9 | 0 | 9 | 87 | 44 | 9 | 35 | 23 | 24 | 0 | 31 | 22 | 21 | 1 | 3 | 0 | 9 |
147 |
0compute/xtraceback
|
0compute_xtraceback/xtraceback/xtraceback.py
|
xtraceback.xtraceback.XTraceback
|
class XTraceback(object):
"""
An extended traceback formatter
"""
def __init__(self, etype, value, tb, **options):
"""
:param etype: The exception type
:type etype: type
:param value: The exception instance
:type value: Exception
:param tb: The traceback instance
:type tb: traceback
:param options: Options for this instance
:type options: dict
"""
#: Options for xtraceback
self.options = XTracebackOptions(**options)
#: The exception type
self.etype = etype
#: The exception value (instance)
self.value = value
#: The list of exceptions and tracebacks
if self.options.chain and self.value is not None \
and hasattr(traceback, "_iter_chain"):
# python 3
values = list(traceback._iter_chain(value, tb))
# traceback._iter_chain pulls tb from the exception instance and so
# does not use the tb argument to this method for the last (root)
# exception; normally this would not matter as the two are the same
# but it falls over when tb is None so we replace the last tb in
# the values list with tb from args
values[-1] = (values[-1][0], tb)
else:
values = [(value, tb)]
#: Used in XTracebackFrame to determine indent
self.number_padding = 0
# build list of exceptions
self.exceptions = []
for value, tb in values:
if not isinstance(self.etype, basestring) \
and isinstance(value, basestring):
exc_type = value
value = None
else:
exc_type = etype if value == self.value else type(value)
exc = XTracebackExc(exc_type, value, tb, self)
self.exceptions.append(exc)
self.number_padding = max(exc.number_padding, self.number_padding)
# placeholders
self._lexer = None
self._formatter = None
# work out print width
if self.options.print_width is not None:
self.print_width = self.options.print_width
elif fcntl is not None and self.tty_stream:
self.print_width = struct.unpack(
'HHHH',
fcntl.ioctl(self.options.stream,
termios.TIOCGWINSZ,
struct.pack('HHHH', 0, 0, 0, 0)),
)[1]
else:
self.print_width = DEFAULT_WIDTH
@property
def tty_stream(self):
"""
Whether or not our stream is a tty
"""
return hasattr(self.options.stream, "isatty") \
and self.options.stream.isatty()
@property
def color(self):
"""
Whether or not color should be output
"""
return self.tty_stream if self.options.color is None \
else self.options.color
def __str__(self):
return self._str_lines(self._format_exception())
# { Line formatting
def _highlight(self, string):
if pygments is None:
warnings.warn("highlighting not available - pygments is required")
else:
if self._lexer is None:
self._lexer = PythonXTracebackLexer()
if self._formatter is None:
# passing style=default here is the same as passing no
# arguments - the reason for doing it is that if we don't the
# style gets imported at runtime which under some restricted
# environments (appengine) causes a problem - all of the
# imports must be done before appengine installs its import
# hook
self._formatter = TerminalFormatter(style=default)
try:
return pygments.highlight(string, self._lexer, self._formatter)
except KeyboardInterrupt:
# let the user abort highlighting if problematic
pass
return string
def _str_lines(self, lines):
exc_str = "".join(lines)
if self.color:
exc_str = self._highlight(exc_str)
return exc_str
def _format_lines(self, lines):
# XXX: This is doing the highlight line by line
return map(self._highlight, lines) if self.color else lines
def _print_lines(self, lines):
if self.options.stream is None:
raise RuntimeError("Cannot print - %r has None stream" % self)
self.options.stream.write(self._str_lines(lines))
# { Traceback format - these return lines terminated with "\n"
def _format_tb(self):
lines = []
for exc in self.exceptions:
lines.extend(exc.format_tb())
return lines
def _format_exception_only(self):
return self.exceptions[-1].format_exception_only()
def _format_exception(self):
lines = []
for exc in self.exceptions:
lines.extend(exc.format_exception())
return lines
# { Interface - this is compatible with the stdlib's traceback module
def format_tb(self):
return self._format_lines(self._format_tb())
def format_exception_only(self):
return self._format_lines(self._format_exception_only())
def format_exception(self):
return self._format_lines(self._format_exception())
def print_tb(self):
self._print_lines(self._format_tb())
def print_exception(self):
self._print_lines(self._format_exception())
|
class XTraceback(object):
'''
An extended traceback formatter
'''
def __init__(self, etype, value, tb, **options):
'''
:param etype: The exception type
:type etype: type
:param value: The exception instance
:type value: Exception
:param tb: The traceback instance
:type tb: traceback
:param options: Options for this instance
:type options: dict
'''
pass
@property
def tty_stream(self):
'''
Whether or not our stream is a tty
'''
pass
@property
def color(self):
'''
Whether or not color should be output
'''
pass
def __str__(self):
pass
def _highlight(self, string):
pass
def _str_lines(self, lines):
pass
def _format_lines(self, lines):
pass
def _print_lines(self, lines):
pass
def _format_tb(self):
pass
def _format_exception_only(self):
pass
def _format_exception_only(self):
pass
def format_tb(self):
pass
def format_exception_only(self):
pass
def format_exception_only(self):
pass
def print_tb(self):
pass
def print_exception(self):
pass
| 19 | 4 | 8 | 1 | 6 | 2 | 2 | 0.48 | 1 | 9 | 3 | 0 | 16 | 8 | 16 | 16 | 164 | 28 | 92 | 35 | 73 | 44 | 76 | 33 | 59 | 7 | 1 | 2 | 32 |
148 |
0compute/xtraceback
|
0compute_xtraceback/xtraceback/test/thing.py
|
xtraceback.test.thing.Thing
|
class Thing(object):
def one(self):
sugar = max(1, 2)
self.two(sugar)
def two(self, sugar):
long = "y" * 67
obj = Other()
obj.one(long)
|
class Thing(object):
def one(self):
pass
def two(self, sugar):
pass
| 3 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 2 | 0 | 2 | 2 | 10 | 2 | 8 | 6 | 5 | 0 | 8 | 6 | 5 | 1 | 1 | 0 | 2 |
149 |
0k/kids.cmd
|
0k_kids.cmd/src/kids/cmd/cmd.py
|
kids.cmd.cmd.BaseCommand
|
class BaseCommand(object):
__version__ = "0.0.1"
@property
@cache
def local_path(self):
return False
@cache
@property
def cfg(self): ## shortcut
if self.local_path:
return kids.cfg.load(local_path=self.local_path)
else:
return kids.cfg.load()
def __call__(self, arguments):
return run(self, arguments)
|
class BaseCommand(object):
@property
@cache
def local_path(self):
pass
@cache
@property
def cfg(self):
pass
def __call__(self, arguments):
pass
| 8 | 0 | 3 | 0 | 3 | 0 | 1 | 0.07 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 19 | 4 | 15 | 7 | 7 | 1 | 10 | 5 | 6 | 2 | 1 | 1 | 4 |
150 |
0k/shyaml
|
0k_shyaml/shyaml.py
|
shyaml.InvalidAction
|
class InvalidAction(KeyError):
"""Invalid Action"""
|
class InvalidAction(KeyError):
'''Invalid Action'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 13 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 5 | 0 | 0 |
151 |
0k/shyaml
|
0k_shyaml/shyaml.py
|
shyaml.InvalidPath
|
class InvalidPath(KeyError):
"""Invalid Path"""
def __str__(self):
return self.args[0]
|
class InvalidPath(KeyError):
'''Invalid Path'''
def __str__(self):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.33 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 14 | 5 | 1 | 3 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 5 | 0 | 1 |
152 |
0k/shyaml
|
0k_shyaml/shyaml.py
|
shyaml.LineLoader
|
class LineLoader(ShyamlSafeLoader):
"""Forcing stream in line buffer mode"""
def __init__(self, stream):
stream = ForcedLineStream(stream)
super(LineLoader, self).__init__(stream)
|
class LineLoader(ShyamlSafeLoader):
'''Forcing stream in line buffer mode'''
def __init__(self, stream):
pass
| 2 | 1 | 3 | 0 | 3 | 0 | 1 | 0.25 | 1 | 2 | 1 | 0 | 1 | 0 | 1 | 39 | 6 | 1 | 4 | 2 | 2 | 1 | 4 | 2 | 2 | 1 | 4 | 0 | 1 |
153 |
0k/shyaml
|
0k_shyaml/shyaml.py
|
shyaml.MissingKeyError
|
class MissingKeyError(KeyError):
"""Raised when querying a dict-like structure on non-existing keys"""
def __str__(self):
return self.args[0]
|
class MissingKeyError(KeyError):
'''Raised when querying a dict-like structure on non-existing keys'''
def __str__(self):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.33 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 14 | 5 | 1 | 3 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 5 | 0 | 1 |
154 |
0k/shyaml
|
0k_shyaml/shyaml.py
|
shyaml.NonDictLikeTypeError
|
class NonDictLikeTypeError(TypeError):
"""Raised when attempting to traverse non-dict like structure"""
|
class NonDictLikeTypeError(TypeError):
'''Raised when attempting to traverse non-dict like structure'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
155 |
0k/shyaml
|
0k_shyaml/shyaml.py
|
shyaml.ShyamlSafeDumper
|
class ShyamlSafeDumper(SafeDumper):
"""Shyaml specific safe dumper"""
|
class ShyamlSafeDumper(SafeDumper):
'''Shyaml specific safe dumper'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 31 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
156 |
0k/shyaml
|
0k_shyaml/shyaml.py
|
shyaml.ShyamlSafeLoader
|
class ShyamlSafeLoader(SafeLoader):
"""Shyaml specific safe loader"""
|
class ShyamlSafeLoader(SafeLoader):
'''Shyaml specific safe loader'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 38 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
157 |
0k/shyaml
|
0k_shyaml/shyaml.py
|
shyaml.ForcedLineStream
|
class ForcedLineStream(object):
def __init__(self, fileobj):
self._file = fileobj
def read(self, size=-1):
## don't care about size
return self._file.readline()
def close(self):
## XXXvlab: for some reason, ``.close(..)`` doesn't seem to
## be used by any code. I'll keep this to avoid any bad surprise.
return self._file.close()
|
class ForcedLineStream(object):
def __init__(self, fileobj):
pass
def read(self, size=-1):
pass
def close(self):
pass
| 4 | 0 | 3 | 0 | 2 | 1 | 1 | 0.57 | 1 | 0 | 0 | 0 | 3 | 1 | 3 | 3 | 13 | 3 | 7 | 5 | 3 | 4 | 7 | 5 | 3 | 1 | 1 | 0 | 3 |
158 |
0k/shyaml
|
0k_shyaml/shyaml.py
|
shyaml.EncapsulatedNode
|
class EncapsulatedNode(object):
"""Holds a yaml node"""
|
class EncapsulatedNode(object):
'''Holds a yaml node'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 0 |
159 |
0k/shyaml
|
0k_shyaml/shyaml.py
|
shyaml.ActionTypeError
|
class ActionTypeError(Exception):
def __init__(self, action, provided, expected):
self.action = action
self.provided = provided
self.expected = expected
def __str__(self):
return ("%s does not support %r type. "
"Please provide or select a %s."
% (self.action, self.provided,
self.expected[0] if len(self.expected) == 1 else
("%s or %s" % (", ".join(self.expected[:-1]),
self.expected[-1]))))
|
class ActionTypeError(Exception):
def __init__(self, action, provided, expected):
pass
def __str__(self):
pass
| 3 | 0 | 6 | 0 | 6 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 2 | 3 | 2 | 12 | 14 | 2 | 12 | 6 | 9 | 0 | 7 | 6 | 4 | 2 | 3 | 0 | 3 |
160 |
0k/shyaml
|
0k_shyaml/shyaml.py
|
shyaml.IndexOutOfRange
|
class IndexOutOfRange(IndexError):
"""Raised when attempting to traverse sequence without using an integer"""
|
class IndexOutOfRange(IndexError):
'''Raised when attempting to traverse sequence without using an integer'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 12 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 5 | 0 | 0 |
161 |
0k/shyaml
|
0k_shyaml/shyaml.py
|
shyaml.IndexNotIntegerError
|
class IndexNotIntegerError(ValueError):
"""Raised when attempting to traverse sequence without using an integer"""
|
class IndexNotIntegerError(ValueError):
'''Raised when attempting to traverse sequence without using an integer'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
162 |
0k/shyaml
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/0k_shyaml/shyaml.py
|
shyaml.mk_encapsulated_node._E
|
class _E(data.__class__, EncapsulatedNode):
pass
|
class _E(data.__class__, EncapsulatedNode):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 2 | 0 | 0 |
163 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/generics.py
|
drfaddons.generics.OwnerRetrieveAPIView
|
class OwnerRetrieveAPIView(mixins.RetrieveModelMixin, OwnerGenericAPIView):
"""Concrete view for retrieving a CreateUpdateModel based model instance."""
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
|
class OwnerRetrieveAPIView(mixins.RetrieveModelMixin, OwnerGenericAPIView):
'''Concrete view for retrieving a CreateUpdateModel based model instance.'''
def get(self, request, *args, **kwargs):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.33 | 2 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 5 | 1 | 3 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
164 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/generics.py
|
drfaddons.generics.DestroyByUserAPIView
|
class DestroyByUserAPIView(mixins.DestroyModelMixin, GenericByUserAPIView):
"""
Concrete view for deleting a CreateUpdateModel based model instance
where One-to-One relationship exists on created_by with User.
"""
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
|
class DestroyByUserAPIView(mixins.DestroyModelMixin, GenericByUserAPIView):
'''
Concrete view for deleting a CreateUpdateModel based model instance
where One-to-One relationship exists on created_by with User.
'''
def delete(self, request, *args, **kwargs):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 1.33 | 2 | 0 | 0 | 0 | 1 | 0 | 1 | 2 | 8 | 1 | 3 | 2 | 1 | 4 | 3 | 2 | 1 | 1 | 3 | 0 | 1 |
165 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/generics.py
|
drfaddons.generics.GenericByUserAPIView
|
class GenericByUserAPIView(OwnerGenericAPIView):
"""
Generic view where object is retrieved via logged in user and does
not requires a primary key.
Can be used in models having One-to-One relation with User model.
"""
lookup_field = "created_by"
def get_object(self):
"""Returns the object the view is displaying"""
self.kwargs[self.lookup_field] = self.request.user
return super(GenericByUserAPIView, self).get_object()
|
class GenericByUserAPIView(OwnerGenericAPIView):
'''
Generic view where object is retrieved via logged in user and does
not requires a primary key.
Can be used in models having One-to-One relation with User model.
'''
def get_object(self):
'''Returns the object the view is displaying'''
pass
| 2 | 2 | 4 | 0 | 3 | 1 | 1 | 1.2 | 1 | 1 | 0 | 7 | 1 | 0 | 1 | 1 | 13 | 2 | 5 | 3 | 3 | 6 | 5 | 3 | 3 | 1 | 2 | 0 | 1 |
166 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/generics.py
|
drfaddons.generics.OwnerCreateAPIView
|
class OwnerCreateAPIView(OwnerCreateModelMixin, OwnerGenericAPIView):
"""Concrete view for creating a CreateUpdateModel based model instance."""
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
|
class OwnerCreateAPIView(OwnerCreateModelMixin, OwnerGenericAPIView):
'''Concrete view for creating a CreateUpdateModel based model instance.'''
def post(self, request, *args, **kwargs):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.33 | 2 | 0 | 0 | 0 | 1 | 0 | 1 | 2 | 5 | 1 | 3 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
167 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/generics.py
|
drfaddons.generics.UpdateByUserAPIView
|
class UpdateByUserAPIView(mixins.UpdateModelMixin, GenericByUserAPIView):
"""
Concrete view for updating a CreateUpdateModel based model instance
where One-to-One relationship exists on
created_by with User.
"""
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
return self.partial_update(request, *args, **kwargs)
|
class UpdateByUserAPIView(mixins.UpdateModelMixin, GenericByUserAPIView):
'''
Concrete view for updating a CreateUpdateModel based model instance
where One-to-One relationship exists on
created_by with User.
'''
def put(self, request, *args, **kwargs):
pass
def patch(self, request, *args, **kwargs):
pass
| 3 | 1 | 2 | 0 | 2 | 0 | 1 | 1 | 2 | 0 | 0 | 0 | 2 | 0 | 2 | 3 | 12 | 2 | 5 | 3 | 2 | 5 | 5 | 3 | 2 | 1 | 3 | 0 | 2 |
168 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/generics.py
|
drfaddons.generics.OwnerDestroyAPIView
|
class OwnerDestroyAPIView(mixins.DestroyModelMixin, OwnerGenericAPIView):
"""Concrete view for deleting a CreateUpdateModel based model instance."""
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
|
class OwnerDestroyAPIView(mixins.DestroyModelMixin, OwnerGenericAPIView):
'''Concrete view for deleting a CreateUpdateModel based model instance.'''
def delete(self, request, *args, **kwargs):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.33 | 2 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 5 | 1 | 3 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
169 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/generics.py
|
drfaddons.generics.OwnerListAPIView
|
class OwnerListAPIView(mixins.ListModelMixin, OwnerGenericAPIView):
"""Concrete view for listing a CreateUpdateModel based queryset."""
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
|
class OwnerListAPIView(mixins.ListModelMixin, OwnerGenericAPIView):
'''Concrete view for listing a CreateUpdateModel based queryset.'''
def get(self, request, *args, **kwargs):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.33 | 2 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 5 | 1 | 3 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
170 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/mixins.py
|
drfaddons.mixins.OwnerCreateModelMixin
|
class OwnerCreateModelMixin(CreateModelMixin):
"""
Create a CreateUpdateModel based model instance.
Author: Himanshu Shankar (https://himanshus.com)
"""
def perform_create(self, serializer):
serializer.save(created_by=self.request.user)
|
class OwnerCreateModelMixin(CreateModelMixin):
'''
Create a CreateUpdateModel based model instance.
Author: Himanshu Shankar (https://himanshus.com)
'''
def perform_create(self, serializer):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 1.33 | 1 | 0 | 0 | 3 | 1 | 0 | 1 | 1 | 9 | 2 | 3 | 2 | 1 | 4 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
171 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/models.py
|
drfaddons.models.CreateUpdateModel
|
class CreateUpdateModel(models.Model):
"""
An abstract model that provides 3 field in every inherited model.
create_date: Sets up the create date of any object
update_date: Sets up the last update date of any object
created_by: Sets up the user ID of creator with the object
Author: Himanshu Shankar (https://himanshus.com)
"""
from django.contrib.auth import get_user_model
from django.utils.text import gettext_lazy as _
create_date = models.DateTimeField(_("Create Date/Time"), auto_now_add=True)
update_date = models.DateTimeField(_("Date/Time Modified"), auto_now=True)
created_by = models.ForeignKey(get_user_model(), on_delete=models.PROTECT)
def is_owner(self, user):
"""
Checks if user is the owner of object
Parameters
----------
user: get_user_model() instance
Returns
-------
bool
Author
------
Himanshu Shankar (https://himanshus.com)
"""
if user.is_authenticated:
return self.created_by.id == user.id
return False
def has_permission(self, user):
"""
Checks if the provided user has permission on provided object
Parameters
----------
user: get_user_model() instance
Returns
-------
bool
Author
------
Himanshu Shankar (https://himanshus.com)
"""
return self.is_owner(user)
class Meta:
abstract = True
|
class CreateUpdateModel(models.Model):
'''
An abstract model that provides 3 field in every inherited model.
create_date: Sets up the create date of any object
update_date: Sets up the last update date of any object
created_by: Sets up the user ID of creator with the object
Author: Himanshu Shankar (https://himanshus.com)
'''
def is_owner(self, user):
'''
Checks if user is the owner of object
Parameters
----------
user: get_user_model() instance
Returns
-------
bool
Author
------
Himanshu Shankar (https://himanshus.com)
'''
pass
def has_permission(self, user):
'''
Checks if the provided user has permission on provided object
Parameters
----------
user: get_user_model() instance
Returns
-------
bool
Author
------
Himanshu Shankar (https://himanshus.com)
'''
pass
class Meta:
| 4 | 3 | 18 | 3 | 3 | 12 | 2 | 2.21 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 57 | 12 | 14 | 10 | 8 | 31 | 14 | 10 | 8 | 2 | 1 | 1 | 3 |
172 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/permissions.py
|
drfaddons.permissions.IAWPOrSuperuser
|
class IAWPOrSuperuser(IsAuthenticatedWithPermission):
def has_object_permission(self, request, view, obj):
"""
Checks if user is superuser or it has permission over object
Parameters
----------
request
view
obj
Returns
-------
"""
return request.user.is_superuser or super(
IAWPOrSuperuser, self
).has_object_permission(request=request, view=view, obj=obj)
|
class IAWPOrSuperuser(IsAuthenticatedWithPermission):
def has_object_permission(self, request, view, obj):
'''
Checks if user is superuser or it has permission over object
Parameters
----------
request
view
obj
Returns
-------
'''
pass
| 2 | 1 | 17 | 3 | 4 | 10 | 1 | 2 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 2 | 18 | 3 | 5 | 2 | 3 | 10 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
173 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/permissions.py
|
drfaddons.permissions.IsAuthenticatedWithPermission
|
class IsAuthenticatedWithPermission(IsAuthenticated):
"""
Implements `has_object_permission` to check for object level
permission
Author: Himanshu Shankar (https://himanshus.com)
"""
def has_object_permission(self, request, view, obj):
"""
Checks if `request.user` has permission via
`obj.has_permission()`
Parameters
----------
request
view
obj
Returns
-------
"""
return obj.has_permission(request.user)
|
class IsAuthenticatedWithPermission(IsAuthenticated):
'''
Implements `has_object_permission` to check for object level
permission
Author: Himanshu Shankar (https://himanshus.com)
'''
def has_object_permission(self, request, view, obj):
'''
Checks if `request.user` has permission via
`obj.has_permission()`
Parameters
----------
request
view
obj
Returns
-------
'''
pass
| 2 | 2 | 16 | 3 | 2 | 11 | 1 | 5.33 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | 1 | 24 | 5 | 3 | 2 | 1 | 16 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
174 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/permissions.py
|
drfaddons.permissions.IsOwner
|
class IsOwner(IsAuthenticated):
"""
Implements `has_object_permission` to check for ownership
IsAuthenticated
Author: Himanshu Shankar (https://himanshus.com)
"""
def has_object_permission(self, request, view, obj):
"""
Checks if `request.user` is the owner of `obj`
Parameters
----------
request
view
obj
Returns
-------
bool: True, either if request.user is the creator of object or
if object doesn't have created_by object
False, if object has created_by field but it is not same
as request.user
"""
return obj.is_owner(request.user)
|
class IsOwner(IsAuthenticated):
'''
Implements `has_object_permission` to check for ownership
IsAuthenticated
Author: Himanshu Shankar (https://himanshus.com)
'''
def has_object_permission(self, request, view, obj):
'''
Checks if `request.user` is the owner of `obj`
Parameters
----------
request
view
obj
Returns
-------
bool: True, either if request.user is the creator of object or
if object doesn't have created_by object
False, if object has created_by field but it is not same
as request.user
'''
pass
| 2 | 2 | 18 | 2 | 2 | 14 | 1 | 6.33 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 26 | 4 | 3 | 2 | 1 | 19 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
175 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/serializers.py
|
drfaddons.serializers.ByOwnerSerializer
|
class ByOwnerSerializer(serializers.ModelSerializer):
created_by = serializers.HiddenField(default=serializers.CurrentUserDefault())
def validate(self, attrs):
model = self.Meta.model
if model.objects.filter(created_by=self.context["request"].user).count() > 0:
raise serializers.ValidationError(
detail=_(
"Logged in user already has %s object."
"Can not create another object."
% (model._meta.verbose_name.title())
)
)
return attrs
|
class ByOwnerSerializer(serializers.ModelSerializer):
def validate(self, attrs):
pass
| 2 | 0 | 13 | 2 | 11 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 16 | 3 | 13 | 4 | 11 | 0 | 7 | 4 | 5 | 2 | 1 | 1 | 2 |
176 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/utils.py
|
drfaddons.utils.DateTimeEncoder
|
class DateTimeEncoder(json.JSONEncoder):
"""Date Time Encoder for JSON. I do not use this anymore
Can't identify original source.
Sources: [https://gist.github.com/dannvix/29f53570dfde13f29c35,
https://www.snip2code.com/Snippet/106599/]
"""
def default(self, obj):
if isinstance(obj, datetime):
encoded_object = obj.strftime("%s")
else:
encoded_object = super(self, obj)
return encoded_object
|
class DateTimeEncoder(json.JSONEncoder):
'''Date Time Encoder for JSON. I do not use this anymore
Can't identify original source.
Sources: [https://gist.github.com/dannvix/29f53570dfde13f29c35,
https://www.snip2code.com/Snippet/106599/]
'''
def default(self, obj):
pass
| 2 | 1 | 7 | 1 | 6 | 0 | 2 | 0.71 | 1 | 2 | 0 | 0 | 1 | 0 | 1 | 5 | 14 | 2 | 7 | 3 | 5 | 5 | 6 | 3 | 4 | 2 | 2 | 1 | 2 |
177 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/utils.py
|
drfaddons.utils.JsonResponse
|
class JsonResponse(HttpResponse):
"""
A HttpResponse that responses in JSON. Used in APIs.
Can't identify original source.
Sources: [https://gist.github.com/dannvix/29f53570dfde13f29c35,
https://www.snip2code.com/Snippet/106599/]
"""
def __init__(self, content, status=None, content_type="application/json"):
data = {"data": content, "status_code": status}
json_text = json.dumps(data, default=json_serial)
super(JsonResponse, self).__init__(
content=json_text, status=status, content_type=content_type
)
|
class JsonResponse(HttpResponse):
'''
A HttpResponse that responses in JSON. Used in APIs.
Can't identify original source.
Sources: [https://gist.github.com/dannvix/29f53570dfde13f29c35,
https://www.snip2code.com/Snippet/106599/]
'''
def __init__(self, content, status=None, content_type="application/json"):
pass
| 2 | 1 | 6 | 0 | 6 | 0 | 1 | 0.86 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 14 | 1 | 7 | 4 | 5 | 6 | 5 | 4 | 3 | 1 | 1 | 0 | 1 |
178 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/views.py
|
drfaddons.views.AddObjectView
|
class AddObjectView(ValidateAndPerformView):
"""
Creates or updates an object.
Used in various projects by only specifying a few variables.
Was created by me not knowing about GenericAPIView.
May be labelled as deprecated and get removed in future versions.
Source: Himanshu Shankar (https://github.com/iamhssingh)
"""
from django.views.decorators.csrf import csrf_exempt
from rest_framework.permissions import IsAuthenticated
permission_classes = (IsAuthenticated,)
def validated(self, serialized_data, *args, **kwargs):
from rest_framework import status
serialized_data = self.show_serializer(
serialized_data.save(created_by=self.request.user)
)
return serialized_data.data, status.HTTP_201_CREATED
@csrf_exempt
def post(self, request):
from .utils import JsonResponse
from rest_framework import status
if "id" in request.data.keys():
try:
serialized_data = self.serializer_class(
self.model.objects.get(pk=request.data["id"]), data=request.data
)
except self.model.DoesNotExist:
data = {"id": ["Object with provided ID does not exists"]}
return JsonResponse(data, status=status.HTTP_404_NOT_FOUND)
else:
serialized_data = self.serializer_class(data=request.data)
if serialized_data.is_valid():
data, status_code = self.validated(serialized_data=serialized_data)
return JsonResponse(data, status=status_code)
return JsonResponse(
serialized_data.errors, status=status.HTTP_422_UNPROCESSABLE_ENTITY
)
class Meta:
abstract = True
|
class AddObjectView(ValidateAndPerformView):
'''
Creates or updates an object.
Used in various projects by only specifying a few variables.
Was created by me not knowing about GenericAPIView.
May be labelled as deprecated and get removed in future versions.
Source: Himanshu Shankar (https://github.com/iamhssingh)
'''
def validated(self, serialized_data, *args, **kwargs):
pass
@csrf_exempt
def post(self, request):
pass
class Meta:
| 5 | 1 | 14 | 2 | 13 | 0 | 3 | 0.22 | 1 | 1 | 1 | 0 | 2 | 0 | 2 | 4 | 48 | 9 | 32 | 15 | 22 | 7 | 24 | 14 | 15 | 4 | 2 | 2 | 5 |
179 |
101Loop/drf-addons
|
101Loop_drf-addons/tests/test_utils.py
|
test_utils.TestUtils
|
class TestUtils(TestCase):
def test_validate_email(self):
valid_email = "user@django.com"
invalid_email = "user"
self.assertTrue(validate_email(valid_email))
self.assertFalse(validate_email(invalid_email))
def test_validate_mobile(self):
valid_mobile = "1234567890"
invalid_mobile = "1234567"
self.assertTrue(validate_mobile(valid_mobile))
self.assertFalse(validate_mobile(invalid_mobile))
|
class TestUtils(TestCase):
def test_validate_email(self):
pass
def test_validate_mobile(self):
pass
| 3 | 0 | 6 | 1 | 5 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 14 | 3 | 11 | 7 | 8 | 0 | 11 | 7 | 8 | 1 | 1 | 0 | 2 |
180 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/generics.py
|
drfaddons.generics.RetrieveDestroyByUserAPIView
|
class RetrieveDestroyByUserAPIView(
mixins.RetrieveModelMixin, mixins.DestroyModelMixin, GenericByUserAPIView
):
"""
Concrete view for retrieving or deleting a CreateUpdateModel based
model instance where One-to-One relationship exists on created_by
with User.
"""
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
|
class RetrieveDestroyByUserAPIView(
mixins.RetrieveModelMixin, mixins.DestroyModelMixin, GenericByUserAPIView
):
'''
Concrete view for retrieving or deleting a CreateUpdateModel based
model instance where One-to-One relationship exists on created_by
with User.
'''
def get(self, request, *args, **kwargs):
pass
def delete(self, request, *args, **kwargs):
pass
| 3 | 1 | 2 | 0 | 2 | 0 | 1 | 0.71 | 3 | 0 | 0 | 0 | 2 | 0 | 2 | 3 | 14 | 2 | 7 | 5 | 2 | 5 | 5 | 3 | 2 | 1 | 3 | 0 | 2 |
181 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/generics.py
|
drfaddons.generics.RetrieveByUserAPIView
|
class RetrieveByUserAPIView(mixins.RetrieveModelMixin, GenericByUserAPIView):
"""
Concrete view for retrieving a CreateUpdateModel based model
instance where One-to-One relationship exists on created_by with
User.
"""
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
|
class RetrieveByUserAPIView(mixins.RetrieveModelMixin, GenericByUserAPIView):
'''
Concrete view for retrieving a CreateUpdateModel based model
instance where One-to-One relationship exists on created_by with
User.
'''
def get(self, request, *args, **kwargs):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 1.67 | 2 | 0 | 0 | 0 | 1 | 0 | 1 | 2 | 9 | 1 | 3 | 2 | 1 | 5 | 3 | 2 | 1 | 1 | 3 | 0 | 1 |
182 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/generics.py
|
drfaddons.generics.OwnerUpdateAPIView
|
class OwnerUpdateAPIView(mixins.UpdateModelMixin, OwnerGenericAPIView):
"""Concrete view for updating a CreateUpdateModel based model instance."""
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
return self.partial_update(request, *args, **kwargs)
|
class OwnerUpdateAPIView(mixins.UpdateModelMixin, OwnerGenericAPIView):
'''Concrete view for updating a CreateUpdateModel based model instance.'''
def put(self, request, *args, **kwargs):
pass
def patch(self, request, *args, **kwargs):
pass
| 3 | 1 | 2 | 0 | 2 | 0 | 1 | 0.2 | 2 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 8 | 2 | 5 | 3 | 2 | 1 | 5 | 3 | 2 | 1 | 2 | 0 | 2 |
183 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/generics.py
|
drfaddons.generics.OwnerRetrieveUpdateDestroyAPIView
|
class OwnerRetrieveUpdateDestroyAPIView(
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
OwnerGenericAPIView,
):
"""
Concrete view for retrieving, updating or deleting a
CreateUpdateModel based model instance.
"""
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
return self.partial_update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
|
class OwnerRetrieveUpdateDestroyAPIView(
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
OwnerGenericAPIView,
):
'''
Concrete view for retrieving, updating or deleting a
CreateUpdateModel based model instance.
'''
def get(self, request, *args, **kwargs):
pass
def put(self, request, *args, **kwargs):
pass
def patch(self, request, *args, **kwargs):
pass
def delete(self, request, *args, **kwargs):
pass
| 5 | 1 | 2 | 0 | 2 | 0 | 1 | 0.29 | 4 | 0 | 0 | 0 | 4 | 0 | 4 | 4 | 22 | 4 | 14 | 10 | 4 | 4 | 9 | 5 | 4 | 1 | 2 | 0 | 4 |
184 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/generics.py
|
drfaddons.generics.OwnerRetrieveUpdateAPIView
|
class OwnerRetrieveUpdateAPIView(
mixins.RetrieveModelMixin, mixins.UpdateModelMixin, OwnerGenericAPIView
):
"""
Concrete view for retrieving, updating a CreateUpdateModel based
model instance.
"""
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
return self.partial_update(request, *args, **kwargs)
|
class OwnerRetrieveUpdateAPIView(
mixins.RetrieveModelMixin, mixins.UpdateModelMixin, OwnerGenericAPIView
):
'''
Concrete view for retrieving, updating a CreateUpdateModel based
model instance.
'''
def get(self, request, *args, **kwargs):
pass
def put(self, request, *args, **kwargs):
pass
def patch(self, request, *args, **kwargs):
pass
| 4 | 1 | 2 | 0 | 2 | 0 | 1 | 0.44 | 3 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 16 | 3 | 9 | 6 | 3 | 4 | 7 | 4 | 3 | 1 | 2 | 0 | 3 |
185 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/generics.py
|
drfaddons.generics.OwnerRetrieveDestroyAPIView
|
class OwnerRetrieveDestroyAPIView(
mixins.RetrieveModelMixin, mixins.DestroyModelMixin, OwnerGenericAPIView
):
"""
Concrete view for retrieving or deleting a CreateUpdateModel based
model instance.
"""
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
|
class OwnerRetrieveDestroyAPIView(
mixins.RetrieveModelMixin, mixins.DestroyModelMixin, OwnerGenericAPIView
):
'''
Concrete view for retrieving or deleting a CreateUpdateModel based
model instance.
'''
def get(self, request, *args, **kwargs):
pass
def delete(self, request, *args, **kwargs):
pass
| 3 | 1 | 2 | 0 | 2 | 0 | 1 | 0.57 | 3 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 13 | 2 | 7 | 5 | 2 | 4 | 5 | 3 | 2 | 1 | 2 | 0 | 2 |
186 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/generics.py
|
drfaddons.generics.CreateRetrieveUpdateDestroyByUserAPIView
|
class CreateRetrieveUpdateDestroyByUserAPIView(
OwnerCreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
GenericByUserAPIView,
):
"""
Concrete view for adding, retrieving, updating or deleting a
CreateUpdateModel based model instance where One-to-One
relationship exists on created_by with User.
"""
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
return self.partial_update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
|
class CreateRetrieveUpdateDestroyByUserAPIView(
OwnerCreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
GenericByUserAPIView,
):
'''
Concrete view for adding, retrieving, updating or deleting a
CreateUpdateModel based model instance where One-to-One
relationship exists on created_by with User.
'''
def get(self, request, *args, **kwargs):
pass
def post(self, request, *args, **kwargs):
pass
def put(self, request, *args, **kwargs):
pass
def patch(self, request, *args, **kwargs):
pass
def delete(self, request, *args, **kwargs):
pass
| 6 | 1 | 2 | 0 | 2 | 0 | 1 | 0.29 | 5 | 0 | 0 | 0 | 5 | 0 | 5 | 7 | 27 | 5 | 17 | 12 | 5 | 5 | 11 | 6 | 5 | 1 | 3 | 0 | 5 |
187 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/generics.py
|
drfaddons.generics.OwnerListCreateAPIView
|
class OwnerListCreateAPIView(
mixins.ListModelMixin, OwnerCreateModelMixin, OwnerGenericAPIView
):
"""
Concrete view for listing a queryset or creating a
CreateUpdateModel based model instance.
"""
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
|
class OwnerListCreateAPIView(
mixins.ListModelMixin, OwnerCreateModelMixin, OwnerGenericAPIView
):
'''
Concrete view for listing a queryset or creating a
CreateUpdateModel based model instance.
'''
def get(self, request, *args, **kwargs):
pass
def post(self, request, *args, **kwargs):
pass
| 3 | 1 | 2 | 0 | 2 | 0 | 1 | 0.57 | 3 | 0 | 0 | 0 | 2 | 0 | 2 | 3 | 13 | 2 | 7 | 5 | 2 | 4 | 5 | 3 | 2 | 1 | 2 | 0 | 2 |
188 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/filters.py
|
drfaddons.filters.IsOwnerOrSuperuser
|
class IsOwnerOrSuperuser(IsOwnerFilterBackend):
"""
Filters data as per ownership, is user is not a superuser
Author: Himanshu Shankar (https://himanshus.com)
"""
def filter_queryset(self, request, queryset, view):
if not request.user.is_superuser:
return super(IsOwnerOrSuperuser, self).filter_queryset(
request=request, queryset=request, view=view
)
return queryset
|
class IsOwnerOrSuperuser(IsOwnerFilterBackend):
'''
Filters data as per ownership, is user is not a superuser
Author: Himanshu Shankar (https://himanshus.com)
'''
def filter_queryset(self, request, queryset, view):
pass
| 2 | 1 | 6 | 0 | 6 | 0 | 2 | 0.57 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 2 | 13 | 2 | 7 | 2 | 5 | 4 | 5 | 2 | 3 | 2 | 2 | 1 | 2 |
189 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/auth.py
|
drfaddons.auth.CsrfExemptSessionAuthentication
|
class CsrfExemptSessionAuthentication(SessionAuthentication):
"""
As the name suggests, it is used for CSRF Exemption. Alternative to
@csrf_exempt
Source: https://stackoverflow.com/a/30875830
"""
def enforce_csrf(self, request):
return
|
class CsrfExemptSessionAuthentication(SessionAuthentication):
'''
As the name suggests, it is used for CSRF Exemption. Alternative to
@csrf_exempt
Source: https://stackoverflow.com/a/30875830
'''
def enforce_csrf(self, request):
pass
| 2 | 1 | 2 | 0 | 2 | 1 | 1 | 2 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 9 | 1 | 3 | 2 | 1 | 6 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
190 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/auth.py
|
drfaddons.auth.JSONWebTokenAuthenticationQS
|
class JSONWebTokenAuthenticationQS(BaseJSONWebTokenAuthentication):
"""
This is a custom JWT Authentication class. This has inherited
BaseJsonWebTokenAuthentication and also used some of the codes from
traditional JSONWebTokenAuthentication class. The traditional one
can only authenticate from Header with a specific key only.
This model will first look into HEADER and if the key is not found
there, it looks for key in the body.
Key is also changeable and can be set in Django settings as
JWT_AUTH_KEY with default value of Authorization.
Source: Himanshu Shankar (https://github.com/iamhssingh)
"""
from rest_framework_jwt.settings import api_settings
from django.conf import settings
key = getattr(settings, "JWT_AUTH_KEY", "Authorization")
header_key = "HTTP_" + key.upper()
prefix = api_settings.JWT_AUTH_HEADER_PREFIX
cookie = api_settings.JWT_AUTH_COOKIE
def get_authorization(self, request):
"""
This function extracts the authorization JWT string. It first
looks for specified key in header and then looks
for the same in body part.
Parameters
----------
request: HttpRequest
This is the raw request that user has sent.
Returns
-------
auth: str
Return request's 'JWT_AUTH_KEY:' content from body or
Header, as a bytestring.
Hide some test client ickyness where the header can be unicode.
"""
from six import text_type
from rest_framework import HTTP_HEADER_ENCODING
auth = request.META.get(self.header_key, b"")
if isinstance(auth, text_type):
# Work around django test client oddness
auth = auth.encode(HTTP_HEADER_ENCODING)
return auth
def get_jwt_value(self, request):
"""
This function has been overloaded and it returns the proper JWT
auth string.
Parameters
----------
request: HttpRequest
This is the request that is received by DJango in the view.
Returns
-------
str
This returns the extracted JWT auth token string.
"""
from django.utils.encoding import smart_text
from django.utils.translation import ugettext as _
from rest_framework import exceptions
auth = self.get_authorization(request).split()
auth_header_prefix = self.prefix.lower() or ""
if not auth:
if self.cookie:
return request.COOKIES.get(self.cookie)
return None
if auth_header_prefix is None or len(auth_header_prefix) < 1:
auth.append("")
auth.reverse()
if smart_text(auth[0].lower()) != auth_header_prefix:
return None
if len(auth) == 1:
msg = _("Invalid Authorization header. No credentials provided.")
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = _(
"Invalid Authorization header. Credentials string "
"should not contain spaces."
)
raise exceptions.AuthenticationFailed(msg)
return auth[1]
|
class JSONWebTokenAuthenticationQS(BaseJSONWebTokenAuthentication):
'''
This is a custom JWT Authentication class. This has inherited
BaseJsonWebTokenAuthentication and also used some of the codes from
traditional JSONWebTokenAuthentication class. The traditional one
can only authenticate from Header with a specific key only.
This model will first look into HEADER and if the key is not found
there, it looks for key in the body.
Key is also changeable and can be set in Django settings as
JWT_AUTH_KEY with default value of Authorization.
Source: Himanshu Shankar (https://github.com/iamhssingh)
'''
def get_authorization(self, request):
'''
This function extracts the authorization JWT string. It first
looks for specified key in header and then looks
for the same in body part.
Parameters
----------
request: HttpRequest
This is the raw request that user has sent.
Returns
-------
auth: str
Return request's 'JWT_AUTH_KEY:' content from body or
Header, as a bytestring.
Hide some test client ickyness where the header can be unicode.
'''
pass
def get_jwt_value(self, request):
'''
This function has been overloaded and it returns the proper JWT
auth string.
Parameters
----------
request: HttpRequest
This is the request that is received by DJango in the view.
Returns
-------
str
This returns the extracted JWT auth token string.
'''
pass
| 3 | 3 | 37 | 7 | 16 | 14 | 5 | 1 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 97 | 19 | 39 | 18 | 29 | 39 | 35 | 18 | 25 | 7 | 1 | 2 | 9 |
191 |
101Loop/drf-addons
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/101Loop_drf-addons/drfaddons/views.py
|
drfaddons.views.ValidateAndPerformView.Meta
|
class Meta:
abstract = True
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
192 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/filters.py
|
drfaddons.filters.IsOwnerFilterBackend
|
class IsOwnerFilterBackend(BaseFilterBackend):
"""
Filters data as per ownership
Source: http://www.django-rest-framework.org/api-guide/filtering/
"""
def filter_queryset(self, request, queryset, view):
return queryset.filter(created_by=request.user)
|
class IsOwnerFilterBackend(BaseFilterBackend):
'''
Filters data as per ownership
Source: http://www.django-rest-framework.org/api-guide/filtering/
'''
def filter_queryset(self, request, queryset, view):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 1.33 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | 1 | 8 | 1 | 3 | 2 | 1 | 4 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
193 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/generics.py
|
drfaddons.generics.RetrieveUpdateDestroyByUserAPIView
|
class RetrieveUpdateDestroyByUserAPIView(
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
GenericByUserAPIView,
):
"""
Concrete view for retrieving, updating or deleting a
CreateUpdateModel based model instance where One-to-One
relationship exists on created_by with User.
"""
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
return self.partial_update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
|
class RetrieveUpdateDestroyByUserAPIView(
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
GenericByUserAPIView,
):
'''
Concrete view for retrieving, updating or deleting a
CreateUpdateModel based model instance where One-to-One
relationship exists on created_by with User.
'''
def get(self, request, *args, **kwargs):
pass
def put(self, request, *args, **kwargs):
pass
def patch(self, request, *args, **kwargs):
pass
def delete(self, request, *args, **kwargs):
pass
| 5 | 1 | 2 | 0 | 2 | 0 | 1 | 0.36 | 4 | 0 | 0 | 0 | 4 | 0 | 4 | 5 | 23 | 4 | 14 | 10 | 4 | 5 | 9 | 5 | 4 | 1 | 3 | 0 | 4 |
194 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/admin.py
|
drfaddons.admin.CreateUpdateAdmin
|
class CreateUpdateAdmin(InlineCreateUpdateAdminMixin, admin.ModelAdmin):
"""
An Admin interface for models using CreateUpdateModel.
Sets `created_by`, `create_date`, & `update_date` to readonly.
If `created_by` is readonly in the form, it sets its value to
current logged in user.
Author: Himanshu Shankar (https://himanshus.com)
"""
readonly_fields = ()
exclude = ()
# Define ownership_info for common attributes across all models
ownership_info = {
"label": "Ownership Info",
"fields": {
"created_by": {"readonly": True},
"create_date": {"readonly": True},
"update_date": {"readonly": True},
},
}
def get_fieldsets(self, request, obj=None):
"""
Add ownership info fields in fieldset with proper separation.
Author: Himanshu Shankar (https://himanshus.com)
"""
fieldsets = list(
super(CreateUpdateAdmin, self).get_fieldsets(request=request, obj=obj)
)
# Create sets for future use
fields = set()
to_add = set()
# Prepare a set of existing fields in fieldset
for fs in fieldsets:
fields = fields.union(fs[1]["fields"])
# Loop over ownership info fields
for k, v in self.ownership_info["fields"].items():
# Check if current model has k attribute
# and field k is not already in fieldset
# and field k has not been excluded
if (
hasattr(self.model, k)
and k not in fields
and (not self.exclude or (self.exclude and k not in self.exclude))
):
# Now, let's hide fields in add form, it will be empty
# Check if readonly property is not True
# or this is an edit form
if ("readonly" in v and not v["readonly"]) or obj:
to_add.add(k)
# If to_add set is not empty, add ownership info to fieldset
if len(to_add) > 0:
fieldsets.append((self.ownership_info["label"], {"fields": tuple(to_add)}))
return tuple(fieldsets)
def get_readonly_fields(self, request, obj=None):
"""
Makes `created_by`, `create_date` & `update_date` readonly when
editing.
Author: Himanshu Shankar (https://himanshus.com)
"""
# Get read only fields from super
fields = list(
super(CreateUpdateAdmin, self).get_readonly_fields(request=request, obj=obj)
)
# Loop over ownership info field
for k, v in self.ownership_info["fields"].items():
# Check if model has k attribute
# and field k is readonly
# and k is not already in fields
# and k is not in excluded field
# (if not checked, form.Meta.exclude has same field twice)
if (
hasattr(self.model, k)
and "readonly" in v
and v["readonly"]
and k not in fields
and (not self.exclude or k not in self.exclude)
):
fields.append(k)
return tuple(fields)
def save_model(self, request, obj, form, change):
"""Given a model instance save it to the database."""
# Check if `created_by` has been excluded and the form is for
# creating a new object.
if (
hasattr(form.Meta.model, "created_by")
and not hasattr(form.base_fields, "created_by")
and not change
):
# Set created_by to current user
obj.created_by = request.user
# Finally, call super
super(CreateUpdateAdmin, self).save_model(
request=request, obj=obj, form=form, change=change
)
|
class CreateUpdateAdmin(InlineCreateUpdateAdminMixin, admin.ModelAdmin):
'''
An Admin interface for models using CreateUpdateModel.
Sets `created_by`, `create_date`, & `update_date` to readonly.
If `created_by` is readonly in the form, it sets its value to
current logged in user.
Author: Himanshu Shankar (https://himanshus.com)
'''
def get_fieldsets(self, request, obj=None):
'''
Add ownership info fields in fieldset with proper separation.
Author: Himanshu Shankar (https://himanshus.com)
'''
pass
def get_readonly_fields(self, request, obj=None):
'''
Makes `created_by`, `create_date` & `update_date` readonly when
editing.
Author: Himanshu Shankar (https://himanshus.com)
'''
pass
def save_model(self, request, obj, form, change):
'''Given a model instance save it to the database.'''
pass
| 4 | 4 | 29 | 4 | 14 | 10 | 4 | 0.72 | 2 | 4 | 0 | 1 | 3 | 0 | 3 | 4 | 112 | 19 | 54 | 14 | 50 | 39 | 27 | 14 | 23 | 6 | 1 | 3 | 11 |
195 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/admin.py
|
drfaddons.admin.CreateUpdateExcludeInlineAdminMixin
|
class CreateUpdateExcludeInlineAdminMixin:
"""
Mixin to exclude ownership fields in Inline Admin based on
CreateUpdate Model
Author: Himanshu Shankar (https://himanshus.com)
"""
exclude = ("created_by", "create_date", "update_date")
|
class CreateUpdateExcludeInlineAdminMixin:
'''
Mixin to exclude ownership fields in Inline Admin based on
CreateUpdate Model
Author: Himanshu Shankar (https://himanshus.com)
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 2.5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 9 | 2 | 2 | 2 | 1 | 5 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
196 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/generics.py
|
drfaddons.generics.RetrieveUpdateByUserAPIView
|
class RetrieveUpdateByUserAPIView(
mixins.RetrieveModelMixin, mixins.UpdateModelMixin, GenericByUserAPIView
):
"""
Concrete view for retrieving, updating a CreateUpdateModel based
model instance where One-to-One relationship exists on created_by
with User.
"""
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def patch(self, request, *args, **kwargs):
return self.partial_update(request, *args, **kwargs)
|
class RetrieveUpdateByUserAPIView(
mixins.RetrieveModelMixin, mixins.UpdateModelMixin, GenericByUserAPIView
):
'''
Concrete view for retrieving, updating a CreateUpdateModel based
model instance where One-to-One relationship exists on created_by
with User.
'''
def get(self, request, *args, **kwargs):
pass
def put(self, request, *args, **kwargs):
pass
def patch(self, request, *args, **kwargs):
pass
| 4 | 1 | 2 | 0 | 2 | 0 | 1 | 0.56 | 3 | 0 | 0 | 0 | 3 | 0 | 3 | 4 | 17 | 3 | 9 | 6 | 3 | 5 | 7 | 4 | 3 | 1 | 3 | 0 | 3 |
197 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/admin.py
|
drfaddons.admin.CreateUpdateReadOnlyInlineAdminMixin
|
class CreateUpdateReadOnlyInlineAdminMixin:
"""
Mixin to set read only fields in Inline Admin based on CreateUpdate
Model
Author: Himanshu Shankar (https://himanshus.com)
"""
readonly_fields = ("created_by", "create_date", "update_date")
|
class CreateUpdateReadOnlyInlineAdminMixin:
'''
Mixin to set read only fields in Inline Admin based on CreateUpdate
Model
Author: Himanshu Shankar (https://himanshus.com)
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 2.5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 9 | 2 | 2 | 2 | 1 | 5 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
198 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/admin.py
|
drfaddons.admin.CreateUpdateHiddenAdmin
|
class CreateUpdateHiddenAdmin(HideModelAdminMixin, CreateUpdateAdmin):
"""
Hidden mode of CreateUpdateAdmin
Author: Himanshu Shankar (https://himanshus.com)
"""
|
class CreateUpdateHiddenAdmin(HideModelAdminMixin, CreateUpdateAdmin):
'''
Hidden mode of CreateUpdateAdmin
Author: Himanshu Shankar (https://himanshus.com)
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 4 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 5 | 6 | 1 | 1 | 1 | 0 | 4 | 1 | 1 | 0 | 0 | 2 | 0 | 0 |
199 |
101Loop/drf-addons
|
101Loop_drf-addons/drfaddons/admin.py
|
drfaddons.admin.InlineCreateUpdateAdminMixin
|
class InlineCreateUpdateAdminMixin:
"""
An Inline mixin that takes care of CreateUpdateModel fields.
Author: Himanshu Shankar (https://himanshus.com)
"""
def save_formset(self, request, form, formset, change):
# Check if created_by is in excluded fields
# Even if created_by is in field, we only need to pick current
# user when the field is excluded. If it's not excluded, admin
# may want to setup created_by manually.
if hasattr(formset.form.Meta.model, "created_by") and not hasattr(
formset.form.base_fields, "created_by"
):
# Perform non-commit save to get objects in formset
formset.save(commit=False)
# Check if any new object is being created
if hasattr(formset, "new_objects"):
for new_object in formset.new_objects:
new_object.created_by = request.user
# Finally, call super function to save object.
super(InlineCreateUpdateAdminMixin, self).save_formset(
request=request, form=form, formset=formset, change=change
)
|
class InlineCreateUpdateAdminMixin:
'''
An Inline mixin that takes care of CreateUpdateModel fields.
Author: Himanshu Shankar (https://himanshus.com)
'''
def save_formset(self, request, form, formset, change):
pass
| 2 | 1 | 20 | 2 | 11 | 7 | 4 | 0.92 | 0 | 1 | 0 | 1 | 1 | 0 | 1 | 1 | 27 | 4 | 12 | 3 | 10 | 11 | 8 | 3 | 6 | 4 | 0 | 3 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.