_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q269300 | report_message | test | def report_message(message, level='error', request=None, extra_data=None, payload_data=None):
"""
Reports an arbitrary string message to Rollbar.
message: the string body of the message
level: level to report at. One of: 'critical', 'error', 'warning', 'info', 'debug'
request: the request object for the context of the message
extra_data: dictionary of params to include with the message. 'body' is reserved.
payload_data: param names to pass in the | python | {
"resource": ""
} |
q269301 | search_items | test | def search_items(title, return_fields=None, access_token=None, endpoint=None, **search_fields):
"""
Searches a project for items that match the input criteria.
title: all or part of the item's title to search for.
return_fields: the fields that should be returned for each item.
e.g. ['id', 'project_id', 'status'] will return a dict containing
only those fields for each item.
access_token: a project access token. If this is not provided,
the one provided to init() will be used instead.
search_fields: additional fields to include in the search.
currently supported: status, level, environment
| python | {
"resource": ""
} |
q269302 | _create_agent_log | test | def _create_agent_log():
"""
Creates .rollbar log file for use with rollbar-agent
"""
log_file = SETTINGS['agent.log_file']
if not log_file.endswith('.rollbar'):
log.error("Provided agent log file does not end with .rollbar, which it must. "
"Using default instead.")
log_file = DEFAULTS['agent.log_file']
| python | {
"resource": ""
} |
q269303 | _build_person_data | test | def _build_person_data(request):
"""
Returns a dictionary describing the logged-in user using data from `request.
Try request.rollbar_person first, then 'user', then 'user_id'
"""
if hasattr(request, 'rollbar_person'):
rollbar_person_prop = request.rollbar_person
try:
person = rollbar_person_prop()
except TypeError:
person = rollbar_person_prop
if person and isinstance(person, dict):
return person
else:
return None
if hasattr(request, 'user'):
user_prop = request.user
try:
user = user_prop()
except TypeError:
user = user_prop
if not user:
return None
elif isinstance(user, dict):
return user
else:
retval = {}
if getattr(user, 'id', None):
retval['id'] = text(user.id)
elif getattr(user, 'user_id', None):
| python | {
"resource": ""
} |
q269304 | _add_lambda_context_data | test | def _add_lambda_context_data(data):
"""
Attempts to add information from the lambda context if it exists
"""
global _CURRENT_LAMBDA_CONTEXT
context = _CURRENT_LAMBDA_CONTEXT
if context is None:
return
try:
lambda_data = {
'lambda': {
'remaining_time_in_millis': context.get_remaining_time_in_millis(),
'function_name': context.function_name,
'function_version': context.function_version,
'arn': context.invoked_function_arn,
'request_id': context.aws_request_id,
| python | {
"resource": ""
} |
q269305 | _add_request_data | test | def _add_request_data(data, request):
"""
Attempts to build request data; if successful, sets the 'request' key on `data`.
"""
try:
request_data = _build_request_data(request)
except Exception as e:
log.exception("Exception while | python | {
"resource": ""
} |
q269306 | _check_add_locals | test | def _check_add_locals(frame, frame_num, total_frames):
"""
Returns True if we should record local variables for the given frame.
"""
# Include the last frames locals
# Include any frame locals that came from a file in the project's | python | {
"resource": ""
} |
q269307 | _build_request_data | test | def _build_request_data(request):
"""
Returns a dictionary containing data from the request.
Can handle webob or werkzeug-based request objects.
"""
# webob (pyramid)
if WebobBaseRequest and isinstance(request, WebobBaseRequest):
return _build_webob_request_data(request)
# django
if DjangoHttpRequest and isinstance(request, DjangoHttpRequest):
return _build_django_request_data(request)
# django rest framework
if RestFrameworkRequest and isinstance(request, RestFrameworkRequest):
return _build_django_request_data(request)
# werkzeug (flask)
if WerkzeugRequest and isinstance(request, WerkzeugRequest):
return _build_werkzeug_request_data(request)
# tornado
if TornadoRequest and isinstance(request, TornadoRequest):
return _build_tornado_request_data(request)
# bottle
if BottleRequest and isinstance(request, BottleRequest):
| python | {
"resource": ""
} |
q269308 | _build_server_data | test | def _build_server_data():
"""
Returns a dictionary containing information about the server environment.
"""
# server environment
server_data = {
'host': socket.gethostname(),
'pid': os.getpid()
}
# argv does not always exist in embedded python environments
argv = getattr(sys, 'argv', None)
| python | {
"resource": ""
} |
q269309 | _build_payload | test | def _build_payload(data):
"""
Returns the full payload as a string.
"""
for k, v in iteritems(data):
data[k] = _transform(v, key=(k,))
payload | python | {
"resource": ""
} |
q269310 | main | test | def main():
rollbar.init('ACCESS_TOKEN', environment='test', handler='twisted')
"""This runs the | python | {
"resource": ""
} |
q269311 | compose | test | def compose(chosung, joongsung, jongsung=u''):
"""This function returns a Hangul letter by composing the specified chosung, joongsung, and jongsung.
@param chosung
@param joongsung
@param jongsung the terminal Hangul letter. This is optional if you do not need a jongsung."""
if jongsung is None: jongsung = u''
try:
chosung_index = CHO.index(chosung)
| python | {
"resource": ""
} |
q269312 | decompose | test | def decompose(hangul_letter):
"""This function returns letters by decomposing the specified Hangul letter."""
from . import checker
if len(hangul_letter) < 1:
raise NotLetterException('')
elif not checker.is_hangul(hangul_letter):
raise NotHangulException('')
if hangul_letter in CHO:
return hangul_letter, '', ''
| python | {
"resource": ""
} |
q269313 | has_jongsung | test | def has_jongsung(letter):
"""Check whether this letter contains Jongsung"""
if len(letter) != 1:
raise Exception('The target string must be one letter.')
if not is_hangul(letter):
| python | {
"resource": ""
} |
q269314 | attach | test | def attach(word, josa=EUN_NEUN):
"""add josa at the end of this word"""
last_letter = word.strip()[-1]
try:
_, _, letter_jong = letter.decompose(last_letter)
| python | {
"resource": ""
} |
q269315 | is_inside_except | test | def is_inside_except(node):
"""Returns true if node is inside the name of an except handler."""
current = node
while current and not | python | {
"resource": ""
} |
q269316 | is_inside_lambda | test | def is_inside_lambda(node: astroid.node_classes.NodeNG) -> bool:
"""Return true if given node is inside lambda"""
parent = node.parent
while parent is not None:
| python | {
"resource": ""
} |
q269317 | get_all_elements | test | def get_all_elements(
node: astroid.node_classes.NodeNG
) -> Iterable[astroid.node_classes.NodeNG]:
"""Recursively returns all atoms in nested lists and tuples."""
if isinstance(node, (astroid.Tuple, astroid.List)):
| python | {
"resource": ""
} |
q269318 | clobber_in_except | test | def clobber_in_except(
node: astroid.node_classes.NodeNG
) -> Tuple[bool, Tuple[str, str]]:
"""Checks if an assignment node in an except handler clobbers an existing
variable.
Returns (True, args for W0623) if assignment clobbers an existing variable,
(False, None) otherwise.
"""
if isinstance(node, astroid.AssignAttr):
| python | {
"resource": ""
} |
q269319 | is_super | test | def is_super(node: astroid.node_classes.NodeNG) -> bool:
"""return True if the node is referencing the "super" | python | {
"resource": ""
} |
q269320 | is_error | test | def is_error(node: astroid.node_classes.NodeNG) -> bool:
"""return true if the function does nothing but raising an exception"""
for child_node in node.get_children():
| python | {
"resource": ""
} |
q269321 | is_default_argument | test | def is_default_argument(node: astroid.node_classes.NodeNG) -> bool:
"""return true if the given Name node is used in function or lambda
default argument's value
"""
parent = node.scope()
| python | {
"resource": ""
} |
q269322 | is_func_decorator | test | def is_func_decorator(node: astroid.node_classes.NodeNG) -> bool:
"""return true if the name is used in function decorator"""
parent = node.parent
while parent is not None:
if isinstance(parent, astroid.Decorators):
return True
if parent.is_statement or isinstance(
| python | {
"resource": ""
} |
q269323 | is_ancestor_name | test | def is_ancestor_name(
frame: astroid.node_classes.NodeNG, node: astroid.node_classes.NodeNG
) -> bool:
"""return True if `frame` is an astroid.Class node with `node` in the
subtree of its bases attribute
"""
try:
bases = frame.bases
| python | {
"resource": ""
} |
q269324 | assign_parent | test | def assign_parent(node: astroid.node_classes.NodeNG) -> astroid.node_classes.NodeNG:
"""return the higher parent which is not an AssignName, Tuple or List node
"""
while | python | {
"resource": ""
} |
q269325 | check_messages | test | def check_messages(*messages: str) -> Callable:
"""decorator to store messages that are handled by a checker method"""
def store_messages(func):
| python | {
"resource": ""
} |
q269326 | collect_string_fields | test | def collect_string_fields(format_string) -> Iterable[Optional[str]]:
""" Given a format string, return an iterator
of all the valid format fields. It handles nested fields
as well.
"""
formatter = string.Formatter()
try:
parseiterator = formatter.parse(format_string)
for result in parseiterator:
if all(item is None for item in result[1:]):
# not a replacement format
continue
name = result[1]
nested = result[2]
| python | {
"resource": ""
} |
q269327 | get_argument_from_call | test | def get_argument_from_call(
call_node: astroid.Call, position: int = None, keyword: str = None
) -> astroid.Name:
"""Returns the specified argument from a function call.
:param astroid.Call call_node: Node representing a function call to check.
:param int position: position of the argument.
:param str keyword: the keyword of the argument.
:returns: The node representing the argument, None if the argument is not found.
:rtype: astroid.Name
:raises ValueError: if both position and keyword are None.
:raises NoSuchArgumentError: if no argument at the provided position or with
the provided keyword.
"""
if position is None and keyword is None:
raise ValueError("Must specify at | python | {
"resource": ""
} |
q269328 | inherit_from_std_ex | test | def inherit_from_std_ex(node: astroid.node_classes.NodeNG) -> bool:
"""
Return true if the given class node is subclass of
exceptions.Exception.
"""
ancestors = node.ancestors() if hasattr(node, "ancestors") else []
for ancestor in itertools.chain([node], ancestors):
if (
| python | {
"resource": ""
} |
q269329 | error_of_type | test | def error_of_type(handler: astroid.ExceptHandler, error_type) -> bool:
"""
Check if the given exception handler catches
the given error_type.
The *handler* parameter is a node, representing an ExceptHandler node.
The *error_type* can be an exception, such as AttributeError,
the name of an exception, or it can be a tuple of errors.
The function will return True if the handler catches any of the
given errors.
"""
def stringify_error(error):
if not isinstance(error, str):
return error.__name__
return | python | {
"resource": ""
} |
q269330 | decorated_with_property | test | def decorated_with_property(node: astroid.FunctionDef) -> bool:
""" Detect if the given function node is decorated with a property. """
if not node.decorators:
return False
for decorator in node.decorators.nodes:
if not isinstance(decorator, astroid.Name):
continue
| python | {
"resource": ""
} |
q269331 | decorated_with | test | def decorated_with(func: astroid.FunctionDef, qnames: Iterable[str]) -> bool:
"""Determine if the `func` node has a decorator with the qualified name `qname`."""
decorators = func.decorators.nodes if func.decorators else []
for decorator_node in decorators:
try:
if any(
| python | {
"resource": ""
} |
q269332 | find_try_except_wrapper_node | test | def find_try_except_wrapper_node(
node: astroid.node_classes.NodeNG
) -> Union[astroid.ExceptHandler, astroid.TryExcept]:
"""Return the ExceptHandler or the TryExcept node in which the node is."""
current = node
ignores = (astroid.ExceptHandler, astroid.TryExcept)
| python | {
"resource": ""
} |
q269333 | is_from_fallback_block | test | def is_from_fallback_block(node: astroid.node_classes.NodeNG) -> bool:
"""Check if the given node is from a fallback import block."""
context = find_try_except_wrapper_node(node)
if not context:
return False
if isinstance(context, astroid.ExceptHandler):
other_body = context.parent.body
handlers = context.parent.handlers
else:
other_body = itertools.chain.from_iterable(
handler.body for handler in context.handlers
)
handlers = context.handlers
has_fallback_imports = any(
| python | {
"resource": ""
} |
q269334 | get_exception_handlers | test | def get_exception_handlers(
node: astroid.node_classes.NodeNG, exception=Exception
) -> List[astroid.ExceptHandler]:
"""Return the collections of handlers handling the exception in arguments.
Args:
node (astroid.NodeNG): A node that is potentially wrapped in a try except.
exception (builtin.Exception or str): exception or name of the exception.
Returns:
list: the collection | python | {
"resource": ""
} |
q269335 | node_ignores_exception | test | def node_ignores_exception(
node: astroid.node_classes.NodeNG, exception=Exception
) -> bool:
"""Check if the node is in a TryExcept which handles the given exception.
| python | {
"resource": ""
} |
q269336 | class_is_abstract | test | def class_is_abstract(node: astroid.ClassDef) -> bool:
"""return true if the given class node should be considered as an abstract
| python | {
"resource": ""
} |
q269337 | safe_infer | test | def safe_infer(
node: astroid.node_classes.NodeNG, context=None
) -> Optional[astroid.node_classes.NodeNG]:
"""Return the inferred value for the given node.
Return None if inference failed or if there is some ambiguity (more than
one node has been inferred).
| python | {
"resource": ""
} |
q269338 | node_type | test | def node_type(node: astroid.node_classes.NodeNG) -> Optional[type]:
"""Return the inferred type for `node`
If there is more than one possible type, or if inferred type is Uninferable or None,
return None
"""
# check there is only one possible type for the assign node. Else | python | {
"resource": ""
} |
q269339 | is_registered_in_singledispatch_function | test | def is_registered_in_singledispatch_function(node: astroid.FunctionDef) -> bool:
"""Check if the given function node is a singledispatch function."""
singledispatch_qnames = (
"functools.singledispatch",
"singledispatch.singledispatch",
)
if not isinstance(node, astroid.FunctionDef):
return False
decorators = node.decorators.nodes if node.decorators else []
for decorator in decorators:
# func.register are function calls
if not isinstance(decorator, astroid.Call):
continue
func = decorator.func
if not isinstance(func, astroid.Attribute) or func.attrname != "register":
| python | {
"resource": ""
} |
q269340 | is_postponed_evaluation_enabled | test | def is_postponed_evaluation_enabled(node: astroid.node_classes.NodeNG) -> bool:
"""Check if the postponed evaluation of annotations is enabled"""
| python | {
"resource": ""
} |
q269341 | _qualified_names | test | def _qualified_names(modname):
"""Split the names of the given module into subparts
For example,
_qualified_names('pylint.checkers.ImportsChecker')
| python | {
"resource": ""
} |
q269342 | _get_import_name | test | def _get_import_name(importnode, modname):
"""Get a prepared module name from the given import node
In the case of relative imports, this will return the
absolute qualified module name, which might be useful
for debugging. Otherwise, the initial module name
is returned unchanged.
"""
if isinstance(importnode, astroid.ImportFrom):
if importnode.level:
| python | {
"resource": ""
} |
q269343 | _repr_tree_defs | test | def _repr_tree_defs(data, indent_str=None):
"""return a string which represents imports as a tree"""
lines = []
nodes = data.items()
for i, (mod, (sub, files)) in enumerate(sorted(nodes, key=lambda x: x[0])):
if not files:
files = ""
else:
files = "(%s)" % ",".join(sorted(files))
if indent_str is None:
lines.append("%s %s" % (mod, files))
sub_indent_str = " "
else:
lines.append(r"%s\-%s %s" % (indent_str, mod, files)) | python | {
"resource": ""
} |
q269344 | _make_graph | test | def _make_graph(filename, dep_info, sect, gtype):
"""generate a dependencies graph and add some information about it in the
report's section
"""
| python | {
"resource": ""
} |
q269345 | ImportsChecker.visit_import | test | def visit_import(self, node):
"""triggered when an import statement is seen"""
self._check_reimport(node)
self._check_import_as_rename(node)
modnode = node.root()
names = [name for name, _ in node.names]
if len(names) >= 2:
self.add_message("multiple-imports", args=", ".join(names), node=node)
for name in names:
self._check_deprecated_module(node, name)
self._check_preferred_module(node, name)
imported_module = self._get_imported_module(node, name)
if isinstance(node.parent, astroid.Module):
# Allow imports nested
| python | {
"resource": ""
} |
q269346 | ImportsChecker.visit_importfrom | test | def visit_importfrom(self, node):
"""triggered when a from statement is seen"""
basename = node.modname
imported_module = self._get_imported_module(node, basename)
self._check_import_as_rename(node)
self._check_misplaced_future(node)
self._check_deprecated_module(node, basename)
self._check_preferred_module(node, basename)
self._check_wildcard_imports(node, imported_module)
self._check_same_line_imports(node)
self._check_reimport(node, basename=basename, level=node.level)
if isinstance(node.parent, astroid.Module):
# Allow imports nested
self._check_position(node)
if isinstance(node.scope(), astroid.Module):
| python | {
"resource": ""
} |
q269347 | ImportsChecker._check_position | test | def _check_position(self, node):
"""Check `node` import or importfrom node position is correct
Send a message if `node` comes before another instruction
"""
# if a first non-import instruction has already been encountered,
# it means the import comes after it and therefore is not | python | {
"resource": ""
} |
q269348 | ImportsChecker._record_import | test | def _record_import(self, node, importedmodnode):
"""Record the package `node` imports from"""
if isinstance(node, astroid.ImportFrom):
importedname = node.modname
else:
importedname = importedmodnode.name if importedmodnode else None
if not importedname:
importedname = node.names[0][0].split(".")[0]
if isinstance(node, astroid.ImportFrom) and (node.level or 0) >= 1:
# We need the importedname with first point to detect local package
# Example of node:
# 'from .my_package1 import MyClass1'
| python | {
"resource": ""
} |
q269349 | ImportsChecker._check_imports_order | test | def _check_imports_order(self, _module_node):
"""Checks imports of module `node` are grouped by category
Imports must follow this order: standard, 3rd party, local
"""
std_imports = []
third_party_imports = []
first_party_imports = []
# need of a list that holds third or first party ordered import
external_imports = []
local_imports = []
third_party_not_ignored = []
first_party_not_ignored = []
local_not_ignored = []
isort_obj = isort.SortImports(
file_contents="",
known_third_party=self.config.known_third_party,
known_standard_library=self.config.known_standard_library,
)
for node, modname in self._imports_stack:
if modname.startswith("."):
package = "." + modname.split(".")[1]
else:
package = modname.split(".")[0]
nested = not isinstance(node.parent, astroid.Module)
ignore_for_import_order = not self.linter.is_message_enabled(
"wrong-import-order", node.fromlineno
)
import_category = isort_obj.place_module(package)
node_and_package_import = (node, package)
if import_category in ("FUTURE", "STDLIB"):
std_imports.append(node_and_package_import)
wrong_import = (
third_party_not_ignored
or first_party_not_ignored
or local_not_ignored
)
if self._is_fallback_import(node, wrong_import):
| python | {
"resource": ""
} |
q269350 | ImportsChecker._check_relative_import | test | def _check_relative_import(
self, modnode, importnode, importedmodnode, importedasname
):
"""check relative import. node is either an Import or From node, modname
the imported module name.
"""
if not self.linter.is_message_enabled("relative-import"):
return None
if importedmodnode.file is None:
return False # built-in module
if modnode is importedmodnode:
return False # module importing itself
if modnode.absolute_import_activated() or getattr(importnode, "level", None):
return False
| python | {
"resource": ""
} |
q269351 | ImportsChecker._add_imported_module | test | def _add_imported_module(self, node, importedmodname):
"""notify an imported module, used to analyze dependencies"""
module_file = node.root().file
context_name = node.root().name
base = os.path.splitext(os.path.basename(module_file))[0]
try:
importedmodname = astroid.modutils.get_module_part(
importedmodname, module_file
)
except ImportError:
pass
if context_name == importedmodname:
self.add_message("import-self", node=node)
elif not astroid.modutils.is_standard_module(importedmodname):
# if this is not a package __init__ module
if base != "__init__" and context_name not in self._module_pkg:
# record the module's parent, or the module itself if this is
# a top level module, as the package it belongs to
self._module_pkg[context_name] = context_name.rsplit(".", 1)[0]
# handle dependencies
importedmodnames | python | {
"resource": ""
} |
q269352 | ImportsChecker._check_deprecated_module | test | def _check_deprecated_module(self, node, mod_path):
"""check if the module is deprecated"""
for mod_name in self.config.deprecated_modules:
| python | {
"resource": ""
} |
q269353 | ImportsChecker._check_preferred_module | test | def _check_preferred_module(self, node, mod_path):
"""check if the module has a preferred replacement"""
if mod_path in self.preferred_modules:
self.add_message(
"preferred-module",
| python | {
"resource": ""
} |
q269354 | ImportsChecker._report_external_dependencies | test | def _report_external_dependencies(self, sect, _, _dummy):
"""return a verbatim layout for displaying dependencies"""
dep_info = _make_tree_defs(self._external_dependencies_info().items())
if not dep_info:
| python | {
"resource": ""
} |
q269355 | ImportsChecker._filter_dependencies_graph | test | def _filter_dependencies_graph(self, internal):
"""build the internal or the external depedency graph"""
graph = collections.defaultdict(set)
for importee, importers in self.stats["dependencies"].items():
for importer in importers:
package = self._module_pkg.get(importer, importer) | python | {
"resource": ""
} |
q269356 | get_default_options | test | def get_default_options():
"""
Read config file and return list of options
"""
options = []
home = os.environ.get("HOME", "")
if home:
rcfile = os.path.join(home, RCFILE)
try:
| python | {
"resource": ""
} |
q269357 | insert_default_options | test | def insert_default_options():
"""insert default options to sys.argv
"""
options = get_default_options()
| python | {
"resource": ""
} |
q269358 | FilterMixIn.show_attr | test | def show_attr(self, node):
"""return true if the node should be treated
| python | {
"resource": ""
} |
q269359 | ASTWalker.get_callbacks | test | def get_callbacks(self, node):
"""get callbacks from handler for the visited node"""
klass = node.__class__
methods = self._cache.get(klass)
if methods is None:
handler = self.handler
kid = klass.__name__.lower()
e_method = getattr(
handler, "visit_%s" % kid, getattr(handler, "visit_default", None)
)
l_method = getattr(
| python | {
"resource": ""
} |
q269360 | LocalsVisitor.visit | test | def visit(self, node):
"""launch the visit starting from the given node"""
if node in self._visited:
return None
self._visited[node] = 1 # FIXME: use set ?
methods = self.get_callbacks(node)
if methods[0] is not None:
methods[0](node)
if hasattr(node, | python | {
"resource": ""
} |
q269361 | BaseChecker.check_consistency | test | def check_consistency(self) -> None:
"""Check the consistency of msgid.
msg ids for a checker should be a string of len 4, where the two first
characters are the checker id and the two last the msg id in this
checker.
:raises InvalidMessageError: If the checker id in the messages are not
always the same. """
checker_id = None
existing_ids = []
for message in self.messages:
if checker_id is not None and checker_id != message.msgid[1:3]:
error_msg = "Inconsistent checker part in message id "
| python | {
"resource": ""
} |
q269362 | StdlibChecker.visit_call | test | def visit_call(self, node):
"""Visit a Call node."""
try:
for inferred in node.func.infer():
if inferred is astroid.Uninferable:
continue
elif inferred.root().name == OPEN_MODULE:
if getattr(node.func, "name", None) in OPEN_FILES:
self._check_open_mode(node)
elif inferred.root().name == UNITTEST_CASE:
self._check_redundant_assert(node, inferred)
elif isinstance(inferred, astroid.ClassDef):
if inferred.qname() == THREADING_THREAD:
self._check_bad_thread_instantiation(node)
elif inferred.qname() == SUBPROCESS_POPEN:
self._check_for_preexec_fn_in_popen(node)
elif isinstance(inferred, astroid.FunctionDef):
name = inferred.qname()
| python | {
"resource": ""
} |
q269363 | StdlibChecker._check_datetime | test | def _check_datetime(self, node):
""" Check that a datetime was infered.
If so, emit boolean-datetime warning.
"""
try:
infered = next(node.infer())
except astroid.InferenceError:
return
| python | {
"resource": ""
} |
q269364 | StdlibChecker._check_open_mode | test | def _check_open_mode(self, node):
"""Check that the mode argument of an open or file call is valid."""
try:
mode_arg = utils.get_argument_from_call(node, position=1, keyword="mode")
except utils.NoSuchArgumentError:
return
if mode_arg:
| python | {
"resource": ""
} |
q269365 | JSONReporter.handle_message | test | def handle_message(self, msg):
"""Manage message of different type and in the context of path."""
self.messages.append(
{
"type": msg.category,
"module": msg.module,
"obj": msg.obj,
"line": msg.line,
"column": msg.column,
"path": msg.path,
| python | {
"resource": ""
} |
q269366 | JSONReporter.display_messages | test | def display_messages(self, layout):
"""Launch layouts display"""
| python | {
"resource": ""
} |
q269367 | DiaDefGenerator.get_title | test | def get_title(self, node):
"""get title for objects"""
title = node.name
if self.module_names:
| python | {
"resource": ""
} |
q269368 | DiaDefGenerator._set_default_options | test | def _set_default_options(self):
"""set different default options with _default dictionary"""
self.module_names = self._set_option(self.config.module_names)
all_ancestors = self._set_option(self.config.all_ancestors)
all_associated = self._set_option(self.config.all_associated)
anc_level, association_level = (0, 0)
if all_ancestors:
anc_level = -1
if all_associated:
association_level = -1
if self.config.show_ancestors | python | {
"resource": ""
} |
q269369 | DiaDefGenerator.show_node | test | def show_node(self, node):
"""true if builtins and not show_builtins"""
if self.config.show_builtin:
| python | {
"resource": ""
} |
q269370 | DiaDefGenerator.add_class | test | def add_class(self, node):
"""visit one class and add it to diagram"""
| python | {
"resource": ""
} |
q269371 | DiaDefGenerator.get_ancestors | test | def get_ancestors(self, node, level):
"""return ancestor nodes of a class node"""
if level == 0:
return
for ancestor in node.ancestors(recurs=False):
| python | {
"resource": ""
} |
q269372 | DiaDefGenerator.get_associated | test | def get_associated(self, klass_node, level):
"""return associated nodes of a class node"""
if level == 0:
return
for association_nodes in list(klass_node.instance_attrs_type.values()) + list(
| python | {
"resource": ""
} |
q269373 | DiaDefGenerator.extract_classes | test | def extract_classes(self, klass_node, anc_level, association_level):
"""extract recursively classes related to klass_node"""
if self.classdiagram.has_node(klass_node) or not self.show_node(klass_node):
return
self.add_class(klass_node)
for ancestor in self.get_ancestors(klass_node, anc_level):
| python | {
"resource": ""
} |
q269374 | DefaultDiadefGenerator.leave_project | test | def leave_project(self, node): # pylint: disable=unused-argument
"""leave the pyreverse.utils.Project node
| python | {
"resource": ""
} |
q269375 | DefaultDiadefGenerator.visit_importfrom | test | def visit_importfrom(self, node):
"""visit astroid.ImportFrom and catch modules for package diagram
"""
| python | {
"resource": ""
} |
q269376 | ClassDiadefGenerator.class_diagram | test | def class_diagram(self, project, klass):
"""return a class diagram definition for the given klass and its
related klasses
"""
self.classdiagram = ClassDiagram(klass, self.config.mode)
if len(project.modules) > 1:
module, klass = klass.rsplit(".", 1)
module = project.get_module(module)
else:
module = project.modules[0]
klass = klass.split(".")[-1]
| python | {
"resource": ""
} |
q269377 | DiadefsHandler.get_diadefs | test | def get_diadefs(self, project, linker):
"""Get the diagrams configuration data
:param project:The pyreverse project
:type project: pyreverse.utils.Project
:param linker: The linker
:type linker: pyreverse.inspector.Linker(IdGeneratorMixIn, LocalsVisitor)
:returns: The list of diagram definitions
:rtype: | python | {
"resource": ""
} |
q269378 | _is_owner_ignored | test | def _is_owner_ignored(owner, name, ignored_classes, ignored_modules):
"""Check if the given owner should be ignored
This will verify if the owner's module is in *ignored_modules*
or the owner's module fully qualified name is in *ignored_modules*
or if the *ignored_modules* contains a pattern which catches
the fully qualified name of the module.
Also, similar checks are done for the owner itself, if its name
matches any name from the *ignored_classes* or if its qualified
name can be found in *ignored_classes*.
"""
ignored_modules = set(ignored_modules)
module_name = owner.root().name
module_qname = owner.root().qname()
if any(
module_name in ignored_modules
| python | {
"resource": ""
} |
q269379 | _similar_names | test | def _similar_names(owner, attrname, distance_threshold, max_choices):
"""Given an owner and a name, try to find similar names
The similar names are searched given a distance metric and only
a given number of choices will be returned.
"""
possible_names = []
names = _node_names(owner)
for name in names:
if name == attrname:
continue
distance = _string_distance(attrname, name)
if distance <= distance_threshold:
possible_names.append((name, distance))
# Now | python | {
"resource": ""
} |
q269380 | _emit_no_member | test | def _emit_no_member(node, owner, owner_name, ignored_mixins=True, ignored_none=True):
"""Try to see if no-member should be emitted for the given owner.
The following cases are ignored:
* the owner is a function and it has decorators.
* the owner is an instance and it has __getattr__, __getattribute__ implemented
* the module is explicitly ignored from no-member checks
* the owner is a class and the name can be found in its metaclass.
* The access node is protected by an except handler, which handles
AttributeError, Exception or bare except.
"""
# pylint: disable=too-many-return-statements
if node_ignores_exception(node, AttributeError):
return False
if ignored_none and isinstance(owner, astroid.Const) and owner.value is None:
return False
if is_super(owner) or getattr(owner, "type", None) == "metaclass":
return False
if ignored_mixins and owner_name[-5:].lower() == "mixin":
return False
if isinstance(owner, astroid.FunctionDef) and owner.decorators:
return False
if isinstance(owner, | python | {
"resource": ""
} |
q269381 | _has_parent_of_type | test | def _has_parent_of_type(node, node_type, statement):
"""Check if the given node has a parent of the given type."""
| python | {
"resource": ""
} |
q269382 | _is_name_used_as_variadic | test | def _is_name_used_as_variadic(name, variadics):
"""Check if the given name is used as a variadic argument."""
return any(
variadic.value == name | python | {
"resource": ""
} |
q269383 | _no_context_variadic | test | def _no_context_variadic(node, variadic_name, variadic_type, variadics):
"""Verify if the given call node has variadic nodes without context
This is a workaround for handling cases of nested call functions
which don't have the specific call context at hand.
Variadic arguments (variable positional arguments and variable
keyword arguments) are inferred, inherently wrong, by astroid
as a Tuple, respectively a Dict with empty elements.
This can lead pylint to believe that a function call receives
too few arguments.
"""
statement = node.statement() | python | {
"resource": ""
} |
q269384 | TypeChecker.visit_attribute | test | def visit_attribute(self, node):
"""check that the accessed attribute exists
to avoid too much false positives for now, we'll consider the code as
correct if a single of the inferred nodes has the accessed attribute.
function/method, super call and metaclasses are ignored
"""
for pattern in self.config.generated_members:
# attribute is marked as generated, stop here
if re.match(pattern, node.attrname):
return
if re.match(pattern, node.as_string()):
return
try:
inferred = list(node.expr.infer())
except exceptions.InferenceError:
return
# list of (node, nodename) which are missing the attribute
missingattr = set()
non_opaque_inference_results = [
owner
for owner in inferred
if owner is not astroid.Uninferable
and not isinstance(owner, astroid.nodes.Unknown)
]
if (
len(non_opaque_inference_results) != len(inferred)
and self.config.ignore_on_opaque_inference
):
# There is an ambiguity in the inference. Since we can't
# make sure that we won't emit a false positive, we just stop
# whenever the inference returns an opaque inference object.
return
for owner in non_opaque_inference_results:
name = getattr(owner, "name", None)
if _is_owner_ignored(
owner, name, self.config.ignored_classes, self.config.ignored_modules
):
continue
try:
if not [
n
for n in owner.getattr(node.attrname)
if not isinstance(n.statement(), astroid.AugAssign)
]:
missingattr.add((owner, name))
continue
except AttributeError:
# XXX method / function
continue
except exceptions.NotFoundError:
| python | {
"resource": ""
} |
q269385 | TypeChecker.visit_assign | test | def visit_assign(self, node):
"""check that if assigning to a function call, the function is
possibly returning something valuable
"""
if not isinstance(node.value, astroid.Call):
return
function_node = safe_infer(node.value.func)
# skip class, generator and incomplete function definition
funcs = (astroid.FunctionDef, astroid.UnboundMethod, astroid.BoundMethod)
if not (
isinstance(function_node, funcs)
and function_node.root().fully_defined()
and not function_node.decorators
| python | {
"resource": ""
} |
q269386 | TypeChecker._check_uninferable_call | test | def _check_uninferable_call(self, node):
"""
Check that the given uninferable Call node does not
call an actual function.
"""
if not isinstance(node.func, astroid.Attribute):
return
# Look for properties. First, obtain
# the lhs of the Attribute node and search the attribute
# there. If that attribute is a property or a subclass of properties,
# then most likely it's not callable.
# TODO: since astroid doesn't understand descriptors very well
# we will not handle them here, right now.
expr = node.func.expr
klass = safe_infer(expr)
if (
klass is None
or klass is astroid.Uninferable
or not isinstance(klass, astroid.Instance)
):
return
try:
attrs = klass._proxied.getattr(node.func.attrname)
except exceptions.NotFoundError:
return
for attr in attrs:
if attr is astroid.Uninferable:
continue
if not isinstance(attr, astroid.FunctionDef):
| python | {
"resource": ""
} |
q269387 | TypeChecker.visit_unaryop | test | def visit_unaryop(self, node):
"""Detect TypeErrors for unary operands."""
for error in node.type_errors():
# Let the error customize | python | {
"resource": ""
} |
q269388 | interfaces | test | def interfaces(node, herited=True, handler_func=_iface_hdlr):
"""Return an iterator on interfaces implemented by the given class node."""
# FIXME: what if __implements__ = (MyIFace, MyParent.__implements__)...
try:
implements = bases.Instance(node).getattr("__implements__")[0]
except exceptions.NotFoundError:
| python | {
"resource": ""
} |
q269389 | project_from_files | test | def project_from_files(
files, func_wrapper=_astroid_wrapper, project_name="no name", black_list=("CVS",)
):
"""return a Project from a list of files or modules"""
# build the project representation
astroid_manager = manager.AstroidManager()
project = Project(project_name)
for something in files:
if not os.path.exists(something):
fpath = modutils.file_from_modpath(something.split("."))
elif os.path.isdir(something):
fpath = os.path.join(something, "__init__.py")
else:
fpath = something
ast = func_wrapper(astroid_manager.ast_from_file, fpath)
if ast is None:
continue
# XXX why is first file defining the project.path ?
project.path = project.path or ast.file
| python | {
"resource": ""
} |
q269390 | Linker.visit_package | test | def visit_package(self, node):
"""visit an astroid.Package node
* optionally tag the node with a unique id
"""
if self.tag:
node.uid | python | {
"resource": ""
} |
q269391 | Linker.visit_functiondef | test | def visit_functiondef(self, node):
"""visit an astroid.Function node
* set the locals_type mapping
* optionally tag the node with a unique id
"""
if hasattr(node, "locals_type"):
| python | {
"resource": ""
} |
q269392 | Linker.visit_assignname | test | def visit_assignname(self, node):
"""visit an astroid.AssignName node
handle locals_type
"""
# avoid double parsing done by different Linkers.visit
# running over the same project:
if hasattr(node, "_handled"):
return
node._handled = True
if node.name in node.frame():
frame = node.frame()
else:
# the name has been defined as 'global' in the frame and belongs
# there.
frame = node.root()
try:
if not hasattr(frame, "locals_type"):
# If the frame doesn't have a locals_type yet,
# it means it wasn't yet visited. Visit it now
# to add what's missing from it.
if isinstance(frame, astroid.ClassDef):
self.visit_classdef(frame)
| python | {
"resource": ""
} |
q269393 | Linker.handle_assignattr_type | test | def handle_assignattr_type(node, parent):
"""handle an astroid.assignattr node
handle instance_attrs_type
"""
try:
| python | {
"resource": ""
} |
q269394 | Linker.visit_import | test | def visit_import(self, node):
"""visit an astroid.Import node
resolve module dependencies
"""
context_file = node.root().file
for name in node.names:
| python | {
"resource": ""
} |
q269395 | Linker.visit_importfrom | test | def visit_importfrom(self, node):
"""visit an astroid.ImportFrom node
resolve module dependencies
"""
basename = node.modname
context_file = node.root().file
if context_file is not None:
relative = modutils.is_relative(basename, context_file)
else:
relative = False
for name in node.names:
| python | {
"resource": ""
} |
q269396 | Linker.compute_module | test | def compute_module(self, context_name, mod_path):
"""return true if the module should be added to dependencies"""
package_dir = os.path.dirname(self.project.path)
if context_name == mod_path:
| python | {
"resource": ""
} |
q269397 | Linker._imported_module | test | def _imported_module(self, node, mod_path, relative):
"""Notify an imported module, used to analyze dependencies"""
module = node.root()
context_name = module.name
if relative:
mod_path = "%s.%s" % (".".join(context_name.split(".")[:-1]), mod_path)
if self.compute_module(context_name, mod_path):
# handle dependencies
| python | {
"resource": ""
} |
q269398 | _get_ansi_code | test | def _get_ansi_code(color=None, style=None):
"""return ansi escape code corresponding to color and style
:type color: str or None
:param color:
the color name (see `ANSI_COLORS` for available values)
or the color number when 256 colors are available
:type style: str or None
:param style:
style string (see `ANSI_COLORS` for available values). To get
several style effects at the same time, use a coma as separator.
:raise KeyError: if an unexistent color or style identifier is given
:rtype: str
:return: the built escape code
"""
ansi_code = []
if style:
style_attrs = utils._splitstrip(style)
| python | {
"resource": ""
} |
q269399 | colorize_ansi | test | def colorize_ansi(msg, color=None, style=None):
"""colorize message by wrapping it with ansi escape codes
:type msg: str or unicode
:param msg: the message string to colorize
:type color: str or None
:param color:
the color identifier (see `ANSI_COLORS` for available values)
:type style: str or None
:param style:
style string (see `ANSI_COLORS` for available values). To get
several style effects at the same time, use a coma as separator.
:raise KeyError: if an unexistent color or style identifier is given
:rtype: str or unicode
:return: the ansi escaped string
"""
# If both color and style are not | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.